Repository: jayway/powermock Branch: release/2.x Commit: a0be5c4bbeb0 Files: 969 Total size: 2.6 MB Directory structure: gitextract_foq7ud8y/ ├── .github/ │ ├── ISSUE_TEMPLATE.md │ ├── dependabot.yml │ └── workflows/ │ └── gradle-wrapper-validation.yml ├── .gitignore ├── .travis.yml ├── CONTRIBUTING.md ├── LICENSE.txt ├── README.md ├── build.gradle ├── config/ │ └── checkstyle/ │ └── checkstyle.xml ├── docs/ │ ├── changelog.txt │ ├── generate_javadoc.sh │ └── release-notes/ │ └── official.md ├── gradle/ │ ├── java-module.gradle │ ├── modules.gradle │ ├── publishing/ │ │ ├── publish-maven.gradle │ │ ├── publish.gradle │ │ └── publishable-module.gradle │ ├── release/ │ │ ├── distZip.gradle │ │ ├── fullJars.gradle │ │ ├── publish-distZip.gradle │ │ ├── publish-fullJar.gradle │ │ └── publish-jar.gradle │ ├── shipkit.gradle │ ├── version.gradle │ └── wrapper/ │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradle.properties ├── gradlew ├── gradlew.bat ├── powermock-api/ │ ├── powermock-api-easymock/ │ │ └── src/ │ │ └── main/ │ │ └── java/ │ │ └── org/ │ │ └── powermock/ │ │ └── api/ │ │ ├── easymock/ │ │ │ ├── EasyMockConfiguration.java │ │ │ ├── PowerMock.java │ │ │ ├── annotation/ │ │ │ │ ├── Mock.java │ │ │ │ ├── MockNice.java │ │ │ │ └── MockStrict.java │ │ │ ├── internal/ │ │ │ │ ├── invocationcontrol/ │ │ │ │ │ ├── EasyMockMethodInvocationControl.java │ │ │ │ │ ├── EasyMockNewInvocationControl.java │ │ │ │ │ └── NewInvocationControlAssertionError.java │ │ │ │ └── mockstrategy/ │ │ │ │ ├── MockStrategy.java │ │ │ │ └── impl/ │ │ │ │ ├── AbstractMockStrategyBase.java │ │ │ │ ├── DefaultMockStrategy.java │ │ │ │ ├── NiceMockStrategy.java │ │ │ │ └── StrictMockStrategy.java │ │ │ ├── mockpolicies/ │ │ │ │ ├── AbstractEasyMockLogPolicyBase.java │ │ │ │ ├── JclMockPolicy.java │ │ │ │ ├── Log4jMockPolicy.java │ │ │ │ └── Slf4jMockPolicy.java │ │ │ └── powermocklistener/ │ │ │ └── AnnotationEnabler.java │ │ └── extension/ │ │ ├── InjectFieldSearcher.java │ │ ├── agent/ │ │ │ └── JavaAgentFrameworkRegisterImpl.java │ │ └── listener/ │ │ ├── AnnotationEnabler.java │ │ ├── AnnotationGlobalMetadata.java │ │ ├── AnnotationMockCreator.java │ │ ├── AnnotationMockCreatorFactory.java │ │ ├── AnnotationMockMetadata.java │ │ ├── AnnotationMockScanner.java │ │ ├── DefaultInjectFieldSearcher.java │ │ ├── EasyMockAnnotationSupport.java │ │ ├── MockMetadata.java │ │ └── TestSubjectInjector.java │ ├── powermock-api-mockito2/ │ │ └── src/ │ │ ├── main/ │ │ │ ├── java/ │ │ │ │ └── org/ │ │ │ │ └── powermock/ │ │ │ │ └── api/ │ │ │ │ ├── extension/ │ │ │ │ │ ├── agent/ │ │ │ │ │ │ └── JavaAgentFrameworkRegisterImpl.java │ │ │ │ │ └── listener/ │ │ │ │ │ └── AnnotationEnabler.java │ │ │ │ └── mockito/ │ │ │ │ ├── ClassNotPreparedException.java │ │ │ │ ├── PowerMockito.java │ │ │ │ ├── expectation/ │ │ │ │ │ ├── ConstructorAwareExpectationSetup.java │ │ │ │ │ ├── ConstructorExpectationSetup.java │ │ │ │ │ ├── DefaultConstructorExpectationSetup.java │ │ │ │ │ ├── PowerMockitoStubber.java │ │ │ │ │ ├── PrivatelyExpectedArguments.java │ │ │ │ │ ├── WithAnyArguments.java │ │ │ │ │ ├── WithExpectedArguments.java │ │ │ │ │ ├── WithExpectedParameterTypes.java │ │ │ │ │ ├── WithOrWithoutExpectedArguments.java │ │ │ │ │ ├── WithoutExpectedArguments.java │ │ │ │ │ └── reporter/ │ │ │ │ │ └── MockitoPowerMockReporter.java │ │ │ │ ├── internal/ │ │ │ │ │ ├── PowerMockitoCore.java │ │ │ │ │ ├── configuration/ │ │ │ │ │ │ ├── PowerMockitoInjectingAnnotationEngine.java │ │ │ │ │ │ └── PowerMockitoSpyAnnotationEngine.java │ │ │ │ │ ├── exceptions/ │ │ │ │ │ │ └── StackTraceCleanerProvider.java │ │ │ │ │ ├── expectation/ │ │ │ │ │ │ ├── DefaultMethodExpectationSetup.java │ │ │ │ │ │ ├── DefaultPrivatelyExpectedArguments.java │ │ │ │ │ │ ├── DelegatingToConstructorsOngoingStubbing.java │ │ │ │ │ │ └── PowerMockitoStubberImpl.java │ │ │ │ │ ├── invocation/ │ │ │ │ │ │ ├── InvocationControlAssertionError.java │ │ │ │ │ │ └── MockitoNewInvocationControl.java │ │ │ │ │ ├── mockcreation/ │ │ │ │ │ │ ├── AbstractMockCreator.java │ │ │ │ │ │ ├── DefaultMockCreator.java │ │ │ │ │ │ ├── MockCreator.java │ │ │ │ │ │ ├── MockTypeValidator.java │ │ │ │ │ │ ├── MockTypeValidatorFactory.java │ │ │ │ │ │ └── RuntimeExceptionProxy.java │ │ │ │ │ ├── stubbing/ │ │ │ │ │ │ ├── MockitoRealMethodInvocation.java │ │ │ │ │ │ └── PowerMockCallRealMethod.java │ │ │ │ │ └── verification/ │ │ │ │ │ ├── DefaultConstructorArgumentsVerification.java │ │ │ │ │ ├── DefaultPrivateMethodVerification.java │ │ │ │ │ └── VerifyNoMoreInteractions.java │ │ │ │ ├── invocation/ │ │ │ │ │ ├── InvocationFactory.java │ │ │ │ │ ├── MockHandlerAdaptor.java │ │ │ │ │ └── MockitoMethodInvocationControl.java │ │ │ │ ├── mockmaker/ │ │ │ │ │ ├── MockMakerLoader.java │ │ │ │ │ └── PowerMockMaker.java │ │ │ │ ├── mockpolicies/ │ │ │ │ │ └── Slf4jMockPolicy.java │ │ │ │ ├── powermocklistener/ │ │ │ │ │ └── AnnotationEnabler.java │ │ │ │ └── verification/ │ │ │ │ ├── ConstructorArgumentsVerification.java │ │ │ │ ├── PrivateMethodVerification.java │ │ │ │ ├── WithOrWithoutVerifiedArguments.java │ │ │ │ ├── WithVerifiedArguments.java │ │ │ │ └── WithoutVerifiedArguments.java │ │ │ └── resources/ │ │ │ └── mockito-extensions/ │ │ │ ├── org.mockito.plugins.MockMaker │ │ │ └── org.mockito.plugins.StackTraceCleanerProvider │ │ └── test/ │ │ ├── java/ │ │ │ └── org/ │ │ │ └── powermock/ │ │ │ └── api/ │ │ │ └── mockito/ │ │ │ ├── PowerMockMockito2ApiTestSuite.java │ │ │ ├── internal/ │ │ │ │ ├── expectation/ │ │ │ │ │ └── DefaultMethodExpectationSetupTestCase.java │ │ │ │ └── mockcreation/ │ │ │ │ └── MockCreatorTestCase.java │ │ │ └── mockmaker/ │ │ │ └── PowerMockMakerTestCase.java │ │ └── resources/ │ │ └── org/ │ │ └── powermock/ │ │ └── extensions/ │ │ └── configuration.template │ └── powermock-api-support/ │ └── src/ │ └── main/ │ └── java/ │ └── org/ │ └── powermock/ │ └── api/ │ └── support/ │ ├── ClassLoaderUtil.java │ ├── MethodProxy.java │ ├── SafeExceptionRethrower.java │ ├── Stubber.java │ ├── SuppressCode.java │ └── membermodification/ │ ├── MemberMatcher.java │ ├── MemberModifier.java │ └── strategy/ │ ├── ClassReplaceStrategy.java │ ├── MethodReplaceStrategy.java │ ├── MethodStubStrategy.java │ └── impl/ │ ├── MethodReplaceStrategyImpl.java │ └── MethodStubStrategyImpl.java ├── powermock-classloading/ │ ├── powermock-classloading-base/ │ │ └── src/ │ │ └── main/ │ │ └── java/ │ │ └── org/ │ │ └── powermock/ │ │ └── classloading/ │ │ ├── AbstractClassloaderExecutor.java │ │ ├── ClassloaderExecutor.java │ │ ├── SingleClassloaderExecutor.java │ │ └── spi/ │ │ ├── DeepClonerSPI.java │ │ └── DoNotClone.java │ ├── powermock-classloading-objenesis/ │ │ └── src/ │ │ ├── main/ │ │ │ └── java/ │ │ │ └── org/ │ │ │ └── powermock/ │ │ │ └── classloading/ │ │ │ └── DeepCloner.java │ │ └── test/ │ │ └── java/ │ │ └── powermock/ │ │ └── classloading/ │ │ ├── ObjenesisClassloaderExecutorTest.java │ │ └── ObjenesisDeepClonerTest.java │ └── powermock-classloading-xstream/ │ └── src/ │ ├── main/ │ │ └── java/ │ │ └── org/ │ │ └── powermock/ │ │ └── classloading/ │ │ └── DeepCloner.java │ └── test/ │ └── java/ │ └── powermock/ │ └── classloading/ │ ├── XStreamClassloaderExecutorTest.java │ └── XStreamDeepClonerTest.java ├── powermock-core/ │ ├── build.gradle │ └── src/ │ ├── main/ │ │ ├── java/ │ │ │ └── org/ │ │ │ └── powermock/ │ │ │ ├── PowerMockInternalException.java │ │ │ ├── configuration/ │ │ │ │ ├── Configuration.java │ │ │ │ ├── ConfigurationFactory.java │ │ │ │ ├── ConfigurationType.java │ │ │ │ ├── GlobalConfiguration.java │ │ │ │ ├── MockitoConfiguration.java │ │ │ │ ├── PowerMockConfiguration.java │ │ │ │ └── support/ │ │ │ │ ├── ConfigurationBuilder.java │ │ │ │ ├── ConfigurationFactoryImpl.java │ │ │ │ ├── ConfigurationMapper.java │ │ │ │ ├── PropertiesFinder.java │ │ │ │ ├── PropertiesLoader.java │ │ │ │ └── ValueAliases.java │ │ │ ├── core/ │ │ │ │ ├── ClassLocator.java │ │ │ │ ├── ClassReplicaCreator.java │ │ │ │ ├── ConcreteClassGenerator.java │ │ │ │ ├── DefaultFieldValueGenerator.java │ │ │ │ ├── IdentityHashSet.java │ │ │ │ ├── IndicateReloadClass.java │ │ │ │ ├── InvocationException.java │ │ │ │ ├── ListMap.java │ │ │ │ ├── MockGateway.java │ │ │ │ ├── MockInvocation.java │ │ │ │ ├── MockRepository.java │ │ │ │ ├── PowerMockUtils.java │ │ │ │ ├── WildcardMatcher.java │ │ │ │ ├── agent/ │ │ │ │ │ ├── JavaAgentClassRegister.java │ │ │ │ │ ├── JavaAgentFrameworkRegister.java │ │ │ │ │ └── JavaAgentFrameworkRegisterFactory.java │ │ │ │ ├── bytebuddy/ │ │ │ │ │ ├── ConditionalStateStackManipulation.java │ │ │ │ │ ├── Frame.java │ │ │ │ │ ├── MaxLocalsExtractor.java │ │ │ │ │ ├── MethodMaxLocals.java │ │ │ │ │ ├── MockGetawayCall.java │ │ │ │ │ ├── PrimitiveBoxing.java │ │ │ │ │ └── Variable.java │ │ │ │ ├── classloader/ │ │ │ │ │ ├── ByteCodeFramework.java │ │ │ │ │ ├── ClassMarker.java │ │ │ │ │ ├── ClassloaderWrapper.java │ │ │ │ │ ├── DeferSupportingClassLoader.java │ │ │ │ │ ├── MockClassLoader.java │ │ │ │ │ ├── MockClassLoaderBuilder.java │ │ │ │ │ ├── MockClassLoaderConfiguration.java │ │ │ │ │ ├── MockClassLoaderFactory.java │ │ │ │ │ ├── PowerMockModified.java │ │ │ │ │ ├── annotations/ │ │ │ │ │ │ ├── MockPolicy.java │ │ │ │ │ │ ├── PowerMockIgnore.java │ │ │ │ │ │ ├── PowerMockListener.java │ │ │ │ │ │ ├── PrepareEverythingForTest.java │ │ │ │ │ │ ├── PrepareForTest.java │ │ │ │ │ │ ├── PrepareOnlyThisForTest.java │ │ │ │ │ │ ├── SuppressStaticInitializationFor.java │ │ │ │ │ │ └── UseClassPathAdjuster.java │ │ │ │ │ └── javassist/ │ │ │ │ │ ├── ClassPathAdjuster.java │ │ │ │ │ ├── ClassPoolFactory.java │ │ │ │ │ ├── JavaAssistClassMarkerFactory.java │ │ │ │ │ └── JavassistMockClassLoader.java │ │ │ │ ├── reporter/ │ │ │ │ │ ├── MockingFrameworkReporter.java │ │ │ │ │ ├── PowerMockReporter.java │ │ │ │ │ └── PowerMockReporterFactory.java │ │ │ │ ├── spi/ │ │ │ │ │ ├── DefaultBehavior.java │ │ │ │ │ ├── MethodInvocationControl.java │ │ │ │ │ ├── NewInvocationControl.java │ │ │ │ │ ├── PowerMockPolicy.java │ │ │ │ │ ├── PowerMockTestListener.java │ │ │ │ │ ├── listener/ │ │ │ │ │ │ └── AnnotationEnablerListener.java │ │ │ │ │ ├── support/ │ │ │ │ │ │ ├── AbstractPowerMockTestListenerBase.java │ │ │ │ │ │ └── InvocationSubstitute.java │ │ │ │ │ └── testresult/ │ │ │ │ │ ├── Result.java │ │ │ │ │ ├── TestMethodResult.java │ │ │ │ │ ├── TestSuiteResult.java │ │ │ │ │ └── impl/ │ │ │ │ │ ├── TestMethodResultImpl.java │ │ │ │ │ └── TestSuiteResultImpl.java │ │ │ │ ├── testlisteners/ │ │ │ │ │ ├── FieldDefaulter.java │ │ │ │ │ └── GlobalNotificationBuildSupport.java │ │ │ │ └── transformers/ │ │ │ │ ├── ClassWrapper.java │ │ │ │ ├── ClassWrapperFactory.java │ │ │ │ ├── MethodSignatureWriter.java │ │ │ │ ├── MethodSignatures.java │ │ │ │ ├── MockTransformer.java │ │ │ │ ├── MockTransformerChain.java │ │ │ │ ├── MockTransformerChainFactory.java │ │ │ │ ├── TestClassAwareTransformer.java │ │ │ │ ├── TestClassTransformer.java │ │ │ │ ├── TestClassTransformerBuilder.java │ │ │ │ ├── TransformStrategy.java │ │ │ │ ├── javassist/ │ │ │ │ │ ├── AbstractJavaAssistMockTransformer.java │ │ │ │ │ ├── ClassFinalModifierMockTransformer.java │ │ │ │ │ ├── ConstructorsMockTransformer.java │ │ │ │ │ ├── InstrumentMockTransformer.java │ │ │ │ │ ├── JavassistMockTransformerChainFactory.java │ │ │ │ │ ├── MethodMockTransformer.java │ │ │ │ │ ├── MethodSizeMockTransformer.java │ │ │ │ │ ├── PackagePrivateClassesMockTransformer.java │ │ │ │ │ ├── StaticFinalFieldsMockTransformer.java │ │ │ │ │ ├── StaticFinalNativeMethodMockTransformer.java │ │ │ │ │ ├── SuppressStaticInitializerMockTransformer.java │ │ │ │ │ ├── support/ │ │ │ │ │ │ ├── JavaAssistClassWrapperFactory.java │ │ │ │ │ │ ├── PowerMockExpressionEditor.java │ │ │ │ │ │ ├── Primitives.java │ │ │ │ │ │ └── TransformerHelper.java │ │ │ │ │ └── testclass/ │ │ │ │ │ ├── ForMethodsJavaAssistTestClassTransformer.java │ │ │ │ │ ├── FromAllMethodsExceptJavaAssistTestClassTransformer.java │ │ │ │ │ └── JavaAssistTestClassTransformer.java │ │ │ │ └── support/ │ │ │ │ ├── DefaultMockTransformerChain.java │ │ │ │ └── FilterPredicates.java │ │ │ ├── mockpolicies/ │ │ │ │ ├── MockPolicyClassLoadingSettings.java │ │ │ │ ├── MockPolicyInterceptionSettings.java │ │ │ │ ├── impl/ │ │ │ │ │ ├── MockPolicyClassLoadingSettingsImpl.java │ │ │ │ │ └── MockPolicyInterceptionSettingsImpl.java │ │ │ │ └── support/ │ │ │ │ └── LogPolicySupport.java │ │ │ ├── tests/ │ │ │ │ └── utils/ │ │ │ │ ├── ArrayMerger.java │ │ │ │ ├── IgnorePackagesExtractor.java │ │ │ │ ├── Keys.java │ │ │ │ ├── MockPolicyInitializer.java │ │ │ │ ├── PowerMockTestNotifier.java │ │ │ │ ├── RunnerTestSuiteChunker.java │ │ │ │ ├── TestChunk.java │ │ │ │ ├── TestClassesExtractor.java │ │ │ │ ├── TestSuiteChunker.java │ │ │ │ └── impl/ │ │ │ │ ├── AbstractCommonTestSuiteChunkerImpl.java │ │ │ │ ├── AbstractTestClassExtractor.java │ │ │ │ ├── AbstractTestSuiteChunkerImpl.java │ │ │ │ ├── ArrayMergerImpl.java │ │ │ │ ├── MockPolicyInitializerImpl.java │ │ │ │ ├── PowerMockIgnorePackagesExtractorImpl.java │ │ │ │ ├── PowerMockTestNotifierImpl.java │ │ │ │ ├── PrepareForTestExtractorImpl.java │ │ │ │ ├── StaticConstructorSuppressExtractorImpl.java │ │ │ │ ├── TestCaseEntry.java │ │ │ │ └── TestChunkImpl.java │ │ │ └── utils/ │ │ │ ├── ArrayUtil.java │ │ │ ├── Asserts.java │ │ │ ├── IOUtils.java │ │ │ ├── JavaVersion.java │ │ │ ├── NumberUtils.java │ │ │ └── StringJoiner.java │ │ └── resources/ │ │ └── org/ │ │ └── powermock/ │ │ └── default.properties │ └── test/ │ ├── java/ │ │ ├── org/ │ │ │ └── powermock/ │ │ │ ├── WildcardMatcherTest.java │ │ │ ├── configuration/ │ │ │ │ └── support/ │ │ │ │ ├── ConfigurationBuilderTest.java │ │ │ │ └── ConfigurationFactoryImplTest.java │ │ │ ├── core/ │ │ │ │ ├── classloader/ │ │ │ │ │ ├── Collaborator.java │ │ │ │ │ ├── HardToTransform.java │ │ │ │ │ ├── MockClassLoaderBuilderTest.java │ │ │ │ │ ├── MockClassLoaderConfigurationTest.java │ │ │ │ │ ├── MockClassLoaderFactoryTest.java │ │ │ │ │ ├── MockClassLoaderTest.java │ │ │ │ │ └── ResourcePrefixClassLoader.java │ │ │ │ ├── test/ │ │ │ │ │ ├── ClassLoaderTestHelper.java │ │ │ │ │ ├── ContainsCondition.java │ │ │ │ │ └── MockClassLoaderFactory.java │ │ │ │ ├── testlisteners/ │ │ │ │ │ └── GlobalNotificationBuildSupportTest.java │ │ │ │ └── transformers/ │ │ │ │ ├── AbstractBaseMockTransformerTest.java │ │ │ │ ├── ClassFinalModifierMockTransformerTest.java │ │ │ │ ├── ConstructorCallMockTransformerTest.java │ │ │ │ ├── ConstructorModifiersMockTransformerTest.java │ │ │ │ ├── InstrumentMockTransformerTest.java │ │ │ │ ├── MethodSizeMockTransformerTest.java │ │ │ │ ├── MethodsMockTransformerTest.java │ │ │ │ ├── MockTransformerChainTest.java │ │ │ │ ├── MockTransformerTestHelper.java │ │ │ │ ├── NativeMethodsMockTransformerTest.java │ │ │ │ ├── StaticFinalFieldsMockTransformerTest.java │ │ │ │ ├── StaticMethodsMockTransformerTest.java │ │ │ │ ├── SuppressStaticInitializerMockTransformerTest.java │ │ │ │ ├── TestClassTransformerTest.java │ │ │ │ ├── javassist/ │ │ │ │ │ └── TestPrimitives.java │ │ │ │ └── mock/ │ │ │ │ └── MockGatewaySpy.java │ │ │ ├── tests/ │ │ │ │ └── utils/ │ │ │ │ └── impl/ │ │ │ │ ├── PowerMockIgnorePackagesExtractorImplTest.java │ │ │ │ └── PrepareForTestExtractorImplTest.java │ │ │ └── utils/ │ │ │ ├── JavaVersionTest.java │ │ │ └── NumberUtilsTest.java │ │ └── powermock/ │ │ └── test/ │ │ └── support/ │ │ ├── ClassForMockClassLoaderTestCase.java │ │ ├── ClassWithLargeMethods.java │ │ ├── MainMockTransformerTestSupport.java │ │ └── TestWithTwoTestMethods.java │ └── resources/ │ └── org/ │ └── powermock/ │ ├── core/ │ │ └── classloader/ │ │ └── foo/ │ │ └── bar/ │ │ └── baz/ │ │ └── test.txt │ ├── extensions/ │ │ ├── test.properties │ │ ├── test_configuration.properties │ │ ├── test_with_alias.properties │ │ └── test_without_prefix.properties │ └── test_default_configuration.properties ├── powermock-modules/ │ ├── powermock-module-javaagent/ │ │ ├── jmockit-license.txt │ │ └── src/ │ │ └── main/ │ │ ├── java/ │ │ │ ├── com/ │ │ │ │ └── sun/ │ │ │ │ └── tools/ │ │ │ │ └── attach/ │ │ │ │ ├── AgentInitializationException.java │ │ │ │ ├── AgentLoadException.java │ │ │ │ ├── AttachNotSupportedException.java │ │ │ │ ├── VirtualMachine.java │ │ │ │ ├── VirtualMachineDescriptor.java │ │ │ │ └── spi/ │ │ │ │ └── AttachProvider.java │ │ │ ├── org/ │ │ │ │ └── powermock/ │ │ │ │ └── modules/ │ │ │ │ └── agent/ │ │ │ │ ├── AbstractClassTransformer.java │ │ │ │ ├── AgentInitialization.java │ │ │ │ ├── AgentLoader.java │ │ │ │ ├── DefinalizingClassTransformer.java │ │ │ │ ├── DefinalizingClassVisitor.java │ │ │ │ ├── PowerMockAgent.java │ │ │ │ ├── PowerMockClassRedefiner.java │ │ │ │ ├── PowerMockClassTransformer.java │ │ │ │ └── support/ │ │ │ │ ├── JavaAgentClassRegisterImpl.java │ │ │ │ └── PowerMockAgentTestInitializer.java │ │ │ └── sun/ │ │ │ └── tools/ │ │ │ └── attach/ │ │ │ ├── BsdVirtualMachine.java │ │ │ ├── HotSpotVirtualMachine.java │ │ │ ├── LinuxVirtualMachine.java │ │ │ ├── SolarisVirtualMachine.java │ │ │ └── WindowsVirtualMachine.java │ │ └── javadoc/ │ │ └── resources/ │ │ └── org,powermock/ │ │ └── modules/ │ │ └── agent/ │ │ └── package.html │ ├── powermock-module-junit4/ │ │ └── src/ │ │ ├── main/ │ │ │ └── java/ │ │ │ └── org/ │ │ │ └── powermock/ │ │ │ └── modules/ │ │ │ └── junit4/ │ │ │ ├── PowerMockRunner.java │ │ │ ├── PowerMockRunnerDelegate.java │ │ │ └── internal/ │ │ │ └── impl/ │ │ │ ├── DelegatingPowerMockRunner.java │ │ │ ├── NotificationBuilder.java │ │ │ ├── PowerMockJUnit44RunnerDelegateImpl.java │ │ │ ├── PowerMockJUnit47RunnerDelegateImpl.java │ │ │ ├── PowerMockJUnit49RunnerDelegateImpl.java │ │ │ ├── PowerMockRunNotifier.java │ │ │ └── testcaseworkaround/ │ │ │ └── PowerMockJUnit4MethodValidator.java │ │ └── test/ │ │ └── java/ │ │ └── org/ │ │ └── powermock/ │ │ └── modules/ │ │ └── junit4/ │ │ └── internal/ │ │ └── impl/ │ │ └── PowerMockRunNotifierTest.java │ ├── powermock-module-junit4-common/ │ │ └── src/ │ │ ├── main/ │ │ │ └── java/ │ │ │ └── org/ │ │ │ └── powermock/ │ │ │ └── modules/ │ │ │ └── junit4/ │ │ │ └── common/ │ │ │ └── internal/ │ │ │ ├── JUnit4TestSuiteChunker.java │ │ │ ├── PowerMockJUnitRunnerDelegate.java │ │ │ └── impl/ │ │ │ ├── AbstractCommonPowerMockRunner.java │ │ │ ├── JUnit4TestMethodChecker.java │ │ │ ├── JUnit4TestSuiteChunkerImpl.java │ │ │ ├── JUnitVersion.java │ │ │ ├── PowerMockJUnit4RunListener.java │ │ │ ├── VersionComparator.java │ │ │ └── VersionTokenizer.java │ │ └── test/ │ │ └── java/ │ │ └── org/ │ │ └── powermock/ │ │ └── modules/ │ │ └── junit4/ │ │ └── common/ │ │ └── internal/ │ │ └── impl/ │ │ └── JUnitVersionTest.java │ ├── powermock-module-junit4-legacy/ │ │ └── src/ │ │ └── main/ │ │ └── java/ │ │ └── org/ │ │ └── powermock/ │ │ └── modules/ │ │ └── junit4/ │ │ └── legacy/ │ │ ├── PowerMockRunner.java │ │ └── internal/ │ │ └── impl/ │ │ ├── PowerMockJUnit4LegacyFilter.java │ │ ├── PowerMockJUnit4LegacyRunnerDelegateImpl.java │ │ └── testcaseworkaround/ │ │ ├── PowerMockJUnit4LegacyTestClassMethodsRunner.java │ │ ├── PowerMockJUnit4LegacyTestIntrospector.java │ │ └── PowerMockJUnit4LegacyTestMethodRunner.java │ ├── powermock-module-junit4-rule/ │ │ └── src/ │ │ └── main/ │ │ └── java/ │ │ └── org/ │ │ └── powermock/ │ │ └── modules/ │ │ └── junit4/ │ │ └── rule/ │ │ ├── PowerMockRule.java │ │ └── PowerMockRuleTestSuiteChunker.java │ ├── powermock-module-junit4-rule-agent/ │ │ └── src/ │ │ └── main/ │ │ └── java/ │ │ └── org/ │ │ └── powermock/ │ │ └── modules/ │ │ └── junit4/ │ │ └── rule/ │ │ └── PowerMockRule.java │ ├── powermock-module-testng/ │ │ └── src/ │ │ └── main/ │ │ └── java/ │ │ └── org/ │ │ └── powermock/ │ │ └── modules/ │ │ └── testng/ │ │ ├── PowerMockObjectFactory.java │ │ └── internal/ │ │ ├── Assumes.java │ │ ├── PowerMockClassloaderObjectFactory.java │ │ ├── PowerMockExpectedExceptionsExtractorImpl.java │ │ ├── PowerMockTestNGMethodHandler.java │ │ ├── TestClassInstanceFactory.java │ │ ├── TestNGMethodFilter.java │ │ └── TestNGMockClassLoaderFactory.java │ ├── powermock-module-testng-agent/ │ │ └── src/ │ │ └── main/ │ │ └── java/ │ │ └── org/ │ │ └── powermock/ │ │ └── modules/ │ │ └── testng/ │ │ └── PowerMockObjectFactory.java │ └── powermock-module-testng-common/ │ └── src/ │ └── main/ │ └── java/ │ └── org/ │ └── powermock/ │ └── modules/ │ └── testng/ │ └── PowerMockTestCase.java ├── powermock-reflect/ │ ├── build.gradle │ └── src/ │ ├── main/ │ │ └── java/ │ │ └── org/ │ │ └── powermock/ │ │ └── reflect/ │ │ ├── Whitebox.java │ │ ├── exceptions/ │ │ │ ├── ConstructorNotFoundException.java │ │ │ ├── FieldNotFoundException.java │ │ │ ├── MethodInvocationException.java │ │ │ ├── MethodNotFoundException.java │ │ │ ├── TooManyConstructorsFoundException.java │ │ │ ├── TooManyFieldsFoundException.java │ │ │ └── TooManyMethodsFoundException.java │ │ ├── internal/ │ │ │ ├── CandidateConstructorSearcher.java │ │ │ ├── Constructor.java │ │ │ ├── ConstructorFinder.java │ │ │ ├── ParameterTypesMatcher.java │ │ │ ├── ParametersMatcher.java │ │ │ ├── TypeUtils.java │ │ │ ├── WhiteboxImpl.java │ │ │ ├── comparator/ │ │ │ │ └── ComparatorFactory.java │ │ │ ├── matcherstrategies/ │ │ │ │ ├── AllFieldsMatcherStrategy.java │ │ │ │ ├── AssignableFromFieldTypeMatcherStrategy.java │ │ │ │ ├── AssignableToFieldTypeMatcherStrategy.java │ │ │ │ ├── FieldAnnotationMatcherStrategy.java │ │ │ │ ├── FieldMatcherStrategy.java │ │ │ │ ├── FieldNameMatcherStrategy.java │ │ │ │ └── FieldTypeMatcherStrategy.java │ │ │ ├── primitivesupport/ │ │ │ │ ├── BoxedWrapper.java │ │ │ │ └── PrimitiveWrapper.java │ │ │ └── proxy/ │ │ │ ├── ProxyFrameworks.java │ │ │ ├── UnproxiedType.java │ │ │ └── UnproxiedTypeFactory.java │ │ └── matching/ │ │ └── FieldMatchingStrategy.java │ └── test/ │ └── java/ │ └── org/ │ └── powermock/ │ └── reflect/ │ ├── WhiteBoxGetFieldTest.java │ ├── WhiteBoxTest.java │ ├── context/ │ │ ├── ClassFieldsNotInTargetContext.java │ │ ├── InstanceFieldsNotInTargetContext.java │ │ ├── MyContext.java │ │ ├── MyIntContext.java │ │ ├── MyStringContext.java │ │ └── OneInstanceAndOneStaticFieldOfSameTypeContext.java │ ├── internal/ │ │ ├── WhiteboxImplTest.java │ │ └── proxy/ │ │ ├── AnotherInterface.java │ │ ├── ClassFactory.java │ │ ├── ProxyFrameworksTest.java │ │ ├── SomeClass.java │ │ └── SomeInterface.java │ └── testclasses/ │ ├── AbstractClass.java │ ├── AnInterface.java │ ├── Child.java │ ├── ClassWithAMethod.java │ ├── ClassWithChildThatHasInternalState.java │ ├── ClassWithInterfaceConstructors.java │ ├── ClassWithInternalState.java │ ├── ClassWithList.java │ ├── ClassWithMethodUsingBothPrimitiveTypeAndWrappedTypeArguments.java │ ├── ClassWithMethodUsingSuperTypeArgument.java │ ├── ClassWithObjectConstructors.java │ ├── ClassWithOverloadedConstructors.java │ ├── ClassWithOverloadedMethods.java │ ├── ClassWithOverriddenMethod.java │ ├── ClassWithPrimitiveConstructors.java │ ├── ClassWithPrivateMethods.java │ ├── ClassWithSerializableState.java │ ├── ClassWithSeveralMethodsWithSameName.java │ ├── ClassWithSeveralMethodsWithSameNameOneWithoutParameters.java │ ├── ClassWithSimpleInternalState.java │ ├── ClassWithSimpleStateOfSameType.java │ ├── ClassWithStandardMethod.java │ ├── ClassWithStaticAndInstanceInternalStateOfSameType.java │ ├── ClassWithStaticMethod.java │ ├── ClassWithUniquePrivateMethods.java │ ├── ClassWithVarArgsConstructor.java │ ├── ClassWithVarArgsConstructor2.java │ └── Parent.java ├── powermock-release/ │ └── build.gradle ├── settings.gradle ├── tests/ │ ├── build.gradle │ ├── easymock/ │ │ ├── build.gradle │ │ ├── junit4/ │ │ │ └── src/ │ │ │ └── test/ │ │ │ └── java/ │ │ │ └── samples/ │ │ │ ├── interfacemethodfinding/ │ │ │ │ └── InterfaceMethodHierarchyUsageTest.java │ │ │ ├── junit4/ │ │ │ │ ├── abstractmocking/ │ │ │ │ │ └── AbstractMethodMockingTest.java │ │ │ │ ├── annotationbased/ │ │ │ │ │ ├── AnnotationDemoWithSetupMethodTest.java │ │ │ │ │ ├── FinalDemoWithAnnotationInjectionAndFieldDefaulterTest.java │ │ │ │ │ ├── FinalDemoWithAnnotationInjectionTest.java │ │ │ │ │ ├── FinalDemoWithNiceAnnotationInjectionTest.java │ │ │ │ │ ├── FinalDemoWithStrictAnnotationInjectionTest.java │ │ │ │ │ ├── TestSubjectEasymockAnnotationTest.java │ │ │ │ │ └── TestSubjectPowermockAnnotationTest.java │ │ │ │ ├── assume/ │ │ │ │ │ └── AssumeTest.java │ │ │ │ ├── classhierarchy/ │ │ │ │ │ └── CommonParentTest.java │ │ │ │ ├── classwithinnermembers/ │ │ │ │ │ └── ClassWithInnerMembersTest.java │ │ │ │ ├── console/ │ │ │ │ │ └── ConsoleTest.java │ │ │ │ ├── constructor/ │ │ │ │ │ ├── PrivateConstructorInstantiationDemoTest.java │ │ │ │ │ └── PublicConstructorWithDependencyDemoTest.java │ │ │ │ ├── constructorargs/ │ │ │ │ │ └── ConstructorArgsDemoTest.java │ │ │ │ ├── easymock/ │ │ │ │ │ └── EasyMockAndPowerMockMixTest.java │ │ │ │ ├── enummocking/ │ │ │ │ │ └── EnumMockingTest.java │ │ │ │ ├── equalswithgetclass/ │ │ │ │ │ └── EqualsWithGetClassTest.java │ │ │ │ ├── expectnew/ │ │ │ │ │ ├── ExpectNewCases.java │ │ │ │ │ ├── ExpectNewDemoTest.java │ │ │ │ │ ├── ExpectNewOfFinalSystemClassTest.java │ │ │ │ │ ├── MockDateTest.java │ │ │ │ │ ├── PrimitiveAndWrapperDemoTest.java │ │ │ │ │ └── PrimitiveAndWrapperUserTest.java │ │ │ │ ├── expectvoid/ │ │ │ │ │ └── ExpectVoidDemoTest.java │ │ │ │ ├── finalmocking/ │ │ │ │ │ ├── FinalDemoTest.java │ │ │ │ │ ├── MockingOfInstanceMethodsInFinalSystemClassTest.java │ │ │ │ │ └── NoDuplicateTest.java │ │ │ │ ├── hashcode/ │ │ │ │ │ └── PowerMockUsesIdentityHashMapToStoreMocks.java │ │ │ │ ├── interfacefieldchange/ │ │ │ │ │ └── ChangeValueOfStaticFinalFieldInInterfacesDefect.java │ │ │ │ ├── java/ │ │ │ │ │ └── MockClassesInsideJavaPackage.java │ │ │ │ ├── largemethod/ │ │ │ │ │ └── LargeMethodTest.java │ │ │ │ ├── misc/ │ │ │ │ │ └── PrivateInnerInterfacesInTestClassTest.java │ │ │ │ ├── mockpolicy/ │ │ │ │ │ ├── MockPolicyUsageExampleTest.java │ │ │ │ │ ├── MockPolicyWithExpectationsTest.java │ │ │ │ │ ├── MockPolicyWithInvocationHandlerTest.java │ │ │ │ │ └── frameworkexample/ │ │ │ │ │ ├── SimpleFrameworkMockPolicy.java │ │ │ │ │ └── SimpleFrameworkUserTest.java │ │ │ │ ├── multireplayverify/ │ │ │ │ │ └── MultiReplayVerifyTest.java │ │ │ │ ├── nativemocking/ │ │ │ │ │ └── NativeMockingSampleTest.java │ │ │ │ ├── newmocking/ │ │ │ │ │ └── StupidNewTest.java │ │ │ │ ├── nice/ │ │ │ │ │ └── NiceDemoTest.java │ │ │ │ ├── noannotation/ │ │ │ │ │ ├── NoAnnotationUsageTest.java │ │ │ │ │ ├── SetUpAndTearDownWhenExtendingTestCaseTest.java │ │ │ │ │ ├── SetUpAndTearDownWhenNotExtendingTestCaseTest.java │ │ │ │ │ ├── SetUpIsOnlyCalledOnceWhenExtendingTestCaseTest.java │ │ │ │ │ └── StringConstructorWorksWhenExtendingTestCase.java │ │ │ │ ├── overloading/ │ │ │ │ │ ├── MethodWithSameNameButDifferentDefinitionTypeTest.java │ │ │ │ │ └── OverloadingDemoTest.java │ │ │ │ ├── partialmocking/ │ │ │ │ │ ├── MockSelfDemoTest.java │ │ │ │ │ ├── MockSelfDemoWithSubClassTest.java │ │ │ │ │ ├── PartialMockingWithConstructorTest.java │ │ │ │ │ └── PartialMockingWithConstructorUsingEasyMockTest.java │ │ │ │ ├── powermockignore/ │ │ │ │ │ └── PowerMockIgnoreAndPrepareForTest.java │ │ │ │ ├── prepareeverything/ │ │ │ │ │ └── ExpectNewDemoUsingThePrepareEverythingAnnotationTest.java │ │ │ │ ├── privateandfinal/ │ │ │ │ │ └── PrivateFinalTest.java │ │ │ │ ├── privatefield/ │ │ │ │ │ ├── MockSelfPrivateFieldServiceClassTest.java │ │ │ │ │ └── SimplePrivateFieldServiceClassTest.java │ │ │ │ ├── privatemocking/ │ │ │ │ │ └── PrivateMethodDemoTest.java │ │ │ │ ├── reflection/ │ │ │ │ │ └── ReflectionInstantiatorTest.java │ │ │ │ ├── replayall/ │ │ │ │ │ ├── ReplayAllForExpectNewTest.java │ │ │ │ │ └── ReplayAllForStaticMethodsTest.java │ │ │ │ ├── resetmock/ │ │ │ │ │ ├── ResetForStaticMethodsTest.java │ │ │ │ │ └── ResetMockTest.java │ │ │ │ ├── servletmocking/ │ │ │ │ │ └── SampleServletTest.java │ │ │ │ ├── simplereturn/ │ │ │ │ │ └── SimpleReturnExampleUserTest.java │ │ │ │ ├── singleton/ │ │ │ │ │ ├── LogicAndTestInSameClassTest.java │ │ │ │ │ ├── MockStaticTest.java │ │ │ │ │ └── SimpleStaticServiceTest.java │ │ │ │ ├── stackoverflow/ │ │ │ │ │ ├── EvilHashCode.java │ │ │ │ │ └── StackOverFlowTest.java │ │ │ │ ├── staticandinstance/ │ │ │ │ │ ├── StaticAndInstanceDemoTest.java │ │ │ │ │ └── StaticAndInstanceWithConstructorCodeDemoTest.java │ │ │ │ ├── staticinitializer/ │ │ │ │ │ ├── AbstractStaticInitializerTest.java │ │ │ │ │ ├── EvilStaticInitializerExampleTest.java │ │ │ │ │ ├── InterfaceStaticInitializerExampleTest.java │ │ │ │ │ └── StaticInitializerExampleTest.java │ │ │ │ ├── strict/ │ │ │ │ │ └── StrictDemoTest.java │ │ │ │ ├── stubmethod/ │ │ │ │ │ └── StubMethodTest.java │ │ │ │ ├── suppressconstructor/ │ │ │ │ │ ├── CreateUnmockedTest.java │ │ │ │ │ ├── SuppressConstructorDemoTest.java │ │ │ │ │ ├── SuppressConstructorHierarchyDemoTest.java │ │ │ │ │ └── SuppressNonParentConstructorDemoTest.java │ │ │ │ ├── suppressfield/ │ │ │ │ │ ├── ItemRepositoryTest.java │ │ │ │ │ └── SuppressFieldTest.java │ │ │ │ ├── suppressmethod/ │ │ │ │ │ └── SuppressMethodTest.java │ │ │ │ ├── swing/ │ │ │ │ │ └── ReallySimpleSwingDemoTest.java │ │ │ │ ├── system/ │ │ │ │ │ ├── FieldMockDefect.java │ │ │ │ │ └── SystemClassUserTest.java │ │ │ │ ├── testhierarchy/ │ │ │ │ │ ├── RunWithHierarchyTest.java │ │ │ │ │ └── TestParent.java │ │ │ │ ├── verify/ │ │ │ │ │ └── AssertVerifyWorksTest.java │ │ │ │ └── whitebox/ │ │ │ │ └── PowerMockConstructorFiltrationTest.java │ │ │ ├── methodhierarchy/ │ │ │ │ └── MethodInvocationDemoTest.java │ │ │ ├── packageprivate/ │ │ │ │ └── PackagePrivateClassTest.java │ │ │ └── suppressconstructor/ │ │ │ ├── SuppressDefaultConstructorTest.java │ │ │ └── SuppressSpecificConstructorDemoTest.java │ │ ├── junit4-agent/ │ │ │ └── src/ │ │ │ └── test/ │ │ │ └── java/ │ │ │ └── samples/ │ │ │ └── powermockito/ │ │ │ └── junit4/ │ │ │ └── agent/ │ │ │ ├── AnnotationUsageTest.java │ │ │ └── LargeMethodTest.java │ │ ├── junit4-legacy/ │ │ │ └── src/ │ │ │ └── test/ │ │ │ └── java/ │ │ │ └── samples/ │ │ │ └── junit4/ │ │ │ └── legacy/ │ │ │ ├── annotationbased/ │ │ │ │ ├── AnnotationDemoWithSetupMethodTest.java │ │ │ │ └── FinalDemoWithAnnotationInjectionTest.java │ │ │ ├── noannotation/ │ │ │ │ ├── NoAnnotationUsageTest.java │ │ │ │ ├── SetUpAndTearDownWhenExtendingTestCaseTest.java │ │ │ │ └── SetUpAndTearDownWhenNotExtendingTestCaseTest.java │ │ │ ├── singleton/ │ │ │ │ └── MockStaticTest.java │ │ │ └── suppressconstructor/ │ │ │ └── SuppressConstructorHierarchyDemoTest.java │ │ ├── junit410/ │ │ │ └── src/ │ │ │ └── test/ │ │ │ └── java/ │ │ │ └── samples/ │ │ │ └── junit410/ │ │ │ ├── assume/ │ │ │ │ └── AssumeForJUnit410Test.java │ │ │ ├── expectnew/ │ │ │ │ ├── ExpectNewDemoTest.java │ │ │ │ └── ExpectNewOfFinalSystemClassTest.java │ │ │ ├── github668/ │ │ │ │ ├── Github668.java │ │ │ │ ├── IncidentPropertyChangeDAO.java │ │ │ │ └── package-info.java │ │ │ └── rules/ │ │ │ ├── AssertThatJUnit410RulesWorks.java │ │ │ ├── ExceptionHandlingRuleTest.java │ │ │ ├── NoRuleAssertionErrorTest.java │ │ │ └── impl/ │ │ │ └── SimpleEasyMockJUnitRule.java │ │ ├── junit412/ │ │ │ └── src/ │ │ │ └── test/ │ │ │ └── java/ │ │ │ └── samples/ │ │ │ └── junit412/ │ │ │ ├── bug/ │ │ │ │ └── github755/ │ │ │ │ ├── TwoObjectsAnnotatedTest.java │ │ │ │ └── package-info.java │ │ │ ├── expectnew/ │ │ │ │ ├── ExpectNewDemoTest.java │ │ │ │ └── ExpectNewOfFinalSystemClassTest.java │ │ │ └── github668/ │ │ │ ├── Github668Test.java │ │ │ ├── IncidentPropertyChangeDAO.java │ │ │ ├── TwoMockFieldsWithDifferentTypesClass.java │ │ │ ├── TwoMockFieldsWithSameTypeCase.java │ │ │ └── package-info.java │ │ ├── junit45/ │ │ │ └── src/ │ │ │ ├── main/ │ │ │ │ └── java/ │ │ │ │ └── demo/ │ │ │ │ └── org/ │ │ │ │ └── powermock/ │ │ │ │ └── modules/ │ │ │ │ └── test/ │ │ │ │ └── junit45/ │ │ │ │ └── failure/ │ │ │ │ ├── MyClass.java │ │ │ │ ├── MyException.java │ │ │ │ └── MyUtils.java │ │ │ └── test/ │ │ │ └── java/ │ │ │ └── demo/ │ │ │ └── org/ │ │ │ └── powermock/ │ │ │ └── modules/ │ │ │ └── test/ │ │ │ └── junit45/ │ │ │ └── failure/ │ │ │ └── AssertThatJUnit45FailuresWorkTest.java │ │ ├── junit47/ │ │ │ └── src/ │ │ │ └── test/ │ │ │ └── java/ │ │ │ └── samples/ │ │ │ └── junit4/ │ │ │ ├── annotationbased/ │ │ │ │ └── FinalDemoWithAnnotationInjectionAndFieldDefaulterTest.java │ │ │ ├── expectnew/ │ │ │ │ ├── ExpectNewDemoTest.java │ │ │ │ └── ExpectNewOfFinalSystemClassTest.java │ │ │ └── rules/ │ │ │ ├── AssertThatJUnit47RulesWorks.java │ │ │ ├── NoRuleAssertionErrorTest.java │ │ │ ├── RuleOrderTest.java │ │ │ └── ThrowingRuleTest.java │ │ ├── junit48/ │ │ │ └── src/ │ │ │ └── test/ │ │ │ └── java/ │ │ │ └── samples/ │ │ │ └── junit48/ │ │ │ ├── expectnew/ │ │ │ │ ├── ExpectNewDemoTest.java │ │ │ │ └── ExpectNewOfFinalSystemClassTest.java │ │ │ └── rules/ │ │ │ ├── AssertThatJUnit48RulesWorks.java │ │ │ ├── ExceptionHandlingRuleTest.java │ │ │ ├── NoRuleAssertionErrorTest.java │ │ │ ├── RuleOrderTest.java │ │ │ ├── ThrowingRuleTest.java │ │ │ └── impl/ │ │ │ └── SimpleEasyMockJUnitRule.java │ │ ├── testng/ │ │ │ ├── src/ │ │ │ │ └── test/ │ │ │ │ └── java/ │ │ │ │ └── samples/ │ │ │ │ └── testng/ │ │ │ │ ├── AnnotationDemoTest.java │ │ │ │ ├── AnnotationDemoWithBeforeMethodTest.java │ │ │ │ ├── DocumentBuilderFactoryTest.java │ │ │ │ ├── FinalTest.java │ │ │ │ ├── MockStaticExtendsPowerMockTestCaseTest.java │ │ │ │ ├── MockStaticTest.java │ │ │ │ ├── NotAnnotatedWithPrepareForTest.java │ │ │ │ ├── PartialMockingWithBeforeClassTest.java │ │ │ │ ├── PrivateFinalTest.java │ │ │ │ ├── SampleServletTest.java │ │ │ │ ├── StaticInitializerExampleTest.java │ │ │ │ └── SystemClassUserTest.java │ │ │ └── suite.xml │ │ └── testng-agent/ │ │ ├── src/ │ │ │ └── test/ │ │ │ └── java/ │ │ │ └── samples/ │ │ │ └── testng/ │ │ │ └── agent/ │ │ │ ├── AnnotationDemoTest.java │ │ │ ├── AnnotationDemoWithBeforeMethodTest.java │ │ │ ├── FinalDemoTest.java │ │ │ ├── MockStaticExtendsPowerMockTestCaseTest.java │ │ │ ├── MockStaticTest.java │ │ │ ├── NotAnnotatedWithPrepareForTest.java │ │ │ ├── PartialMockingWithBeforeClassTest.java │ │ │ ├── PrivateFinalTest.java │ │ │ ├── SampleServletTest.java │ │ │ └── SystemClassUserTest.java │ │ └── suite.xml │ ├── java11/ │ │ ├── build.gradle │ │ └── mockito-junit4/ │ │ └── src/ │ │ ├── main/ │ │ │ └── java/ │ │ │ └── samples/ │ │ │ └── powermockito/ │ │ │ └── junit4/ │ │ │ └── bugs/ │ │ │ └── github958/ │ │ │ └── OuterClass.java │ │ └── test/ │ │ └── java/ │ │ └── samples/ │ │ └── powermockito/ │ │ └── junit4/ │ │ └── bugs/ │ │ └── github958/ │ │ └── Github958Test.java │ ├── java8/ │ │ ├── build.gradle │ │ ├── easymock-junit4/ │ │ │ └── src/ │ │ │ ├── main/ │ │ │ │ └── java/ │ │ │ │ └── samples/ │ │ │ │ └── powermockito/ │ │ │ │ └── junit4/ │ │ │ │ └── bugs/ │ │ │ │ └── github717/ │ │ │ │ ├── Instance.java │ │ │ │ ├── InstanceFacade.java │ │ │ │ ├── InstanceFacadeImpl.java │ │ │ │ └── InstanceStatus.java │ │ │ └── test/ │ │ │ └── java/ │ │ │ └── samples/ │ │ │ └── powermockito/ │ │ │ └── junit4/ │ │ │ └── bugs/ │ │ │ └── github717/ │ │ │ ├── InstanceFacadeImplTest.java │ │ │ └── package-info.java │ │ ├── mockito-junit4/ │ │ │ └── src/ │ │ │ ├── main/ │ │ │ │ └── java/ │ │ │ │ └── samples/ │ │ │ │ └── powermockito/ │ │ │ │ └── junit4/ │ │ │ │ ├── bugs/ │ │ │ │ │ └── github510/ │ │ │ │ │ ├── ClassUsesInterface.java │ │ │ │ │ ├── ConstructorObject.java │ │ │ │ │ └── InterfaceWithStatic.java │ │ │ │ └── largemethod/ │ │ │ │ └── InterfaceMethodExceedingJvmLimit.java │ │ │ └── test/ │ │ │ └── java/ │ │ │ ├── org/ │ │ │ │ └── powermock/ │ │ │ │ └── modules/ │ │ │ │ └── junit4/ │ │ │ │ └── largemethod/ │ │ │ │ └── LargeMethodInInterfaceTest.java │ │ │ └── samples/ │ │ │ └── powermockito/ │ │ │ └── junit4/ │ │ │ └── bugs/ │ │ │ └── github510/ │ │ │ ├── Github510Test.java │ │ │ └── package-info.java │ │ ├── mockito-junit4-agent/ │ │ │ └── src/ │ │ │ ├── main/ │ │ │ │ └── java/ │ │ │ │ └── samples/ │ │ │ │ └── powermockito/ │ │ │ │ └── junit4/ │ │ │ │ └── bugs/ │ │ │ │ └── github510/ │ │ │ │ ├── ClassUsesInterface.java │ │ │ │ └── InterfaceWithStatic.java │ │ │ └── test/ │ │ │ └── java/ │ │ │ └── samples/ │ │ │ └── powermockito/ │ │ │ └── junit4/ │ │ │ └── bugs/ │ │ │ └── github510/ │ │ │ └── ClassUsesInterfaceTest.java │ │ └── mockito-junit4-rule-xstream/ │ │ └── src/ │ │ ├── main/ │ │ │ └── java/ │ │ │ └── samples/ │ │ │ └── powermockito/ │ │ │ └── junit4/ │ │ │ └── bugs/ │ │ │ └── github510/ │ │ │ ├── ClassUsesInterface.java │ │ │ └── InterfaceWithStatic.java │ │ └── test/ │ │ └── java/ │ │ └── samples/ │ │ └── powermockito/ │ │ └── junit4/ │ │ └── bugs/ │ │ └── github510/ │ │ └── ClassUsesInterfaceTest.java │ ├── junit4/ │ │ └── src/ │ │ └── test/ │ │ └── java/ │ │ └── samples/ │ │ └── powermockito/ │ │ └── junit4/ │ │ └── bugs/ │ │ ├── github352/ │ │ │ ├── GitHub352Test.java │ │ │ ├── MyAbstractTest.java │ │ │ ├── MyTest.java │ │ │ └── package-info.java │ │ ├── github722/ │ │ │ ├── GitHub722Test.java │ │ │ ├── UseJUnitTest.java │ │ │ └── UseTheoriesTest.java │ │ └── github733/ │ │ ├── GitHub733Test.java │ │ └── UseTestAnnotatedTest.java │ ├── mockito/ │ │ ├── build.gradle │ │ ├── inline/ │ │ │ └── src/ │ │ │ ├── main/ │ │ │ │ └── java/ │ │ │ │ └── samples/ │ │ │ │ └── powermockito/ │ │ │ │ └── inline/ │ │ │ │ └── bugs/ │ │ │ │ └── github793/ │ │ │ │ ├── FinalClass.java │ │ │ │ └── StaticClass.java │ │ │ └── test/ │ │ │ ├── java/ │ │ │ │ └── samples/ │ │ │ │ └── powermockito/ │ │ │ │ └── inline/ │ │ │ │ └── bugs/ │ │ │ │ └── github793/ │ │ │ │ ├── MockitoFinalClassMockingTest.java │ │ │ │ ├── PartialMockingExampleTest.java │ │ │ │ └── PowerMockStaticMockingTest.java │ │ │ └── resources/ │ │ │ └── org/ │ │ │ └── powermock/ │ │ │ └── extensions/ │ │ │ └── configuration.properties │ │ ├── junit4/ │ │ │ └── src/ │ │ │ ├── main/ │ │ │ │ └── java/ │ │ │ │ └── samples/ │ │ │ │ └── powermockito/ │ │ │ │ └── junit4/ │ │ │ │ └── bugs/ │ │ │ │ ├── github731/ │ │ │ │ │ ├── AType.java │ │ │ │ │ ├── OptionalInterface.java │ │ │ │ │ └── SomeInterface.java │ │ │ │ ├── github801/ │ │ │ │ │ └── GlobalPowerMockIgnore.java │ │ │ │ └── github806/ │ │ │ │ ├── CustomException.java │ │ │ │ └── DoThrowTMockClass.java │ │ │ └── test/ │ │ │ ├── java/ │ │ │ │ └── samples/ │ │ │ │ └── powermockito/ │ │ │ │ └── junit4/ │ │ │ │ ├── FinalEqualsClass.java │ │ │ │ ├── FinalEqualsClassTest.java │ │ │ │ ├── abstractmocking/ │ │ │ │ │ └── AbstractMethodMockingTest.java │ │ │ │ ├── annotationbased/ │ │ │ │ │ ├── CaptorAnnotationTest.java │ │ │ │ │ ├── ChunkingAndStaticInitializerRemovalTest.java │ │ │ │ │ ├── InjectMocksAnnotationTest.java │ │ │ │ │ ├── MockFinalUsingAnnotationsTest.java │ │ │ │ │ ├── MockFinalUsingAnnotationsWithAnswersTest.java │ │ │ │ │ └── SpyAnnotationTest.java │ │ │ │ ├── argumentmatcher/ │ │ │ │ │ └── ArgumentMatcherTest.java │ │ │ │ ├── bugs/ │ │ │ │ │ ├── ClassLoaderBugTest.java │ │ │ │ │ ├── github510/ │ │ │ │ │ │ └── package-info.java │ │ │ │ │ ├── github583/ │ │ │ │ │ │ ├── ChildClass.java │ │ │ │ │ │ ├── ClassWithInheritanceTest.java │ │ │ │ │ │ ├── ParenClass.java │ │ │ │ │ │ └── package-info.java │ │ │ │ │ ├── github668/ │ │ │ │ │ │ ├── GitHub668Test.java │ │ │ │ │ │ └── package-info.java │ │ │ │ │ ├── github701/ │ │ │ │ │ │ ├── GitHub701Test.java │ │ │ │ │ │ ├── MapWrapper.java │ │ │ │ │ │ ├── OverridesEquals.java │ │ │ │ │ │ └── package-info.java │ │ │ │ │ ├── github704/ │ │ │ │ │ │ ├── PrepareForTestSignedTest.java │ │ │ │ │ │ ├── SomeClassUseSignedClasses.java │ │ │ │ │ │ └── package-info.java │ │ │ │ │ ├── github716/ │ │ │ │ │ │ ├── A.java │ │ │ │ │ │ ├── B.java │ │ │ │ │ │ ├── C.java │ │ │ │ │ │ ├── MyService.java │ │ │ │ │ │ ├── WhenNewWithAnyArgumentsTest.java │ │ │ │ │ │ └── package-info.java │ │ │ │ │ ├── github731/ │ │ │ │ │ │ ├── MockingInterfacesTest.java │ │ │ │ │ │ └── SomeException.java │ │ │ │ │ ├── github781/ │ │ │ │ │ │ ├── EqualsStatic.java │ │ │ │ │ │ ├── GitHub781Test.java │ │ │ │ │ │ └── SpyObject.java │ │ │ │ │ ├── github801/ │ │ │ │ │ │ └── GlobalPowerMockIgnoreTest.java │ │ │ │ │ └── github806/ │ │ │ │ │ ├── DoThrowTest.java │ │ │ │ │ └── package-info.java │ │ │ │ ├── constructor/ │ │ │ │ │ └── InnerConstructorsAreFoundTest.java │ │ │ │ ├── doreturn/ │ │ │ │ │ └── DoReturnTest.java │ │ │ │ ├── enums/ │ │ │ │ │ └── EnumWithConstructorTest.java │ │ │ │ ├── equalsmocking/ │ │ │ │ │ └── EqualsMockingTest.java │ │ │ │ ├── finalmocking/ │ │ │ │ │ ├── MockFinalMethodsCases.java │ │ │ │ │ └── MockFinalNonStaticMethodsTest.java │ │ │ │ ├── getannotation/ │ │ │ │ │ └── GetAnnotationTest.java │ │ │ │ ├── getclass/ │ │ │ │ │ └── GetClassTest.java │ │ │ │ ├── hashcode/ │ │ │ │ │ ├── HashCodeTest.java │ │ │ │ │ └── InnerClassHashCodeTest.java │ │ │ │ ├── jacoco/ │ │ │ │ │ ├── InstanceMethods.java │ │ │ │ │ ├── JacocoCoverageTest.java │ │ │ │ │ ├── StaticMethods.java │ │ │ │ │ └── TargetTest.java │ │ │ │ ├── largemethod/ │ │ │ │ │ └── LargeMethodTest.java │ │ │ │ ├── membermodification/ │ │ │ │ │ └── MemberModificationExampleTest.java │ │ │ │ ├── nested/ │ │ │ │ │ └── NestedClassDefinedInsideTestCaseTest.java │ │ │ │ ├── partialmocking/ │ │ │ │ │ ├── PartialMockingExampleTest.java │ │ │ │ │ ├── PartialMockingRetainsStateTest.java │ │ │ │ │ ├── PrivatePartialMockingExampleTest.java │ │ │ │ │ └── StaticPartialMockingTest.java │ │ │ │ ├── privatemocking/ │ │ │ │ │ ├── PrivateInstanceMockingCases.java │ │ │ │ │ └── PrivateInstanceMockingTest.java │ │ │ │ ├── proxymethod/ │ │ │ │ │ └── ProxyMethodTest.java │ │ │ │ ├── simplemix/ │ │ │ │ │ └── SimpleMixTest.java │ │ │ │ ├── spy/ │ │ │ │ │ └── SpyTest.java │ │ │ │ ├── stacktracecleaner/ │ │ │ │ │ ├── LocationFromStackTraceTest.java │ │ │ │ │ └── SomethingWithStaticMethod.java │ │ │ │ ├── staticandinstance/ │ │ │ │ │ └── StaticAndInstanceDemoTest.java │ │ │ │ ├── staticmocking/ │ │ │ │ │ ├── MockStaticCases.java │ │ │ │ │ └── MockStaticTest.java │ │ │ │ ├── stress/ │ │ │ │ │ └── PowerMockStressTest.java │ │ │ │ ├── system/ │ │ │ │ │ ├── ServiceLoaderTest.java │ │ │ │ │ └── SystemClassUserTest.java │ │ │ │ ├── tostring/ │ │ │ │ │ └── ToStringTest.java │ │ │ │ ├── verify/ │ │ │ │ │ ├── VerifyNoMoreInteractionsTest.java │ │ │ │ │ └── VerifyZeroInteractionsTest.java │ │ │ │ ├── whennew/ │ │ │ │ │ ├── DoesntSupportCreatingMocksInFieldsWhenNewDefect.java │ │ │ │ │ ├── NewFileExampleTest.java │ │ │ │ │ ├── VerifyNewMultipleTimesTest.java │ │ │ │ │ ├── VerifyNewWithoutWhenNewTest.java │ │ │ │ │ ├── WhenNewCases.java │ │ │ │ │ ├── WhenNewCases.java.orig │ │ │ │ │ └── WhenNewTest.java │ │ │ │ └── withsettings/ │ │ │ │ └── WithSettingsTest.java │ │ │ └── resources/ │ │ │ └── org/ │ │ │ └── powermock/ │ │ │ └── extensions/ │ │ │ └── configuration.properties │ │ ├── junit4-agent/ │ │ │ └── src/ │ │ │ └── test/ │ │ │ └── java/ │ │ │ └── samples/ │ │ │ └── powermockito/ │ │ │ └── junit4/ │ │ │ └── agent/ │ │ │ ├── AnnotationUsageTest.java │ │ │ ├── AssertPowerMockRuleDelagatesToOtherRulesTest.java │ │ │ ├── LargeMethodTest.java │ │ │ ├── MemberModificationExampleTest.java │ │ │ ├── MockFinalNonStaticMethodsTest.java │ │ │ ├── MockFinalUsingAnnotationsTest.java │ │ │ ├── MockStaticTest.java │ │ │ ├── MockStaticWithPrivateCtorTest.java │ │ │ ├── PrivateInstanceMockingTest.java │ │ │ ├── StubMethodTest.java │ │ │ ├── SuppressConstructorDemoTest.java │ │ │ ├── SuppressConstructorHierarchyDemoTest.java │ │ │ ├── SystemClassUserTest.java │ │ │ ├── WhenNewTest.java │ │ │ └── github512/ │ │ │ ├── Github512Test.java │ │ │ └── package-info.java │ │ ├── junit4-delegate/ │ │ │ └── src/ │ │ │ └── test/ │ │ │ └── java/ │ │ │ └── powermock/ │ │ │ └── modules/ │ │ │ └── test/ │ │ │ └── mockito/ │ │ │ └── junit4/ │ │ │ └── delegate/ │ │ │ ├── EnclosedTest.java │ │ │ ├── JUnitParamsTest.java │ │ │ ├── MultipleConstructorsTest.java │ │ │ ├── SelfieTest.java │ │ │ ├── SubclassDelegateTest.java │ │ │ ├── SuperClass.java │ │ │ ├── SuppressedMethod.java │ │ │ ├── SuppressedMethodStubbing.java │ │ │ ├── SystemClassUserCases.java │ │ │ ├── SystemClassUserMethod.java │ │ │ ├── WhenNewCaseMethod.java │ │ │ └── parameterized/ │ │ │ ├── FinalDemoTest.java │ │ │ ├── MockFinalUsingAnnotationsTest.java │ │ │ ├── StubMethodTest.java │ │ │ ├── SuppressConstructorDemoTest.java │ │ │ ├── SuppressConstructorHierarchyDemoTest.java │ │ │ ├── SupressMethodExampleTest.java │ │ │ ├── SystemClassUserTest.java │ │ │ └── WhenNewTest.java │ │ ├── junit4-rule-objenesis/ │ │ │ └── src/ │ │ │ └── test/ │ │ │ └── java/ │ │ │ └── samples/ │ │ │ └── powermockito/ │ │ │ └── junit4/ │ │ │ └── rule/ │ │ │ └── objenesis/ │ │ │ ├── Foo.java │ │ │ ├── MockFinalNonStaticMethodsTest.java │ │ │ ├── MockStaticTest.java │ │ │ ├── PowerMockRuleTest.java │ │ │ ├── PrivateInstanceMockingTest.java │ │ │ ├── StaticInitializerExampleTest.java │ │ │ ├── SystemClassUserTest.java │ │ │ ├── WhenNewTest.java │ │ │ └── bugs/ │ │ │ └── github512/ │ │ │ ├── Github512Test.java │ │ │ └── package-info.java │ │ ├── junit4-rule-xstream/ │ │ │ └── src/ │ │ │ └── test/ │ │ │ └── java/ │ │ │ └── samples/ │ │ │ └── powermockito/ │ │ │ └── junit4/ │ │ │ └── rule/ │ │ │ └── xstream/ │ │ │ ├── AssertPowerMockRuleDelagatesToOtherRulesTest.java │ │ │ ├── Foo.java │ │ │ ├── MockFinalNonStaticMethodsTest.java │ │ │ ├── MockStaticTest.java │ │ │ ├── PowerMockRuleTest.java │ │ │ ├── PrivateInstanceMockingTest.java │ │ │ ├── StaticInitializerExampleTest.java │ │ │ ├── SystemClassUserTest.java │ │ │ ├── WhenNewTest.java │ │ │ └── github512/ │ │ │ ├── Github512Test.java │ │ │ └── package-info.java │ │ ├── junit49/ │ │ │ └── src/ │ │ │ └── test/ │ │ │ └── java/ │ │ │ └── samples/ │ │ │ └── powermockito/ │ │ │ └── junit4/ │ │ │ └── rules/ │ │ │ └── JUnit49RuleTest.java │ │ └── testng/ │ │ ├── src/ │ │ │ └── test/ │ │ │ └── java/ │ │ │ └── samples/ │ │ │ ├── powermockito/ │ │ │ │ └── testng/ │ │ │ │ └── staticmocking/ │ │ │ │ ├── MockStaticNotPreparedTest.java │ │ │ │ ├── MockStaticPreparedWithoutMockStaticTest.java │ │ │ │ └── MockitoMockStaticTest.java │ │ │ └── testng/ │ │ │ └── bugs/ │ │ │ └── github656/ │ │ │ ├── GitHub656Test.java │ │ │ └── package-info.java │ │ └── suite.xml │ ├── testng/ │ │ ├── src/ │ │ │ └── test/ │ │ │ └── java/ │ │ │ └── samples/ │ │ │ └── testng/ │ │ │ ├── SimpleBaseTest.java │ │ │ └── bugs/ │ │ │ └── github647/ │ │ │ ├── GitHub647.java │ │ │ ├── SkipExceptionTest.java │ │ │ └── SomeClass.java │ │ └── suite.xml │ └── utils/ │ └── src/ │ └── main/ │ └── java/ │ ├── org/ │ │ └── powermock/ │ │ └── api/ │ │ └── mockito/ │ │ ├── ConfigurationTestUtils.java │ │ └── MockitoVersion.java │ └── samples/ │ ├── Service.java │ ├── abstractmocking/ │ │ └── AbstractMethodMocking.java │ ├── annotationbased/ │ │ ├── AnnotatedClassDemo.java │ │ ├── AnnotationDemo.java │ │ └── testannotations/ │ │ └── RuntimeAnnotation.java │ ├── anonymousmocking/ │ │ ├── MyAbstractClass.java │ │ └── StupidAnonymous.java │ ├── argumentmatcher/ │ │ └── ArgumentMatcherDemo.java │ ├── classhierarchy/ │ │ ├── ChildA.java │ │ ├── ChildB.java │ │ └── Parent.java │ ├── classwithinnermembers/ │ │ └── ClassWithInnerMembers.java │ ├── constructor/ │ │ ├── PrivateConstructorDemo.java │ │ ├── PrivateConstructorInstantiationDemo.java │ │ ├── PublicConstructorDemo.java │ │ └── PublicConstructorWithDependencyDemo.java │ ├── constructorargs/ │ │ └── ConstructorArgsDemo.java │ ├── enummocking/ │ │ ├── AnotherSomeObjectInterfaceImpl.java │ │ ├── EnumWithConstructor.java │ │ ├── MyEnum.java │ │ ├── SomeObjectInterface.java │ │ └── SomeObjectInterfaceImpl.java │ ├── equalswithgetclass/ │ │ └── EqualsWithGetClass.java │ ├── expectnew/ │ │ ├── CreationException.java │ │ ├── ExpectNewDemo.java │ │ ├── ExpectNewOfFinalSystemClassDemo.java │ │ ├── ExpectNewServiceUser.java │ │ ├── ExpectNewWithMultipleCtorDemo.java │ │ ├── ITarget.java │ │ ├── MultiConstructor.java │ │ ├── NewFileExample.java │ │ ├── PrimitiveAndWrapperDemo.java │ │ ├── PrimitiveAndWrapperUser.java │ │ ├── SimpleVarArgsConstructorDemo.java │ │ ├── Target.java │ │ └── VarArgsConstructorDemo.java │ ├── expectvoid/ │ │ └── ExpectVoidDemo.java │ ├── fieldmock/ │ │ └── FieldInitializerDemo.java │ ├── finalmocking/ │ │ ├── FinalDemo.java │ │ ├── HoldingFinalDemo.java │ │ └── StaticHoldingFinalDemo.java │ ├── hashcode/ │ │ └── HashCodeInitializedInCtor.java │ ├── injectmocks/ │ │ ├── DependencyHolder.java │ │ ├── DependencyHolderQualifier.java │ │ ├── InjectDemo.java │ │ ├── InjectDependencyHolder.java │ │ └── InjectDependencyHolderQualifier.java │ ├── innerclassmocking/ │ │ ├── ClassWithNonPrivateInnerClass.java │ │ └── ClassWithPrivateInnerClass.java │ ├── interfacefieldchange/ │ │ └── InterfaceWithStaticFinalField.java │ ├── interfacemethodfinding/ │ │ ├── InterfaceMethodHierarchyUsage.java │ │ └── WsUtil.java │ ├── java/ │ │ └── ClassInsideJavaPackage.java │ ├── largemethod/ │ │ └── MethodExceedingJvmLimit.java │ ├── methodhierarchy/ │ │ ├── MethodInvocationDemo.java │ │ ├── MethodInvocationDemoGrandParent.java │ │ └── MethodInvocationDemoParent.java │ ├── mockpolicy/ │ │ ├── ResultCalculator.java │ │ ├── SimpleClassWithADependency.java │ │ ├── SomeClassWithAMethod.java │ │ ├── SomeClassWithAMethodParent.java │ │ └── frameworkexample/ │ │ ├── NativeResult.java │ │ ├── SimpleFramework.java │ │ └── SimpleFrameworkUser.java │ ├── nativemocking/ │ │ ├── NativeMockingSample.java │ │ └── NativeService.java │ ├── newmocking/ │ │ ├── MyClass.java │ │ ├── NewDemo.java │ │ ├── SomeDependency.java │ │ └── StupidNew.java │ ├── nice/ │ │ └── NiceDemo.java │ ├── overloading/ │ │ ├── OverloadedMethodsExample.java │ │ ├── OverloadingDemo.java │ │ ├── StaticAndInstanceMethodWithSameName.java │ │ └── StaticAndInstanceMethodWithSameNameUser.java │ ├── packageprivate/ │ │ └── PackagePrivateClass.java │ ├── partialmocking/ │ │ ├── MockSelfDemo.java │ │ ├── MockSelfDemoSubClass.java │ │ ├── MockSelfDemoWithSubClass.java │ │ ├── MockSelfWithNoDefaultConstructorDemo.java │ │ ├── MockWithStaticStateDemo.java │ │ ├── PartialMockingExample.java │ │ ├── PartialMockingWithConstructor.java │ │ └── PrivatePartialMockingExample.java │ ├── powermockignore/ │ │ └── PowerMockIgnoreDemo.java │ ├── privateandfinal/ │ │ ├── PrivateFinal.java │ │ └── PrivateFinalOverload.java │ ├── privatefield/ │ │ ├── MockSelfPrivateFieldServiceClass.java │ │ └── SimplePrivateFieldServiceClass.java │ ├── privatemocking/ │ │ └── PrivateMethodDemo.java │ ├── reflection/ │ │ ├── ReflectionInstantiator.java │ │ ├── UseMe.java │ │ └── UseMeInterface.java │ ├── rule/ │ │ ├── SimpleThing.java │ │ ├── SimpleThingCreator.java │ │ ├── SimpleThingImpl.java │ │ └── ThingToTest.java │ ├── servletmocking/ │ │ └── SampleServlet.java │ ├── simplemix/ │ │ ├── SimpleMix.java │ │ ├── SimpleMixCollaborator.java │ │ ├── SimpleMixConstruction.java │ │ └── SimpleMixUtilities.java │ ├── simplereturn/ │ │ ├── SimpleReturnExample.java │ │ └── SimpleReturnExampleUser.java │ ├── singleton/ │ │ ├── SimpleStaticService.java │ │ ├── StaticExample.java │ │ ├── StaticHelper.java │ │ ├── StaticService.java │ │ └── StaticWithPrivateCtor.java │ ├── spy/ │ │ └── SpyObject.java │ ├── staticandinstance/ │ │ ├── StaticAndInstanceDemo.java │ │ └── StaticAndInstanceWithConstructorCodeDemo.java │ ├── staticinitializer/ │ │ ├── AbstractStaticInitializerExample.java │ │ ├── EvilStaticInitializerExample.java │ │ ├── InterfaceComputation.java │ │ ├── SimpleStaticInitializerExample.java │ │ └── StaticInitializerExample.java │ ├── stress/ │ │ ├── ClassWithStatic.java │ │ └── StressSample.java │ ├── strict/ │ │ └── StrictDemo.java │ ├── suppressconstructor/ │ │ ├── AppaleList.java │ │ ├── InvokeConstructor.java │ │ ├── SuppressConstructorDemo.java │ │ ├── SuppressConstructorHeirarchyEvilGrandParent.java │ │ ├── SuppressConstructorHierarchy.java │ │ ├── SuppressConstructorHierarchyParent.java │ │ ├── SuppressConstructorSubclassDemo.java │ │ ├── SuppressNonParentConstructorDemo.java │ │ └── SuppressSpecificConstructorDemo.java │ ├── suppresseverything/ │ │ └── SuppressEverything.java │ ├── suppressfield/ │ │ ├── DomainObject.java │ │ ├── ItemRepository.java │ │ └── SuppressField.java │ ├── suppressmethod/ │ │ ├── SuppressMethod.java │ │ ├── SuppressMethodExample.java │ │ └── SuppressMethodParent.java │ ├── swing/ │ │ ├── ReallySimpleSwingDemo.java │ │ └── SimpleSwingDemo.java │ ├── system/ │ │ └── SystemClassUser.java │ └── whitebox/ │ └── ClassWithPowerMockGeneratedConstructor.java └── version.properties ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/ISSUE_TEMPLATE.md ================================================ Hey there and thank you for using PowerMock Please read the following tips before filing an issue: Is this something you can debug and fix? ------------------------------------------------------- Can you see anything in the logs? Can you debug why this happens? **Send a pull request**! Bug fixes and documentation fixes are very welcome. Is this question about PowerMock usage? --------------------------------------- The better way to ask question: * The PowerMock [mailing-list](https://groups.google.com/forum/#!forum/powermock/) * [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**.) None of the above, want to create a GitHub issue ------------------------------------------------------------------ Issues should always have a [Short, Self Contained, Correct (Compilable)](http://sscce.org), Example (same as any question on stackoverflow.com) In order to help us to clarify issue can you answer the following question: What steps will reproduce the problem? What is the expected output? What do you see instead? What version of the product are you using? ================================================ FILE: .github/dependabot.yml ================================================ version: 2 updates: - package-ecosystem: "gradle" directory: "/" schedule: interval: "weekly" - package-ecosystem: "github-actions" directory: "/" schedule: interval: "weekly" ================================================ FILE: .github/workflows/gradle-wrapper-validation.yml ================================================ name: "Validate Gradle Wrapper" on: [push, pull_request] jobs: validation: name: "Gradle wrapper validation" runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: gradle/wrapper-validation-action@v1 ================================================ FILE: .gitignore ================================================ target *.iws *.ipr *.iml .classpath .project .settings .springBeans repo .idea **/build/** .gradle **/out/** **/classes/** **/bin/** ================================================ FILE: .travis.yml ================================================ # More details on how to configure the Travis build # https://docs.travis-ci.com/user/customizing-the-build/ # Speed up build by leveraging travis caches cache: directories: - $HOME/.gradle/caches/ - $HOME/.gradle/wrapper/ # Note that OracleJDK 9 is available for jdk_switcher only on Trusty. # https://github.com/travis-ci/travis-ci/issues/7253#issuecomment-283671037 dist: trusty group: edge language: java matrix: include: - jdk: oraclejdk8 env: - SKIP_RELEASE=true - powermock.byte-code-framework=Javassist - jdk: oraclejdk9 env: - SKIP_RELEASE=true - powermock.byte-code-framework=Javassist - jdk: oraclejdk8 #Below skips the installation step completely (https://docs.travis-ci.com/user/customizing-the-build/#Skipping-the-Installation-Step) #We need it because otherwise Travis CI injects an awkward './gradlew assemble' step into the CI workflow #We want to control and decide what Gradle tasks are executed install: - true script: # We are using && below on purpose # ciPerformRelease must run only when the entire build has completed # This guarantees that no release steps are executed when the build or tests fail - ./gradlew assemble -s -PcheckJava6Compatibility && ./gradlew -i -s check && ./gradlew -i ciPerformRelease ================================================ FILE: CONTRIBUTING.md ================================================ # Contributing to PowerMock # First 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. ## Content ## * [If looking for support](#if-looking-for-support) * [Pull request criteria](#pull-request-criteria) * [General info](#general-info) * [More on pull requests](#more-on-pull-requests) ## If looking for support ## Search / Ask question on [stackoverflow](https://stackoverflow.com/questions/tagged/powermock) Go to the PowerMock [mailing-list](https://groups.google.com/forum/#!forum/powermock/) (moderated) Issues should always have a [Short, Self Contained, Correct (Compilable)](http://sscce.org), Example (same as any question on stackoverflow.com) ## Pull request criteria ## * 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. * Use `@since` tags for new public APIs * Include tests * Document public APIs with examples * 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. * For new features consider adding new documentation item in `PowerMock`/`PowerMockito` class. * Also, look at the [GitHub's Pull Request guide](https://github.com/blog/1943-how-to-write-the-perfect-pull-request) ## General info ## * Comment on issues or pull requests * 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. * Also, don't hesitate to ask questions on the mailing list - that helps us improve javadocs/FAQ. * Please suggest changes to javadoc/exception messages when you find something unclear. * If you miss a particular feature in PowerMock - browse or ask on the mailing list, show us a sample code and describe the problem. * 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. * 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. * 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. ## More on pull requests ## * On pull requests, please document the change, what it brings, what is the benefit. * **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. 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_. _Exemple gratia_: ``` Fixes #777 : The new feature Fixes #777 : Refactors this part of PowerMock to make feature possible ``` * 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. * 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. * 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). * 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/). ================================================ FILE: LICENSE.txt ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2007-2017 PowerMock Contributors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: README.md ================================================ ![PowerMock](powermock.png) [![Build Status](https://travis-ci.org/powermock/powermock.svg?branch=master)](https://travis-ci.org/powermock/powermock) [![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) [ ![Download](https://api.bintray.com/packages/powermock/maven/powermock/images/download.svg) ](https://bintray.com/powermock/maven/powermock/_latestVersion) [![Javadoc](https://javadoc-emblem.rhcloud.com/doc/org.powermock/powermock-core/badge.svg)](http://www.javadoc.io/doc/org.powermock/powermock-core) Writing 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. PowerMock 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. When 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. Please 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. ## News * 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. * 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). * 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. * 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. * 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/) [Older News](https://github.com/powermock/powermock/wiki/OldNews) ## Documentation * [Getting Started](https://github.com/powermock/powermock/wiki/Getting-Started) * [Downloads](https://github.com/powermock/powermock/wiki/Downloads) * [Motivation](https://github.com/powermock/powermock/wiki/Motivation) * Javadoc * [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)) * [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)) * [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)) * [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)) * Common * [PowerMock Configuration](https://github.com/powermock/powermock/wiki/PowerMock-Configuration) * [Bypass Encapsulation](https://github.com/powermock/powermock/wiki/Bypass-Encapsulation) * [Suppress Unwanted Behavior](https://github.com/powermock/powermock/wiki/Suppress-Unwanted-Behavior) * [Test Listeners](https://github.com/powermock/powermock/wiki/Test-Listeners) * [Mock Policies](https://github.com/powermock/powermock/wiki/Mock-Policies) * [Mock system classes](https://github.com/powermock/powermock/wiki/Mock-System) * [EasyMock](https://github.com/powermock/powermock/wiki/EasyMock) * [Mockito](https://github.com/powermock/powermock/wiki/Mockito) * [TestNG](https://github.com/powermock/powermock/wiki/TestNG) * [Delegate to another JUnit Runner](https://github.com/powermock/powermock/wiki/JUnit_Delegating_Runner) * [Bootstrap using a JUnit Rule](https://github.com/powermock/powermock/wiki/PowerMockRule) * [Bootstrap using a Java Agent](https://github.com/powermock/powermock/wiki/PowerMockAgent) * [OSGi](https://github.com/powermock/powermock/wiki/osgi) * [Release Notes](https://github.com/powermock/powermock/wiki/ReleaseNotes) * [FAQ](https://github.com/powermock/powermock/wiki/FAQ) ## Contributing to PowerMock Please, read [the guideline](CONTRIBUTING.md) for a new contributor before start. ### Support and discussion Join the mailing-list [here](http://groups.google.com/group/powermock) for questions, feedback and support. ================================================ FILE: build.gradle ================================================ buildscript { repositories { mavenCentral() jcenter() maven { url 'https://repo.spring.io/plugins-release' } maven { url 'https://plugins.gradle.org/m2/' } } dependencies { classpath 'org.springframework.build.gradle:propdeps-plugin:0.0.7' classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.8.4' classpath 'net.researchgate:gradle-release:2.4.0' classpath 'com.github.jengelman.gradle.plugins:shadow:1.2.4' classpath 'org.shipkit:shipkit:2.3.4' classpath 'ru.vyarus:gradle-animalsniffer-plugin:1.4.1' } } ext{ gradleScriptDir = "${rootProject.projectDir}/gradle" byteBuddy = "1.12.7" easymockVersion = "4.0.1" hamcrestVersion = "1.3" assertjVersion = "2.6.0" cglibVersion = "3.2.9" objenesisVersion = "3.2" javassistVersion = "3.27.0-GA" junitVersion = "4.12" junitRulesVersion = "4.8.2" testngVersion = "6.9.10" xstreamVersion = "1.4.10" mockitoVersion = "4.3.1" servletVersion = "2.5" jacocoVersion = "0.7.7.201606060606" eclipseJdt = "3.3.0-v_771" checkstyleVersion= "7.6.1" systemRulesVersion="1.18.0" } apply plugin: 'org.shipkit.java' description = 'PowerMock allows you to unit test code normally regarded as untestable.\n' + ' For instance it is possible to mock static methods, remove static initializers, allow mocking without dependency\n' + ' injection and more.\n' + ' PowerMock works by bytecode manipulation.\n' + ' PowerMock also contain some utilities that gives you easier access to an objects internal state.\n' + ' PowerMock can be used to test otherwise untestable code and also to achieve a cleaner separation between test\n' + ' and production code.' apply from: "${gradleScriptDir}/version.gradle" allprojects{ apply plugin: 'propdeps-idea' } apply from: "${gradleScriptDir}/modules.gradle" jar{ enabled = false } task wrapper(type: Wrapper) { gradleVersion = '4.10.2' } ================================================ FILE: config/checkstyle/checkstyle.xml ================================================ ================================================ FILE: docs/changelog.txt ================================================ Change log 2.0.0 * PowerMockito changes: ** `verifyStatic` is replaced by `verifyStatic(Class)` ** `mockStatic` does not reset mocking process anymore. As result you may get the `UnfinishedVerificationException` or `UnfinishedStubbingException` ** Possible incapability due toString methods returns by default name of mocked. Change log 1.7.1 * Fixed #832 Provide a new API for verifying static mock and deprecate old for Mockito Change log 1.7.0 ----------------------------- * Added supporting Mockito 2.8.9 for PowerMock 2.x (thanks to Gregor Stamac @gstamac for pull request) * Added supporting global ignore via configuration (issue # #801) * Added supporting org.mockito.internal.creation.bytebuddy.InlineByteBuddyMockMaker via PowerMock configuration (issues #793, #774) * Optimizations in powermock-reflect (thanks to Roman Leventov @leventov for pull request) (#724) * Migrated from Maven to Gradle (#728) * 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. * Fixed issue #722 IllegalArgumentException is output to standard error (thanks to Kotaro Nanri @k-nanri for pull request) * Fixed issue #717 Regression: MethodNotFoundException * Fixed issue #731 No methods matching the name(s) get were found in the class hierarchy for interfaces * Fixed issue #753 fix to upgrade code to be compatible with later versions of Mockito (thanks to emmaLP @emmaLP for pull request) * Fixed issue #763 whenNew not matching constructor when null is passed as first or last argument. (thanks to @podarsmarty podarsmarty for pull request) * Fixed issue #781 Call mocked equals static method instead of real (thanks to @Ilya-Gh Ilya Ghirici for pull request) * Fixed issue #772: PowerMockIgnorePackagesExtractorImpl should visit interfaces. (thanks to François Jacques @hypnoce for pull request) * 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 Change log 1.6.6 (2016-11-04) ----------------------------- * Added support for setting private static final fields in Whitebox.setInternalState (thanks to Andrei Petcu @andreicristianpetcu for pull request) * Added support for specifying constructor parameters for Mockito for whenNew case (Only mock specific calls to new #31) * Fixed #668 @Mock fields are not injected anymore (1.6.5 regression) * Fixed #676 Using Powermock with Roo/AspectJ gives NullPointerException (thanks to Sebastian Saip @ssaip for pull request) * Fixed #656 TooManyActualInvocations when class is prepared for test. * Fixed #695 ClassNotFoundException when loading cglib enhanced classes created by Spring * Fixed Java 6 compatibility issue in org.powermock.utils.StringJoiner (which accidentally referenced Java 7 API's) * Fixed #701 StackOverflowError mocking final class extending non-public abstract class overriding equals method * Fixed #707 PowerMock should ignore and keep synthetic method/fields when modifies class * Fixed #645 jacoco offline instrumentation incompatibility with powermock byte-code manipulation when using @SuppressStaticInitializationFor * Fixed #704 PowerMockito 1.6.5 throws java.lang.SecurityException signer information mismatch * Refactoring: Move ProxyFramework from api modules to `reflect` module. * Renamed org.powermock.reflect.internal.WhiteboxImpl.getAllMetodsExcept to org.powermock.reflect.internal.WhiteboxImpl.getAllMethodsExcept (typo) * 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) * Upgraded Assertj dependency from 3.4.1 to version 3.5.2 * Upgraded Javaassist dependency from 3.20.0-GA to version 3.21.0-GA * Upgraded Objenesis dependency from 2.2 to version 3.4 Change log 1.6.5 (2016-04-30) ----------------------------- * Add ability to chain returns with doReturn() (thanks to "gauee" for pull request) (issue #599) * Code quality improvement, @Override annotation should be used on any method overriding (since Java 5) or implementing (since Java 6) another one * PowerMockRunner now processes JUnit Rules correctly (thanks to Stefan Birkner for pull request) (issue 427) * Added support for @TestSubject in EasyMock API. This is the equivalent of @InjectMocks in Mockito (big thanks to Arthur Zagretdinov for pull request) * Added experimental support for mockito 2.x * 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) * Fix #214: Whitebox.invokeConstructor may not work as expected with overloaded constructors * Fix #352: PowerMockRunner should run tests defined in super class * Fix #510: Static method mocking with Mockito 1.9.5 and Powermock fails with Java 8 Consumer Interface * Fix #512: @PrepareForTest on method not working with PowerMockRule * Fix #652: PowerMock stubbing void method don't work for overloaded methods * Fix #648: TestNG SkipException doesn't work with PowerMock * Fix #634/#632: Add workaround as fix for Mockito 1+. Wait fix from Mockito team for Mockito 2. * Fix #590: suppress(method) doesn't work on a @Spy/PowerMockito.spy * Upgraded commons-logging dependency to version 1.2 * Upgraded objenesis dependency to version 2.2 * Upgraded TestNG dependency to version 6.9.10. * Upgraded xStream dependency to version 1.4.9. * ASM for PowerMock Javaagent repackaged from new version 5.0.4 Change log 1.6.4 (2015-12-11) ----------------------------- * DelegatingPowerMockRunner now implements Filterable interface to allow running for example individual test methods (thanks to chang-chao for pull request) * Fixed jacoco/powermock integration issue (thanks to Evgeny Astafyev for pull request) * Improvements to StackTraceCleanerProvider which cleans powermock classes from a stack trace * Replaced usage of uberjar mockito-all with mockito-core (thanks to Petr Široký and René Scheibe for helping out) * Code quality improvement, constructors only call non-overridable methods (thanks to Christian Ivan for pull request) Change log 1.6.3 (2015-10-02) ---------------------------- * Mock name in @Mock(name="abc") annotations are no longer ignored for the Mockito API extension * Fixed NPE in withArguments() constructor (thanks to Tomoyuki Saito for pull request) * Upgraded Javassist dependency to version 3.20.0-GA. * Using soft reference in classloader cache * MockClassloader now extends Javassist Loader classloader to implement findClass etc * PowerMock now works better with ByteBuddy (issue 579) * This allows creating mocks in the applyInterceptionPolicy method of MockPolicy, which in turn allows using MockPolicy together with PowerMockRule (issue 581). * Upgraded the powermock-easymock extension to use EasyMock 3.4 Change log 1.6.2 (2015-01-03) ---------------------------- * PowerMockRunnerDelegate annotation now uses @Inherited (thanks to Henrik Kaipe for pull request) * Tests can now have multiple constructors (thanks to Henrik Kaipe for pull request) * Cleanup pom files and added version numbers (thanks to René Scheibe for pull request) * 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) * Packaged some of the Mocktio classes internally since Mockito is moving from CgLib to ByteBuddy. (thanks to Brice Dutheil for the pull request). * Upgraded Javassist dependency to version 3.19.0-GA. * Upgraded TestNG dependency to version 6.8.21. * The PowerMock EasyMock Api now depends on EasyMock 3.3.1. Change log 1.6.1 (2015-01-03) ---------------------------- * 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. * PowerMock JUnit Module now supports JUnit 4.12 (Thanks to Henri Tremblay for the pull request). * Upgraded TestNG from 6.8.8 to 6.8.13. * Fixed Mockito 1.10.9+ incompatibility, by repackaging CGLIB MockMaker (issue 524). Thanks to Brice Dutheil for the pull request. Change log 1.6.0 (2014-11-27) ----------------------------- * It's now possible to verify private final overloaded methods in the Mockito Extension API. For example: verifyPrivate(tested).invoke(method(MyClass.class, "myOverloadedMethodName", String.class, String.class)).withArguments(anyString(), captor.capture()); * Upgraded Mockito API extension to work with version Mockito 1.10.8. * PowerMock now builds for Java 6 and not Java 5. * 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. 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: @RunWith(PowerMockRunner.class) @PowerMockRunnerDelegate(Parameterized.class) // Use the parameterized JUnit in combination with the PowerMockRunner @PrepareForTest(SuppressConstructorDemo.class) public class SuppressConstructorDemoTest { ... } (Big thanks to Henrik Kaipe for this excellent pull request). Change log 1.5.6 (2014-09-04) ----------------------------- * 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). * Final equals methods should now work with Mockito and not cause stackoverflow (thanks to Peer Hartmann for pull request) * Removed redundant cast when creating a class replicas for final system classes. * Cleaned up some code in the ClassReplicaCreator class * 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). * PowerMockIgnore is now taken into account when using the Java Agent PowerMockRule. * Improved java agent automatic bootstrap mechanism to work better for newer JDK's. * PowerMock now finds default methods in Java 8 (issue 513). * Annotations such as @Mock and @InjectMocks can now be used with the JUnit Java Agent. * Proxy framework is loaded from the the JUnit Java Agent which means that all Whitebox methods work as expected. Change log 1.5.5 (2014-05-28) ----------------------------- * Updated OSGi metadata * MockClassLoader.getResources no longer loads same file twice (thanks to Kelsey Rider for the patch) * Added getResourceAsStream and getResource to DeferSupportingClassLoader which defers loading to the deferring classloader. * 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). * Upgraded to Javassist 3.18.2-GA. * Moved project to github (issue 493). * Upgraded to TestNG 6.8.8. * Removed accidental JUnit dependency to Objenesis and XStream classloading projects. Change log 1.5.4 (2014-01-29) ----------------------------- * Removed OSGi metadata because they didn't work properly * Fixed an issue when setting up private method expectations with multiple arguments in Mockito. * Added support for suppressing static initializers using TestNG (issue 256) (thanks to majorpetya for the patch). * PowerMock Java agent works in Java 8 (issue 475) (thanks to iirekm for help). * Moved bundled asm packages into the powermock package for the PowerMock Java Agent module to avoid classloading issues. Change log 1.5.3 (2014-01-10) ----------------------------- * Added OSGi metadata to manifest files (issue 204) (thanks to Gabor Liptak for patch) * Upgraded to Javassist 3.18.1-GA. * Test case with expectedExceptions no longer fails when using PowerMock with TestNG (issue 366) (thanks to majorpetya for the patch). * Fixed a classloading issue with the JUnit4TestSuiteChunkerImpl (thanks to Robert Gay for the patch) * Updated objenesis to version 2.1 Change log 1.5.2 (2013-11-18) ----------------------------- * Fixed PowerMock OOM (OutOfMemory) issues with Mockito (big thanks to Henrik Karlsson for the patch). * PowerMock EasyMock extension API now supports EasyMock version 3.2. * Added jacoco agent to be deferred by the PowerMock classloader * Updated TestNG dependency to 6.8.7. Change log 1.5.1 (2013-06-19) ----------------------------- * Maven no longer adds classpath to jar manifests when building PowerMock (issue 413). * PowerMockRunner now supports both MethodRules and TestRules to comply with JUnit 4.11 (thanks to "Boris Code" for the patch) (issue 419). * Slf4j MockPolicy in Mockito now works again (issue 431). * Removed synchronized from all MockGateway methods in order to make it work with multi-threaded Mockito. * The PowerMock runner for JUnit now supports assumeTrue(..) statements (issue 408). * Mocked system classes are now invoked when it's casted into another (non-final) type (thanks to Jonatan Jonsson for the patch) (issue 445). * TestNG state is cleaned up in a better way when a test fails (thanks to Jonatan Jonsson for the patch). * 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. * Upgraded Javassist to version 1.8.0-GA. * Upgraded to TestNG module to version 6.8.5 * Upgraded to JUnit module to version 4.11 Change log 1.5 (2012-12-04) --------------------------- * Added var-args to mockStatic in the PowerMockito API. You can now do: mockStatic(A.class, B.class, C.class); * Suppression is now working for overridden methods (issue 364, 51). Thanks to hpbeem for the patch. * PowerMock junit module now supports JUnit rules for version 4.9+ (issue 344). Thanks to Andreas Kutschera for the patch. * Fixed is with PowerMock JUnit runner that failed to parse JUnit versions including characters such as 4.9b2. (issue 381). * Mockito extension API now uses Mockito 1.9.5 (issue 398) * Updated TestNG dependency to version 6.8 * 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). * Upgraded to Javassist 3.17.1-GA, this means that PowerMock works in Java 7! Change log 1.4.12 (2012-04-05) ------------------------------ * Really added missing class, PowerMockTestCase, to testng full release jar (issue 327). * PowerMock JUnit module now works with JUnit 4.10 (thanks to Diego Coronel for the patch) (issue 367) * Changed name from org.powermock.api.mockito.mockpolicies.Slf4jMockPolicy to org.powermock.api.mockito.mockpolicies.Slf4jMockPolicy in the Mockito extension API. * Upgraded Javassist to version 3.16.1.GA. * 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). * Updated TestNG dependency to version 6.4 Change log 1.4.11 (2012-01-05) ------------------------------ * Fixed an OutOfMemory issue in PowerMockRunner (issue 346). * Added Sfl4jMockPolicy to the Mockito extension API, thanks to Alexandre Normand for the patch. * Replaced ${version} to ${project.version} in all pom files (thanks to pvdissel for the patch) (issue 287). * Added work-around to stub some final system classes (such as java.util.UUID) (issue 354). * Improved the PowerMock Java agent support. It should now work together with multiple java agents (thanks to Magnus Jungsbluth for the patch) (issue 357). * Upgraded TestNG module to 6.3.1. * Upgraded EasyMock extension API to use version 3.1 of EasyMock. This version should fix a couple of OutOfMemory issues. * PowerMockito is updated to use Mockito 1.9.0 * setUp-method with @Before annotation is no longer executed twice when extending TestCase (issue 356) * Upgraded classloader xstream deepcloner to XStream 1.4.2 (issue 345) Change log 1.4.10 (2011-08-23) ------------------------------ * Added missing class, PowerMockTestCase, to testng full release jar (issue 327). * Fixed test initialization error when using PowerMock Mockito API in Ant (issue 333). * Upgraded to Javassist 3.15 GA (issue 338). * Upgraded TestNG module to TestNG 6.2. * Mockito @InjectMocks annotations on superclasses of test class are no longer ignored (issue 343). * 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). * PowerMockito now works with Mockito 1.9-rc1 but will not include the new artifact by default because it's still rc (issue 339). * Removed PowerMockRule from full jar in release process (issue 325). Change log 1.4.9 (2011-05-02) ----------------------------- * Fixed an issue when mocking system classes containing fields of type Class, Classloader or synthetic fields such as java.util.ServiceLoader. * TestNG PowerMockObjectFactory now sets the thread context classloader to the PowerMock mock classloader (issue 315). * 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). * Upgraded TestNG module to TestNG 6.0.1 (issue 316). * Fixed an issue with the PowerMock JUnit runner that prevented a JUnit Rule to throw an exception failing the test (issue 311). * Fixed an issue with test state clearing while running a PowerMock enabled test as an Eclipse PDE test (issue 309). * Classloader based PowerMock JUnit Rules now supports suppressing static initializers * Improved state clean-up in TestNG module when extending from PowerMockTestCase. * 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). * 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) * 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. Change log 1.4.8 (2011-02-26) ----------------------------- * Fixed a bug in Whitebox which prevented passing null parameters to methods. * PowerMock now supports mocking static final inner classes and member Enums (issue 95). * 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). * Upgraded TestNG module to TestNG 5.14.6 Change log 1.4.7 (2010-12-27) ----------------------------- * 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). * Fixed a bug which made it impossible to mock private methods with multiple arguments (issue 289). * Removed some unwanted debug messages from the TestNG module. * Updated javadoc in Whitebox and WhiteboxImpl. * 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). * Various improvements to var args handling for both methods and constructors. * Upgraded to Javassist 3.14 (issue 295). * Upgraded junit module to use JUnit 4.8.2 (issue 296). * 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). * Added method "defaultConstructorIn" to the MemberMatcher API so that you can e.g. suppress a default constructor using suppress(defaultConstructorIn(SomeClass.class)) (issue 302). * PowerMock now cleans up EasyMock state after each test case which significantly decreases memory consumption. * PowerMock now cleans up most Mockito state after each test case which decreases memory consumption. * 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. Change log 1.4.6 (2010-10-13) ----------------------------- * 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). * Removed all third-party repositories from the pom's to allow for Maven central syncing. * PowerMock can now be built with Maven 3 (issue 283). * Prepared pom's for Maven central synching. * Upgraded the TestNG module to version 5.14 (issue 275). * Fixed a bug in Whitebox which caused some overriden methods to be treated as overloaded (issue 276). Change log 1.4.5 (2010-08-30) ----------------------------- * The EasyMock API extension should now work when testing Eclipse plugins and running the tests as PDE (JUnit Plugin) tests (issue 264) * Deprecated "andReturn" in the stubber API and added "toReturn" instead. The API now reads e.g. "stub(method("methodName")).toReturn(new Object());" * Added the "toThrow" method to the stubber API. You can now do e.g. "stub(method("methodName")).toThrow(new Exception());" (issue 182) * 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) * 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). * 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) * Upgraded the TestNG module to version 5.13.1. * Whitebox#newInstance(..) now supports instantiating interfaces and arrays. An exception is thrown when trying to instantiate an abstract type (issue 193). Change log 1.4 (2010-07-22) --------------------------- * Implemeted support for mocking instance methods of final system classes with the Mockito extension API (issue 169) * Partial mocking of instance methods in final system classes not having a default constructor now works in the EasyMock extension API (issue 170) * The deep cloner can now clone java.reflect.Method objects correctly to a different classloader. * 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) * Upgraded to Javassist 3.13 (issue 269) * Fixed some problems with Withbox regarding invocation of var args member class constructors and methods (issue 267). * Partial mocking of public static methods now works in Mockito (issue 261) * Better clean-up in test runner which fixes some java.lang.OutOfMemoryError errors in large test suites. Change log 1.3.9 (2010-07-14) ---------------------------------- * Upgraded the Mockito extension API to support Mockito 1.8.5 * Upgraded the EasyMock extension API to support EasyMock 3.0 (issue 259) * Spying with PowerMockito now retains object state (issue 263) Change log 1.3.8 (2010-05-13) ----------------------------- * Fixed a bug in DeepCloner which caused a NullPointerException for arrays containing null values. * Changed groupId of the PowerMock JUnit Rule project to org.powermock.modules. * Included PowerMock rule in the released artifacts * verifyNew with arguments no longer throws NullPointerException when missing expectation in the Mockito extension API. * EasyMock API extension now supports mock creation of classes whose hashCode implementation depends on constructor initialization. * It's now allowed to use verifyNew multiple times just as with verify in standard Mockito (issue 251) * Mockito extension API now supports mocking and stubbing equals and hashcode. * 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. * Upgraded to Javassist 3.12 (issue 254) * Upgraded to TestNG 5.12 (issue 250) * Improved error messages in TestNG when running inside Eclipse Change log 1.3.7 (2010-03-22) ----------------------------- * Added support for JUnit 4.8.1 (issue 226) * Added support for Mockito 1.8.4 * 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) * Changed method signature on "mockStatic" to return void in the Mockito extension API. * 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). * Added support for deep cloning objects containing self references using the DeepCloner. * 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. * Added support for suppressing all constructors in a class using suppress(constructorsDeclaredIn(X.class)). * Added support for suppressing all constructors and methods in a class suppress(everythingDeclaredIn(X.class)). Change log 1.3.6 (2010-03-10) ----------------------------- * Added testng to full release project. * Fixed so that classloader executor supports runnable's. * DeepCloner now supports reference cloning. * DeepCloner now supports cloning enum constants. * DeepCloner now supports cloning standard java types (using simple serialization). * DeepCloner now supports cloning fields in a hierarchy. * DeepCloner now supports cloning class fields. * 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). * Fixed so that you can mock anonymous inner classes with the Mockito API extension (issue 227). * Nested classes declared inside the test case are automatically prepared for test. * Minor improvement in the byte-code manipulation; only package private classes are changed to public. * 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). * Upgraded to Objenesis for powermock-reflect to 1.2. * Fixed so that MockGateway now finds the correct method to invoke when several overloaded method candidates are found (issue 229). * Upgraded to Mockito 1.8.3. * Added support for Mockito annotations @Spy, @Captor and @InjectMocks. * Mockito extension now supports real partial mocking for private (and private final) methods (both static and instance methods) using PowerMockito.doReturn(..), PowerMockito.doThrow(..) etc. * 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);". Change log 1.3.5 (2009-12-13) ----------------------------- * Removed EasyMock maven dependencies from the JUnit legacy runner since they're not needed. * Fixed a bug in WhiteboxImpl#findUniqueConstructorOrThrowException which caused an additional constructor to be found when a class was prepared for test (issue 189). * 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. * Mockito extension API now supports Mockito 1.8.1 & 1.8.2. * 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. * DeepCloner should now support cloning of static final fields on SUN JVM. * Fixed a minor bug in Whitebox#getInternalState so that a better error message is given when the instance argument is null (issue 205). * Fixed some typos in the javadoc of PowerMockito#verifyNew (issue 187). * Fixed so that Whitebox#getInternalState(..) now supports passing in super types as field-type critiera (issue 210). * Fixed so that Whitebox#getInternalState(..) and Whitebox#setInternalState(..) doesn't cause NPE when too many fields matched the criteria (issue 211). * Basic support for TestNG (5.11) implemented. * Fixed so that Whitebox#invokeMethod now works for overridden methods. * Implemented findResource in classloader, this means that you should be able to locate resources in classpath (issue 143). * 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. Change log 1.3.1 (released 2009-10-28) -------------------------------------- * 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. * DeepCloner now supports cloning of one dimensional arrays, primitives, enums and collections. * Test case is now always prepared for test even if no @PrepareForTest annotation is specified * Fixed a bug in Whitebox#setInternalState so that it now works to supply an array when specifying a method name again. * Improved javadoc in Whitebox class * 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). Change log 1.3 (released 2009-10-06) ------------------------------------ * Classes that will have their static initializers suppressed are automatically added to prepare for test in mock policies. * Added a toString implementation for TestMethodResultImpl * Added a toString implementation for TestSuiteResultImpl * 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. * 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. * 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]. * 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. * 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. * 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. * 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. * 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). * 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. * 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). * Upgraded to Javassist 3.10 (3.11 doesn't work with PowerMock due to a bug or backward incompatibility in Javassist). * Fixed a bug in the EasyMock extension API regarding suppression of methods so that it now uses Whitebox.getMethods(..) instead of Whitebox.getMethod(..). * Mocking of static methods in final system classes now works with the Mockito extension (because of a bug fix in Javassist 3.10) * 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. * Implemented support for setting internal state from a context (using Whitebox.setInternalStateFromContext(..)). * Error message differ between static or instance type fields when internal state cannot be set because a field wasn't found. * 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. * You can now mock new instance calls to final system classes in the same was you'd mock any other new instance call. * Improved error message in Whitebox when getting a method or constructor which was not found and no parameter types were supplied. * 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. * Begun working with support for TestNG (thanks to Dan Fabulich for helping us with this). * Deprecated Whitebox#getInternalState(Object object, String fieldName, Class where, Class type), use "Whitebox. getInternalState(Object object, String fieldName, Class where)" instead. * 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. getInternalState(instance, "myFieldName")". * Changed return type of Whitebox#invokeMethod(..) from Object to T. This means that you can avoid cast using e.g. "Whitebox. invokeMethod(..)". * JUnit test runner now supports JUnit 4.7 rules * Upgraded the Mockito extension to use Mockito 1.8 * Created a reusable component (PowerMockIgnorePackagesExtractorImpl) that can be used by test runners to extract which packages that should be ignored in a test case. * Removed mockStatic(Class type, Method method, Method... methods), mockStaticPartial, mockPartial, mock(Class type, Method... methods) & mock(Class type, Method... methods) from the Mockito extension API. You should use PowerMockito.spy instead. * 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. * Mockito extension API support for private methods expectations using PowerMockito.when(..). * 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. * 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. * 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) * 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. * 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. * The method IExpectationSetters expectNew(String fullyQualifiedName, Object... arguments) in the EasyMock extension API changed return type to IExpectationSetters expectNew(String fullyQualifiedName, Object... arguments). * Improved error message for Whitebox#getConstructor when no constructor was found. * Fixed a bug in PowerMockito's CgLibProxyFramework#getUnproxiedType(..) so that it now _really_ returns the unproxied type. * 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). * 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. * Whitebox#getInternalState(..) and Whitebox#setInternalState(..) now uses isAssignableFrom instead of equals when looking for field types. * Added a new api-support project that contains functionality shared between all mock API projects * Mockito extension API now supports suppressing constructors, fields and methods. * 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. * 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. * @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.")). * @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. * 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. * 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). * 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. * Mockito extension API now supports "verifyNoMoreInteractions" and "verifyZeroInteractions" for both instance mocks, class mocks and new instance mocks. * Deprecated setSubstituteReturnValues, getSubstituteReturnValues and addSubtituteReturnValue in MockPolicyInterceptionSettings, you should now use setMethodsToStub, getStubbedMethods and stubMethod instead. * Renamed MockRepository#getSubstituteReturnValue to getMethodToStub and MockRepository#putSubstituteReturnValue to putMethodToStub. * 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. * Removed the deprecated classes "org.powermock.PowerMock" and "org.powermock.Whitebox". * 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. * 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. * Mocking static methods in final system classes works in the Mockito extension API. * AnnotationEnablers only injects to fields that haven't previously been set (i.e. if the field is null). * Added org.powermock.core.spi.listener.AnnotationEnablerListener interface that all AnnotationEnablers must implement. * 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: replace(method(X)).with(method(Y)); // Works only for static methods replace(method(X)).with(invocationHandler); stub(method(X)).andReturn(Y); suppress(methodsDeclaredIn(X.class, Y.class)) suppress(method(X.class, "methodName")) suppress(methods(method(X.class, "methodName"), method(Y.class, "methodName2"))) suppress(methods(X.class, "methodName1", "methodName2")) suppress(field(..)) suppress(constructor(..)); * Deprecated all suppressMethod, suppressField and suppressConstructor methods in the EasyMock extension API. You should now use PowerMock#suppress instead. * PowerMock and PowerMockito now supports stubbing methods (including private methods). Use PowerMock#stub or PowerMockito#stub to accomplish this. * 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. * 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. * Mock policies now supports proxing methods using proxyMethod(..). * Private inner memeber interfaces are not changed to public anymore during the byte-code manipulation session * PowerMock JUnit4 Runner can now instantiate test classes that have a String constructor if the test class extends from junit.framework.TestCase. Change log 1.2.5 (released 2009-05-05) -------------------------------------- * 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. * 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. * 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. * Whitebox#invokeMethod now works without specifying any method name which can increase the refactoring possibilities of the code when invoking unique private methods. * 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")). * All field matcher strategies now throws FieldNotFoundException's instead of IllegalArgumentException's. * Upgraded the Mockito API extension to use Mockito 1.7. * Added mockPartial and mockStaticPartial to the Mockito API to allow for easier creation of partial mocks. Change log 1.2 (released 2009-01-30) ------------------------------------ * Upgraded to Javassist 3.9 * The test result related artifacts were moved from package org.powermock.tests.result to org.powermock.core.spi.testresult. * Structural refactoring to remove Structure 101 XS: Moved org.powermock.api.easymock.internal.proxyframework.spi.ProxyFramework to org.powermock.reflect.internal.proxy.ProxyFramework. * 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. * Whitebox.getMethods(..) and Whitebox.getFields(..) now throw an MethodNotFoundException if no method or field was found. * Error messages when expecting new now works correctly for inner classes. * 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. * Inner member classes declared in class X are automatically prepared for test when X is prepared for test. * 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. * 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. * Fixed problem with infinite recursion with some hashCode implementations * 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. * Fixed a NPE bug in WhiteboxImpl#findSingleFieldUsingStrategy when the startClass was null and a field name haven't been found. Change log 1.1.1 (released 2008-12-15) -------------------------------------- * Fixed maven version issues for the junit4-legacy module and junit3 module. * Fixed a major issue with PowerMock test listeners. The PowerMockTestListener.beforeTestMethod(..) was invoked too late which could cause a NullPointerException when invoking setup methods. * Updated javadoc (some errors in the java doc text). Change log 1.1 (released 2008-12-12) ------------------------------------ * Only signed classes are loaded by the signed supporting CGLib naming policy. * Whitebox.invokeConstructor now propagates InvocationTargetExceptions correctly. * Restructured release assemblies to include just the correct things. * Set sources:jar and javadocs:jar to run on every build. * LoggerTest now creates its test log file in ./target/ directory instead of ./ * 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. * Fixed a serious issue with the classloading hierarchy of PowerMock's JUnit runners. * 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. * 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. * 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. * Exceptions are no longer wrapped in run-time exceptions when invoking a method using Whitebox.invokeMethod(..). * Major refactoring of the classloader structure and delegation. * 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. * 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. * 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. * mockStaticNice(Class clazz, String... methodNames) was renamed to mockStaticPartialNice in the PowerMock API. * 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). * 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. * Updated the tutorial projects to reflect the latest changes in PowerMock. * Errors are propagated correctly when invoking the PowerMock.replay(..) method (i.e. they are no longer wrapped in run-time exceptions). * 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. * Changed so that the default suppression value for methods returning java.lang.String is null to conform with EasyMock and Mockito. * Added Whitebox.getFieldsOfType(..) that can be used to retreive all fields of a particular type in a class hierarchy. * 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. * Whitebox.getMethod(..) sets the accessable flag to true if a method is found. * Added Whitebox.getMethod(Class type, Class... parameterTypes) that let's you get a single method without specifying the method name. * Fixed a bug in WhiteboxImpl.checkIfTypesAreSame(..) that prevented classes to be identified correctly. * 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. * Added spy functionality of final classes and methods to the Mockito API (experimental). * Fixed so that it works to place the PrepareForTest annotation at methods without specifying it at the class-level first. * Added Whitebox.getField(..) method to get a field somewhere in the hierarchy. * Added Whitebox.getFields(..) method to get fields in a class matching a specific name. * 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). * 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. Change log 1.0 (released 2008-11-18) ------------------------------------ * Changed the pom.xml for the tutorial project so that it's now a stand-alone project. * Fixed so that replay all and verify all also works for createMockAndExpectNew. * Added method createStrictMockAndExpectNew and createNiceMockAndExpectNew * Fixed so that suppressMethodCode returns an empty string for methods returning String. * Fixed a bug in the byte-code manipulation of constructors, modifiers that doesn't need change are now preserved. * Added the PrepareEverythingForTestAnnotation, this annotation can be used to tell PowerMock to modify all classes. * MockGateway doMethodCall now also supports java proxy types. * 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. * 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. * Get and setInternalState now separates between class and instance fields, i.e. you cannot set static fields by specifying an instance object. * Updated the tutorial projects to take advantage of the latest features in PowerMock. * Fixed a NPE bug in the AbstractTestClassExtractor.isPrepared(..) method. * The test class is no longer recommended as a PrepareForTest candidate if a NPE occurs inside the test class. * Added createStrictPartialMockForAllMethodsExcept and createNicePartialMockForAllMethodsExcept to the PowerMock API. * The Whitebox API method getAllMethodExcept now traverses the class hierarchy looking for methods. * Fixed a bug in the verifyAll method of the PowerMock API, the state is now properly disposed. * 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. * The suppressConstructorCode method of the PowerMock API was renamed to suppressConstructor. * The suppressMethodCode method of the PowerMock API was renamed to suppressMethod. * The suppressConstructorCodeHierarchy method of the PowerMock API was removed, suppressConstructor(..) automatically suppress the full hierarchy so use this method instead. * Added the PowerMockIgnore annotation that can be used to specify packages or classes that should not be loaded by PowerMock's classloader. * Fixed a bug in MockGateway that prevented wrapper/primitive constructors from being correctly executed. * Added support for specifying parameter types for expectNew and createMockAndExpectNew, createNiceMockAndExpectNew, createStrictMockAndExpectNew. * Added expectNiceNew and expectStrictNew, expectNiceNew can be used with no parameters. * Internal refactoring of the chunking mechanism * 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. Change log 0.9 (released 2008-11-10) ------------------------------------ * Structural refactoring to remove Structure 101 XS: moved WhiteBox implementation to separate class in core and moved IndicateReloadClass * By default Whitebox.getInternalState and Whitebox.setInternalState now traverses the class hierarchy when looking for a field. * Better error message if a NPE is caught in a subclass of a class being prepared for test. * The PrepareForTest annotation now manipulates the full (super) class hierachy by default. This makes it easier to perform mocking of super class methods. * 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. * Fixed a bug that made it impossible to invoke vararg constructors. * createMockAndExpectNew now takes expected arguments as the second parameter. * expectNew takes expected arguments as the second parameter. * Invocations of var arg methods, constructors and expectPrivate now works for sub-types of the declared parameter types. * More consistent error messages when expectNew fails. Error messages now takes the parameters into account. * Renamed mockStaticMethodX to mockStaticPartialX * Added javadoc to the release phase * The JUnit4 legacy runner now throws NoTestsRemainException if no tests are found in the test case. * 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. * 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. * 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. * 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. * Added createNicePartialMockAndInvokeDefaultConstructor and createStrictPartialMockAndInvokeDefaultConstructor to the PowerMock API. * Updated the tutorial projects with * Changed the clean-up mechanisms of PowerMock.replay(..) and PowerMock.verify(..). Should no longer clear unnecessary state. * 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. Change log 0.8.5 (releasd 2008-10-30) ------------------------------------- * Fixed so that it's now possible to mock abstract methods * WhiteBox.getMethod(..) now also returns protected and package-private methods. * Whitebox.invokeMethod can now execute methods in a super class. * Whitebox.invokeMethod no longer throws NullPointerException when an argument is null when the method cannot be found * It's is now possible to use sub-types of method parameters when using Whitebox.invokeMethod. * Tests methods starting with "test" are now executed only if the method is annotated with @Test or if the test class extends from TestCase. * Tests are now executed in the order that they are defined in the test case. Change log 0.8.1 (released 2008-10-26) -------------------------------------- * Added PowerMock API method "createPartialMockAndInvokeDefaultConstructor" that invokes a default constructor after mock creation (even if it's private). * createPartialMock now works as expected * Fixed so that it works to mock package private classes (even if they're signed) * It now works to set a static final field after the static initializes have been suppressed. * Fixed a serious bug that caused classes extending java.lang.Object to be non-mockable. Change log 0.8 (released 2008-10-22) ----------------------------------- * The junit4 test module now work with JUnit 4.5 (although using the old, now deprecated, approach of JUnit 4.4). * Upgraded to EasyMock 2.4 * Upgraded to JavaAssist 3.8.0.GA * WhiteBox invoke method and invoke constructor methods now throws an IllegalArgumentException if the first argument is null. * Replay/verify works as expected when mixing classes and instance mocks. * Better error message when expectNew fails due to too few calls to new when a method was invoked using reflection. * Implemented support for nice mocks. * Added more documentation * expectNew(..).andThrow(..) now works with checked exceptions * Added WhiteBox functionality to instantiate a class without invoking its constructor without using byte-code manipulation. Works in multiple JVM's. * mockMethodX is renamed to createPartialMockX * Fixed the error message that was thrown when a constructor was not found when using mocks as arguments with createPartialMock. * Suppress constructor code now works as expected * 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(..). * Better error message when a class is not replayed when doing expectNew. * Added support to easy suppress several methods in the same class. * doInvokeMethod in PowerMock now catches and deals correctly with InvocationTargetExceptions. * It's now possible to run a single test case in junit4 * Test delegates now implements Sortable * Added support for mocking classes in signed jar files * EasyMock matchers now works in combination with PowerMock's expectPrivate(..) * Added support for invoking var args constructors and methods using Whitebox * Added support for expecting private methods with var args parameter * PowerMock now supports Hamcrest matchers * Exceptions are now propagated correctly from the junit runners. Change log 0.7 (released) ------------------------- * Do not mock hashCode and equals * Added ugly hack for cglib classloading issue with maven * Fixed problems with mocking methods in superclass and modifying multiple classes with same parent * Strict mocking with interface work as expected * Added niceReplayAndVerify * Added logo and improved documentation structure * Follow EasyMock semantics for partial mocking * WhiteBox internalstate support for static fields as expected * Updated assembly and create sources jar files Change log 0.6 (released) ------------------------- * Updated to EasyMock 2.3 and classextension 2.3 * Implemented support for ConstructorArgs * Implemented support for StrictMock * Added possibility to invoke a private method in a subclass of an instance using Whitebox. * 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. * Major internal refactoring. * Fixed major classloading and byte-code manipulation issues. Code coverage tools such as EMMA now works. * Fixed so that it's now possible to invoke private methods using non-primitive and/or non-wrapper values. * Whitebox now throws the correct exceptions to the client and not a wrapped RuntimeException. This means for example that expectNew(..).andThrow(..) works as expected. * 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. ================================================ FILE: docs/generate_javadoc.sh ================================================ #!/bin/sh read -p "Version to generate javadoc for: " version project_names=(powermock-core powermock-api-easymock powermock-api-mockito powermock-api-mockito2 powermock-api-mockito-common\ powermock-reflect powermock-api-support powermock-module-junit4-common powermock-module-junit4 powermock-module-junit4-rule\ powermock-classloading-module powermock-classloading-xstream powermock-module-javaagent powermock-module-junit4-rule-agent\ powermock-module-junit3 powermock-module-junit4-legacy powermock-module-testng-common powermock-module-testng\ powermock-module-testng-agent powermock-modules-impl powermock-classloading-objenesis) echo "Generating Javadoc for version ${version}." for project_name in ${project_names[*]} do echo "Generating for ${project_name}" curl -Ss http://www.javadoc.io/doc/org.powermock/${project_name}/${version} >/dev/null 2>&1 done echo "Completed" ================================================ FILE: docs/release-notes/official.md ================================================ *Release notes were automatically generated by [Shipkit](http://shipkit.org/)* #### 2.0.9 - 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) - PowerMockitoStubberImpl.when throws exceptions with methods using arguments with both primitive and wrapped arguments [(#1077)](https://github.com/powermock/powermock/pull/1077) - Bump byte-buddy from 1.9.10 to 1.10.14 [(#1068)](https://github.com/powermock/powermock/pull/1068) #### 2.0.8 - 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) - Commits: Sean C. Sullivan (2), [Valery Yatsynovich](https://github.com/valfirst) (2), dependabot[bot] (1), [Improver](https://github.com/netbeansuser2019) (1) - [Travis CI] Remove deprecated keyword `sudo` [(#1069)](https://github.com/powermock/powermock/pull/1069) - Upgrade [(#1049)](https://github.com/powermock/powermock/pull/1049) #### 2.0.7 - 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) - [Bugfixes] PowerMock Agent does not work EasyMock 4.x [(#956)](https://github.com/powermock/powermock/issues/956) - Fix missing stackmap frames [(#1043)](https://github.com/powermock/powermock/pull/1043) - VerifyError using the agent for Spock tests [(#1005)](https://github.com/powermock/powermock/issues/1005) - Update dependencies for Java 11 support [(#952)](https://github.com/powermock/powermock/pull/952) - How to resolve "Expected stackmap frame at this location" [(#693)](https://github.com/powermock/powermock/issues/693) #### 2.0.6 - 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) - Upgrade to Javassist 3.27.0-GA [(#1041)](https://github.com/powermock/powermock/pull/1041) #### 2.0.5 - 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) - Use Unsafe to set final static fields, support JDK12+ [(#1026)](https://github.com/powermock/powermock/pull/1026) - Enable local build in IDE without setting ENV [(#1025)](https://github.com/powermock/powermock/pull/1025) #### 2.0.4 - 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) - 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) - [Bugfixes] Not compatible with JUnitParams when using @PowerMockRunnerDelegate(JUnitParamsRunner.class [(#685)](https://github.com/powermock/powermock/issues/685) - Fix Whitebox.getAllInstanceFields returning static fields for classes [(#1011)](https://github.com/powermock/powermock/pull/1011) - Fix changing final fields on Java 12 [(#1010)](https://github.com/powermock/powermock/pull/1010) - Fixes #685 : @PowerMockRunnerDelegate(JUnitParamsRunner.class) [(#998)](https://github.com/powermock/powermock/pull/998) - Fixes #992 Static mocking broken for Mockito >= 2.26.1 [(#997)](https://github.com/powermock/powermock/pull/997) #### 2.0.2 - 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) - 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) - Fixes #973 [SECURITY] Releases are built/executed/released in the context of insecure/untrusted code [(#984)](https://github.com/powermock/powermock/pull/984) - PowerMockAgent does not support java >=10 [(#979)](https://github.com/powermock/powermock/issues/979) - [SECURITY] Releases are built/executed/released in the context of insecure/untrusted code [(#973)](https://github.com/powermock/powermock/issues/973) #### 2.0.1 - 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) - 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) - [Bugfixes] IllegalStateException when inner class has private constructor on Java>8 [(#958)](https://github.com/powermock/powermock/issues/958) - Fixes #958 convert constructors of nested classes to public as well [(#978)](https://github.com/powermock/powermock/pull/978) - Fixes 976: Change to StackTraceCleaner to allow mockito strick stubs … [(#977)](https://github.com/powermock/powermock/pull/977) - Fix date in README [(#967)](https://github.com/powermock/powermock/pull/967) #### 2.0.0 - 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) - 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) - [Major changes] Mockito Public API Support Roadmap [(#726)](https://github.com/powermock/powermock/issues/726) - [Bugfixes] Compile error due to unused import of a class which is not in the dependencies [(#959)](https://github.com/powermock/powermock/issues/959) - [Bugfixes] JDK9, power mockito 2.0.0-beta.5 - final class issue when mocking static method [(#888)](https://github.com/powermock/powermock/issues/888) - [Bugfixes] @Mock annotation from easymock api does not work for two fields of the same type. [(#755)](https://github.com/powermock/powermock/issues/755) - [Enhancements] Removed deprecated code in PowerMock 2.0. [(#839)](https://github.com/powermock/powermock/issues/839) - [Enhancements] JDK 9 support [(#783)](https://github.com/powermock/powermock/issues/783) - Fixes #888: Disable Security of X-Stream [(#962)](https://github.com/powermock/powermock/pull/962) - #959 fix compile error due to unused import of a class which is not i… [(#960)](https://github.com/powermock/powermock/pull/960) - Issue 939: Error with setInternalState and JDK12 "java.lang.NoSuchFieldException: modifiers [(#955)](https://github.com/powermock/powermock/pull/955) - Remove MocksControl.MockType that stayed there [(#951)](https://github.com/powermock/powermock/pull/951) - Preparing PowerMock 2.0 Release without ByteBuddy [ci maven-central-release] [(#948)](https://github.com/powermock/powermock/pull/948) - Use EasyMock exposed MockType instead of the deprecated internal one [(#944)](https://github.com/powermock/powermock/pull/944) - Powermock migration to ByteBuddy [(#910)](https://github.com/powermock/powermock/pull/910) - Update PowerMockAgent.java [(#878)](https://github.com/powermock/powermock/pull/878) #### 2.0.0-RC.5 - 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) - [Bugfixes] Compile error due to unused import of a class which is not in the dependencies [(#959)](https://github.com/powermock/powermock/issues/959) - [Bugfixes] JDK9, power mockito 2.0.0-beta.5 - final class issue when mocking static method [(#888)](https://github.com/powermock/powermock/issues/888) - Fixes #888: Disable Security of X-Stream [(#962)](https://github.com/powermock/powermock/pull/962) - #959 fix compile error due to unused import of a class which is not i… [(#960)](https://github.com/powermock/powermock/pull/960) #### 2.0.0-RC.4 - 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) - Issue 939: Error with setInternalState and JDK12 "java.lang.NoSuchFieldException: modifiers [(#955)](https://github.com/powermock/powermock/pull/955) #### 2.0.0-RC.3 - 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) - No pull requests referenced in commit messages. #### 2.0.0-RC.2 - 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) - Remove MocksControl.MockType that stayed there [(#951)](https://github.com/powermock/powermock/pull/951) #### 2.0.0-RC.1 - 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) - 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) - [Major changes] Mockito Public API Support Roadmap [(#726)](https://github.com/powermock/powermock/issues/726) - [Bugfixes] @Mock annotation from easymock api does not work for two fields of the same type. [(#755)](https://github.com/powermock/powermock/issues/755) - [Enhancements] Removed deprecated code in PowerMock 2.0. [(#839)](https://github.com/powermock/powermock/issues/839) - [Enhancements] JDK 9 support [(#783)](https://github.com/powermock/powermock/issues/783) - Preparing PowerMock 2.0 Release without ByteBuddy [ci maven-central-release] [(#948)](https://github.com/powermock/powermock/pull/948) - Use EasyMock exposed MockType instead of the deprecated internal one [(#944)](https://github.com/powermock/powermock/pull/944) - Powermock migration to ByteBuddy [(#910)](https://github.com/powermock/powermock/pull/910) - Update PowerMockAgent.java [(#878)](https://github.com/powermock/powermock/pull/878) **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) **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) - Use EasyMock exposed MockType instead of the deprecated internal one [(#944)](https://github.com/powermock/powermock/pull/944) **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) - No pull requests referenced in commit messages. **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) - Powermock migration to ByteBuddy [(#910)](https://github.com/powermock/powermock/pull/910) **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) - No pull requests referenced in commit messages. **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) - No pull requests referenced in commit messages. **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) - No pull requests referenced in commit messages. **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) - Update PowerMockAgent.java [(#878)](https://github.com/powermock/powermock/pull/878) **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) - No pull requests referenced in commit messages. **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) - No pull requests referenced in commit messages. **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) - No pull requests referenced in commit messages. **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) - [Bugfixes] @Mock annotation from easymock api does not work for two fields of the same type. [(#755)](https://github.com/powermock/powermock/issues/755) **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) - [Major changes] Mockito Public API Support Roadmap [(#726)](https://github.com/powermock/powermock/issues/726) - [Enhancements] Removed deprecated code in PowerMock 2.0. [(#839)](https://github.com/powermock/powermock/issues/839) - [Enhancements] Use Mockito Shipkit for CD [(#826)](https://github.com/powermock/powermock/issues/826) - Shipkit pom customizations [(#831)](https://github.com/powermock/powermock/pull/831) ================================================ FILE: gradle/java-module.gradle ================================================ repositories { mavenLocal() mavenCentral() jcenter() } group = "org.powermock" apply plugin: 'propdeps' apply plugin: 'propdeps-maven' apply plugin: 'java' targetCompatibility = 1.6 sourceCompatibility = 1.6 tasks.withType(JavaCompile) { options.warnings = false } if (JavaVersion.current() == JavaVersion.VERSION_1_8) { apply plugin: 'checkstyle' checkstyle { toolVersion = checkstyleVersion configFile = rootProject.file('config/checkstyle/checkstyle.xml') } } test{ exclude "**/*Defect*", "**/*TestCase*" } ================================================ FILE: gradle/modules.gradle ================================================ 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 configure(publishableModules) { project -> apply from: "${gradleScriptDir}/java-module.gradle" apply from: "${gradleScriptDir}/publishing/publishable-module.gradle" apply from: "${gradleScriptDir}/publishing/publish.gradle" } def skippedTasksForUnpublishableModules = [ 'generatePomFileForJavaLibraryPublication', 'publishJavaLibraryPublicationToMavenLocal', 'javadoc', 'javadocJar', 'sourcesJar', 'bintrayUpload', 'install' ] def unpublishableModules = allprojects - publishableModules - project(":powermock-release").subprojects configure(unpublishableModules) { project -> project.tasks.all { if(skippedTasksForUnpublishableModules.contains(it.name)) { it.enabled = false } } } def skippedTasksForGenericModules = [ 'generatePomFileForJavaLibraryPublication', 'publishJavaLibraryPublicationToMavenLocal', 'jar', 'javadoc', 'javadocJar', 'sourcesJar' ] def genericModules = project(":powermock-release").subprojects configure(genericModules) { project -> project.tasks.all { if (skippedTasksForGenericModules.contains(it.name)) { it.enabled = false } } } if (project.hasProperty('checkJava6Compatibility') && !System.getenv("SKIP_RELEASE")) { //if we're skipping release, let's also skip checking compatibility (faster builds) configure(publishableModules) { project -> project.apply plugin: 'ru.vyarus.animalsniffer' project.dependencies { signature 'org.codehaus.mojo.signature:java16:1.0@signature' } } } project(":powermock-reflect") { description = "Various utilities for accessing internals of a class." dependencies { compile("org.objenesis:objenesis:${objenesisVersion}") compile("net.bytebuddy:byte-buddy:${byteBuddy}") compile("net.bytebuddy:byte-buddy-agent:${byteBuddy}") testCompile("junit:junit:${junitVersion}") { exclude group: 'org.hamcrest', module: 'hamcrest-core' } testCompile("org.hamcrest:hamcrest-core:${hamcrestVersion}") testCompile("org.assertj:assertj-core:${assertjVersion}") testCompile("cglib:cglib-nodep:${cglibVersion}") } } project(":powermock-core") { description = "Various utilities for accessing internals of a class." dependencies { compile(project(":powermock-reflect")) compile("org.javassist:javassist:${javassistVersion}") compile("net.bytebuddy:byte-buddy:${byteBuddy}") compile("net.bytebuddy:byte-buddy-agent:${byteBuddy}") testCompile("junit:junit:${junitVersion}") { exclude group: 'org.hamcrest', module: 'hamcrest-core' } testCompile("org.hamcrest:hamcrest-core:${hamcrestVersion}") testCompile("org.assertj:assertj-core:${assertjVersion}") testCompile("com.github.stefanbirkner:system-rules:${systemRulesVersion}") testCompile(project(":tests:utils")) testCompile("org.mockito:mockito-core:${mockitoVersion}"){ exclude group: 'net.bytebuddy', module: 'byte-buddy' exclude group: 'net.bytebuddy', module: 'byte-buddy-agent' } } } project(":powermock-api") { jar { enabled = false } } project(":powermock-api:powermock-api-support") { description = "PowerMock API Utility classes." dependencies { compile(project(":powermock-reflect")) compile(project(":powermock-core")) testCompile("junit:junit:${junitVersion}") { exclude group: 'org.hamcrest', module: 'hamcrest-core' } testCompile("org.hamcrest:hamcrest-core:${hamcrestVersion}") testCompile("org.assertj:assertj-core:${assertjVersion}") } } project(":powermock-api:powermock-api-easymock") { description = "PowerMock API for EasyMock." dependencies { compile(project(":powermock-api:powermock-api-support")) compile("cglib:cglib-nodep:${cglibVersion}") compile("org.easymock:easymock:${easymockVersion}") testCompile("junit:junit:${junitVersion}") { exclude group: 'org.hamcrest', module: 'hamcrest-core' } testCompile("org.hamcrest:hamcrest-core:${hamcrestVersion}") testCompile("org.assertj:assertj-core:${assertjVersion}") } } project(":powermock-api:powermock-api-mockito2"){ description = "PowerMock API for Mockito 2.+.." dependencies { compile(project(":powermock-api:powermock-api-support")) compile("org.mockito:mockito-core:${mockitoVersion}"){ exclude group: 'net.bytebuddy', module: 'byte-buddy' exclude group: 'net.bytebuddy', module: 'byte-buddy-agent' } testCompile("junit:junit:${junitVersion}") { exclude group: 'org.hamcrest', module: 'hamcrest-core' } testCompile("org.hamcrest:hamcrest-core:${hamcrestVersion}") testCompile("org.assertj:assertj-core:${assertjVersion}") testCompile(project(":tests:utils")) } } project(":powermock-classloading") { jar { enabled = false } } project(":powermock-classloading:powermock-classloading-base") { description = "Utilities for loading and executing classes." dependencies { compile(project(":powermock-api:powermock-api-support")) compile(project(":powermock-reflect")) compile(project(":powermock-core")) testCompile("junit:junit:${junitVersion}") { exclude group: 'org.hamcrest', module: 'hamcrest-core' } testCompile("org.hamcrest:hamcrest-core:${hamcrestVersion}") testCompile("org.assertj:assertj-core:${assertjVersion}") } } project(":powermock-classloading:powermock-classloading-objenesis") { description = "Performs classloader deep-cloning using Objenesis." dependencies { compile(project(":powermock-classloading:powermock-classloading-base")) testCompile("junit:junit:${junitVersion}") { exclude group: 'org.hamcrest', module: 'hamcrest-core' } testCompile("org.hamcrest:hamcrest-core:${hamcrestVersion}") testCompile("org.assertj:assertj-core:${assertjVersion}") } } project(":powermock-classloading:powermock-classloading-xstream") { description = "Performs classloader deep-cloning using X-Stream." dependencies { compile(project(":powermock-classloading:powermock-classloading-base")) compile("com.thoughtworks.xstream:xstream:${xstreamVersion}") testCompile("junit:junit:${junitVersion}") { exclude group: 'org.hamcrest', module: 'hamcrest-core' } testCompile("org.hamcrest:hamcrest-core:${hamcrestVersion}") testCompile("org.assertj:assertj-core:${assertjVersion}") } } project(":powermock-modules") { jar { enabled = false } } project(":powermock-modules:powermock-module-javaagent") { description = "PowerMock Java agent support." dependencies { compile(project(":powermock-core")) testCompile("junit:junit:${junitVersion}") { exclude group: 'org.hamcrest', module: 'hamcrest-core' } testCompile("org.hamcrest:hamcrest-core:${hamcrestVersion}") testCompile("org.assertj:assertj-core:${assertjVersion}") } jar { manifest { attributes( "Manifest-Version": "1.0", "Premain-Class": "org.powermock.modules.agent.PowerMockAgent", "Agent-Class": "org.powermock.modules.agent.PowerMockAgent", "Can-Retransform-Classes": true, "Can-Redefine-Classes": true ) } } } project(":powermock-modules:powermock-module-junit4-common") { description = "PowerMock support module for all versions of JUnit 4.x." dependencies { compile(project(":powermock-reflect")) compile(project(":powermock-core")) compile("junit:junit:${junitVersion}") { exclude group: 'org.hamcrest', module: 'hamcrest-core' } compile("org.hamcrest:hamcrest-core:${hamcrestVersion}") testCompile("org.assertj:assertj-core:${assertjVersion}") } } project(":powermock-modules:powermock-module-junit4") { description = "PowerMock support module for JUnit 4.x." dependencies { compile(project(":powermock-modules:powermock-module-junit4-common")) compile("junit:junit:${junitVersion}") { exclude group: 'org.hamcrest', module: 'hamcrest-core' } compile("org.hamcrest:hamcrest-core:${hamcrestVersion}") testCompile("org.assertj:assertj-core:${assertjVersion}") testCompile("org.easymock:easymock:${easymockVersion}") } } project(":powermock-modules:powermock-module-junit4-legacy") { description = "PowerMock support module for JUnit 4.0-4.3." dependencies { compile(project(":powermock-modules:powermock-module-junit4-common")) { exclude group: 'junit', module: 'junit' } compile("junit:junit:4.3") { exclude group: 'org.hamcrest', module: 'hamcrest-core' } compile("org.hamcrest:hamcrest-core:${hamcrestVersion}") testCompile("org.assertj:assertj-core:${assertjVersion}") } } project(":powermock-modules:powermock-module-junit4-rule") { description = "PowerMock support module for JUnit 4.x rules." dependencies { compile(project(":powermock-core")) compile(project(":powermock-modules:powermock-module-junit4-common")) provided(project(":powermock-classloading:powermock-classloading-base")) compile("junit:junit:${junitVersion}") { exclude group: 'org.hamcrest', module: 'hamcrest-core' } compile("org.hamcrest:hamcrest-core:${hamcrestVersion}") testCompile("org.assertj:assertj-core:${assertjVersion}") } } project(":powermock-modules:powermock-module-junit4-rule-agent") { description = "PowerMock support module for JUnit 4.x rules with Java agent" dependencies { compile(project(":powermock-core")) compile(project(":powermock-modules:powermock-module-javaagent")) compile("junit:junit:${junitVersion}") { exclude group: 'org.hamcrest', module: 'hamcrest-core' } compile("org.hamcrest:hamcrest-core:${hamcrestVersion}") testCompile("org.assertj:assertj-core:${assertjVersion}") } } project(":powermock-modules:powermock-module-testng-common") { description = "PowerMock module for TestNG. Common classes" dependencies { compile(project(":powermock-reflect")) compile(project(":powermock-core")) compile("org.testng:testng:${testngVersion}") testCompile("org.hamcrest:hamcrest-core:${hamcrestVersion}") testCompile("org.assertj:assertj-core:${assertjVersion}") } } project(":powermock-modules:powermock-module-testng") { description = "PowerMock module for TestNG." dependencies { compile(project(":powermock-core")) compile(project(":powermock-modules:powermock-module-testng-common")) compile("org.testng:testng:${testngVersion}") testCompile("org.hamcrest:hamcrest-core:${hamcrestVersion}") testCompile("org.assertj:assertj-core:${assertjVersion}") } } project(":powermock-modules:powermock-module-testng-agent") { description = "PowerMock module for TestNG with using Javaagent." dependencies { compile(project(":powermock-core")) compile(project(":powermock-modules:powermock-module-testng-common")) compile(project(":powermock-modules:powermock-module-javaagent")) compile("org.testng:testng:${testngVersion}") testCompile("org.hamcrest:hamcrest-core:${hamcrestVersion}") testCompile("org.assertj:assertj-core:${assertjVersion}") } } configure(publishableModules) { project -> apply from: "${gradleScriptDir}/release/publish-jar.gradle" } ================================================ FILE: gradle/publishing/publish-maven.gradle ================================================ apply plugin: 'maven-publish' publishing.publications.all { 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'] pom.withXml { def root = asNode() root.remove(root.get('name')) root.appendNode('name', 'PowerMock') root.remove(root.get('url')) root.appendNode('url', 'http://www.powermock.org') root.remove(root.get('licenses')) def license = root.appendNode('licenses').appendNode('license') license.appendNode('name', 'The Apache Software License, Version 2.0') license.appendNode('url', 'http://www.apache.org/licenses/LICENSE-2.0.txt') license.appendNode('distribution', 'repo') def developers = root.appendNode('developers') devs.each { def split = it.split(':') assert split.length == 3 def d = developers.appendNode('developer') d.appendNode('id', split[0]) d.appendNode('name', split[1]) d.appendNode('email', split[2]) } root.dependencies.'*'.findAll() { it.scope.text() == 'runtime' && project.configurations.compile.allDependencies.find { dep -> dep.name == it.artifactId.text() } }.each() { it.scope*.value = 'compile' } def depends if (root.dependencies.size() > 0) { depends = root.dependencies.get(0) }else{ depends = root.appendNode('dependencies') } if (project.configurations.hasProperty('provided')) { project.configurations.provided.allDependencies.each { def dep = depends.appendNode('dependency') dep.appendNode('groupId', it.group) dep.appendNode('artifactId', it.name) dep.appendNode('version', it.version) dep.appendNode('scope', 'provided') } } if (project.configurations.hasProperty('mockito2')){ project.configurations.mockito2.allDependencies.each { def dep = depends.appendNode('dependency') dep.appendNode('groupId', it.group) dep.appendNode('artifactId', it.name) dep.appendNode('version', it.version) dep.appendNode('scope', 'compile') } } } } ================================================ FILE: gradle/publishing/publish.gradle ================================================ bintray { pkg { repo = project.ext.bintrayRepo } } ================================================ FILE: gradle/publishing/publishable-module.gradle ================================================ ext { bintrayRepo = 'maven' bintrayAutoPublish = true mavenCentralSync = false bintrayPublications = ['javaLibrary'] } jar { manifest.attributes["Created-By"] = "${System.getProperty("java.version")} (${System.getProperty("java.specification.vendor")})" manifest.attributes["Implementation-Title"] = project.name manifest.attributes["Implementation-Version"] = project.version from("${rootProject.projectDir}") { include "LICENSE.txt" into "META-INF" expand(copyright: new Date().format("yyyy"), version: project.version) } } javadoc { description = "Generates project-level javadoc for use in -javadoc jar" options.memberLevel = org.gradle.external.javadoc.JavadocMemberLevel.PROTECTED options.author = true options.header = project.name options.addStringOption('-quiet') failOnError = false } artifacts { archives sourcesJar archives javadocJar } ================================================ FILE: gradle/release/distZip.gradle ================================================ def fullJars = [ project(":powermock-release:powermock-easymock-junit"), project(":powermock-release:powermock-easymock-testng"), project(":powermock-release:powermock-mockito2-junit"), project(":powermock-release:powermock-mockito2-testng") ] configure(fullJars) { project -> ext { bintrayRepo = 'generic' bintrayAutoPublish = true mavenCentralSync = false } repositories { mavenCentral() jcenter() } group = "org.powermock" apply plugin: 'distribution' distributions { main { contents { from(project.configurations.compile) } } } apply from: "${gradleScriptDir}/release/publish-distZip.gradle" } ================================================ FILE: gradle/release/fullJars.gradle ================================================ def fullJars = [ project(":powermock-release:powermock-easymock"), project(":powermock-release:powermock-mockito2") ] configure(fullJars){ project -> ext { bintrayRepo = 'generic' bintrayAutoPublish = true mavenCentralSync = false } repositories { mavenLocal() mavenCentral() jcenter() } group = "org.powermock" apply plugin: 'java' apply plugin: 'com.github.johnrengelman.shadow' jar{ enabled = false } shadowJar { baseName = project.name version = project.version classifier = "full" manifest.attributes["Created-By"] = "${System.getProperty("java.version")} (${System.getProperty("java.specification.vendor")})" manifest.attributes["Implementation-Title"] = project.name + "-full" manifest.attributes["Implementation-Version"] = project.version from("${rootProject.projectDir}") { include "LICENSE.txt" into "META-INF" expand(copyright: new Date().format("yyyy"), version: project.version) } dependencies { exclude(dependency { !it.name.toString().contains('powermock') }) } } apply from: "${gradleScriptDir}/release/publish-fullJar.gradle" } ================================================ FILE: gradle/release/publish-distZip.gradle ================================================ apply from: "${gradleScriptDir}/publishing/publish.gradle" tasks.bintrayUpload.mustRunAfter "assembleDist" bintray { filesSpec{ from "$buildDir/distributions" include '*.zip' include '*.tar' into 'distributions/' } } ================================================ FILE: gradle/release/publish-fullJar.gradle ================================================ apply from: "${gradleScriptDir}/publishing/publish.gradle" tasks.bintrayUpload.mustRunAfter "shadowJar" bintray { configurations = ['shadow'] } ================================================ FILE: gradle/release/publish-jar.gradle ================================================ apply from: "${gradleScriptDir}/publishing/publish-maven.gradle" tasks.bintrayUpload.mustRunAfter "build" bintray { publications = project.ext.bintrayPublications } ================================================ FILE: gradle/shipkit.gradle ================================================ shipkit { gitHub.repository = "powermock/powermock" gitHub.readOnlyAuthToken = "0f1df49ac11364f542c9d3e6735ae64d010ab8e3" git.user = "PowerMock Release Tools" git.email = "" git.releasableBranchRegex = "release/.+" // 'release/2.x', 'release/3.x', etc. git.tagPrefix = "powermock-" // fix for Intellj Idea, because IDE does not read env properties from ${user.home}/.profile file on MacOS gitHub.writeAuthUser = System.getenv("GH_USER") != null ? System.getenv("GH_USER") : "GH_USER-not-set-dev-mode"; gitHub.writeAuthToken = System.getenv("GH_WRITE_TOKEN") != null ? System.getenv("GH_WRITE_TOKEN"): "GH_WRITE_TOKEN-not-set-dev-mode"; def buildNo = System.getenv("TRAVIS_BUILD_NUMBER") git.commitMessagePostfix = buildNo? "by CI build $buildNo\n\n[ci skip]" : "by local build\n\n[ci skip]" releaseNotes.file = "docs/release-notes/official.md" releaseNotes.labelMapping = [ 'epic': "Major changes", 'bug': "Bugfixes", 'enhancement': "Enhancements", 'android': "Android support", 'kotlin': "Kotlin support", 'component:mockito': "Mockito support", 'component:easymock': "EasyMock support", 'component:junit': "jUnit support", 'wiki': 'Documentation', 'regression': 'Fix regression bug' ] releaseNotes.ignoreCommitsContaining = ["[ci skip]"] } boolean centralRelease = shouldReleaseToCentral(project) String versionDescription = "PowerMock ${project.version} Final" if (project.version.toString().contains("beta")){ versionDescription = "PowerMock ${project.version} Beta" }else if (project.version.toString().contains("RC")){ versionDescription = "PowerMock ${project.version} Release Candidate" } allprojects { plugins.withId("org.shipkit.bintray") { bintray { user = System.getenv('BINTRAY_USER') key = System.getenv("BINTRAY_API_KEY") publish = true override = false pkg { userOrg = 'powermock' name = centralRelease ? "powermock" : "powermock-development" desc = project.description websiteUrl = 'http://powermock.org' issueTrackerUrl = 'https://powermock.com/powermock/powermock/issues' vcsUrl = 'https://github.com/powermock/powermock.git' licenses = ['Apache-2.0'] labels = ['java', 'mock', 'mocking', 'tests'] publicDownloadNumbers = true // optional version attributes version { name = "powermock-${project.version}" released = new Date() desc = versionDescription vcsTag = "powermock-${project.version}" gpg { sign = true } //Automatically syncs to central repository (https://oss.sonatype.org/) mavenCentralSync { sync = centralRelease user = System.env.NEXUS_TOKEN_USER password = System.env.NEXUS_TOKEN_PWD } } } } } } /** * Finds out if we should release to Maven Central. * To test this logic, run build with '-i' (info logging) and inspect the build output. */ static boolean shouldReleaseToCentral(project) { boolean centralReleaseByCommit = System.getenv("TRAVIS_COMMIT_MESSAGE")?.contains("[ci maven-central-release]") boolean centralReleaseByProjectProperty = project.hasProperty("mavenCentralSync") ? project.ext.mavenCentralSync : false boolean centralRelease = (centralReleaseByCommit || centralReleaseByProjectProperty) String message = """Release was using following settings: - commit message contains '[ci maven-central-release]': $centralReleaseByCommit - project property 'mavenCentralSync' has value: $centralReleaseByProjectProperty - Maven Central release is enabled: $centralRelease""" project.logger.info(message) return centralRelease } ================================================ FILE: gradle/version.gradle ================================================ def v = Version.versionFile(project.file("version.properties")) allprojects{ project.version = v.version project.ext.versionFile = v } logger.lifecycle "Version: $project.version" class Version{ static VersionFile versionFile(file) { return new VersionFile(file) } } class VersionFile{ private final File file private version VersionFile(file){ this.file = file } def getVersion() { if (version == null){ readVersion() } return version } private readVersion() { Properties p = new Properties() FileReader reader = null try { reader = new FileReader(file) p.load(reader) } catch (Exception ignored) { throw new RuntimeException("Cannot read version file: " + file) } finally { if (reader != null){ reader.close() } } version = p.getProperty("version") } } ================================================ FILE: gradle/wrapper/gradle-wrapper.properties ================================================ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.2-bin.zip ================================================ FILE: gradle.properties ================================================ org.gradle.daemon=true //org.gradle.parallel=true ================================================ FILE: gradlew ================================================ #!/usr/bin/env sh ############################################################################## ## ## Gradle start up script for UN*X ## ############################################################################## # Attempt to set APP_HOME # Resolve links: $0 may be a link PRG="$0" # Need this for relative symlinks. while [ -h "$PRG" ] ; do ls=`ls -ld "$PRG"` link=`expr "$ls" : '.*-> \(.*\)$'` if expr "$link" : '/.*' > /dev/null; then PRG="$link" else PRG=`dirname "$PRG"`"/$link" fi done SAVED="`pwd`" cd "`dirname \"$PRG\"`/" >/dev/null APP_HOME="`pwd -P`" cd "$SAVED" >/dev/null APP_NAME="Gradle" APP_BASE_NAME=`basename "$0"` # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS="" # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD="maximum" warn () { echo "$*" } die () { echo echo "$*" echo exit 1 } # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false case "`uname`" in CYGWIN* ) cygwin=true ;; Darwin* ) darwin=true ;; MINGW* ) msys=true ;; NONSTOP* ) nonstop=true ;; esac CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables JAVACMD="$JAVA_HOME/jre/sh/java" else JAVACMD="$JAVA_HOME/bin/java" fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else JAVACMD="java" which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi # Increase the maximum file descriptors if we can. if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then MAX_FD_LIMIT=`ulimit -H -n` if [ $? -eq 0 ] ; then if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then MAX_FD="$MAX_FD_LIMIT" fi ulimit -n $MAX_FD if [ $? -ne 0 ] ; then warn "Could not set maximum file descriptor limit: $MAX_FD" fi else warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" fi fi # For Darwin, add options to specify how the application appears in the dock if $darwin; then GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" fi # For Cygwin, switch paths to Windows format before running java if $cygwin ; then APP_HOME=`cygpath --path --mixed "$APP_HOME"` CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` JAVACMD=`cygpath --unix "$JAVACMD"` # We build the pattern for arguments to be converted via cygpath ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` SEP="" for dir in $ROOTDIRSRAW ; do ROOTDIRS="$ROOTDIRS$SEP$dir" SEP="|" done OURCYGPATTERN="(^($ROOTDIRS))" # Add a user-defined pattern to the cygpath arguments if [ "$GRADLE_CYGPATTERN" != "" ] ; then OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" fi # Now convert the arguments - kludge to limit ourselves to /bin/sh i=0 for arg in "$@" ; do CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` else eval `echo args$i`="\"$arg\"" fi i=$((i+1)) done case $i in (0) set -- ;; (1) set -- "$args0" ;; (2) set -- "$args0" "$args1" ;; (3) set -- "$args0" "$args1" "$args2" ;; (4) set -- "$args0" "$args1" "$args2" "$args3" ;; (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; esac fi # Escape application args save () { for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done echo " " } APP_ARGS=$(save "$@") # Collect all arguments for the java command, following the shell quoting and substitution rules eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then cd "$(dirname "$0")" fi exec "$JAVACMD" "$@" ================================================ FILE: gradlew.bat ================================================ @if "%DEBUG%" == "" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @rem @rem ########################################################################## @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 if "%DIRNAME%" == "" set DIRNAME=. set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. set DEFAULT_JVM_OPTS= @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if "%ERRORLEVEL%" == "0" goto init echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto init echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :init @rem Get command-line arguments, handling Windows variants if not "%OS%" == "Windows_NT" goto win9xME_args :win9xME_args @rem Slurp the command line arguments. set CMD_LINE_ARGS= set _SKIP=2 :win9xME_args_slurp if "x%~1" == "x" goto execute set CMD_LINE_ARGS=%* :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar @rem Execute Gradle "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% :end @rem End local scope for the variables with windows NT shell if "%ERRORLEVEL%"=="0" goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 exit /b 1 :mainEnd if "%OS%"=="Windows_NT" endlocal :omega ================================================ FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/EasyMockConfiguration.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.api.easymock; /** * Configuration information about EasyMock framework and which feature is supported by version of EasyMock in runtime. * * @since 1.6.5 */ public class EasyMockConfiguration { private static final EasyMockConfiguration INSTANCE = new EasyMockConfiguration(); private boolean testSubjectSupported; private boolean reallyEasyMock; private boolean injectMocksSupported; private EasyMockConfiguration() { initTestSubjectSupported(); initReallyEasyMock(); initInjectMocksSupported(); } public static EasyMockConfiguration getConfiguration() { return INSTANCE; } private void initTestSubjectSupported() { try { Class.forName("org.easymock.TestSubject"); testSubjectSupported = true; } catch (ClassNotFoundException e) { testSubjectSupported = false; } } private void initReallyEasyMock() { try { Class.forName("org.easymock.EasyMockSupport"); reallyEasyMock = true; } catch (ClassNotFoundException e) { reallyEasyMock = false; } } private void initInjectMocksSupported() { try { Class clazz = Class.forName("org.easymock.EasyMockSupport"); clazz.getDeclaredMethod("injectMocks", Object.class); injectMocksSupported = true; } catch (NoSuchMethodException e) { injectMocksSupported = false; } catch (ClassNotFoundException e) { injectMocksSupported = false; } } public boolean isInjectMocksSupported() { return injectMocksSupported; } public boolean isReallyEasyMock() { return reallyEasyMock; } public boolean isTestSubjectSupported() { return testSubjectSupported; } } ================================================ FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/PowerMock.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.api.easymock; import net.sf.cglib.proxy.Enhancer; import org.easymock.ConstructorArgs; import org.easymock.IExpectationSetters; import org.easymock.IMocksControl; import org.easymock.internal.LastControl; import org.easymock.internal.MockInvocationHandler; import org.easymock.internal.MocksControl; import org.powermock.api.easymock.internal.invocationcontrol.EasyMockMethodInvocationControl; import org.powermock.api.easymock.internal.invocationcontrol.NewInvocationControlAssertionError; import org.powermock.api.easymock.internal.invocationcontrol.EasyMockNewInvocationControl; import org.powermock.api.easymock.internal.mockstrategy.MockStrategy; import org.powermock.api.easymock.internal.mockstrategy.impl.DefaultMockStrategy; import org.powermock.api.easymock.internal.mockstrategy.impl.NiceMockStrategy; import org.powermock.api.easymock.internal.mockstrategy.impl.StrictMockStrategy; import org.powermock.api.support.SuppressCode; import org.powermock.api.support.membermodification.MemberModifier; import org.powermock.core.ClassReplicaCreator; import org.powermock.core.DefaultFieldValueGenerator; import org.powermock.core.MockGateway; import org.powermock.core.MockRepository; import org.powermock.core.classloader.MockClassLoader; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.core.classloader.annotations.PrepareOnlyThisForTest; import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor; import org.powermock.core.spi.MethodInvocationControl; import org.powermock.core.spi.NewInvocationControl; import org.powermock.core.spi.support.InvocationSubstitute; import org.powermock.reflect.Whitebox; import org.powermock.reflect.internal.WhiteboxImpl; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Proxy; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; /** * PowerMock extends EasyMock functionality with several new features such as * mocking static and private methods, mocking new instances and more. Use * PowerMock instead of EasyMock where applicable. */ public class PowerMock extends MemberModifier { private static final String NICE_REPLAY_AND_VERIFY_KEY = "PowerMock.niceReplayAndVerify"; static { MockGateway.MOCK_STANDARD_METHODS = false; MockGateway.MOCK_GET_CLASS_METHOD = false; } /** * Creates a mock object that supports mocking of final and native methods. * * @param the type of the mock object * @param type the type of the mock object * @param methods optionally what methods to mock * @return the mock object. */ public static synchronized T createMock(Class type, Method... methods) { return doMock(type, false, new DefaultMockStrategy(), null, methods); } /** * Creates a mock object that supports mocking of final and native methods. * * @param the type of the mock object * @param type the type of the mock object * @return the mock object. */ public static synchronized T createMock(Class type) { return doMock(type, false, new DefaultMockStrategy(), null, (Method[]) null); } /** * Creates a mock object that supports mocking of final and native methods * and invokes a specific constructor. * * @param the type of the mock object * @param type the type of the mock object * @param constructorArgs The constructor arguments that will be used to invoke a * special constructor. * @param methods optionally what methods to mock * @return the mock object. */ public static T createMock(Class type, ConstructorArgs constructorArgs, Method... methods) { return doMock(type, false, new DefaultMockStrategy(), constructorArgs, methods); } /** * Creates a mock object that supports mocking of final and native methods * and invokes a specific constructor based on the supplied argument values. * * @param the type of the mock object * @param type the type of the mock object * @param constructorArguments The constructor arguments that will be used to invoke a * certain constructor. * @return the mock object. */ public static T createMock(Class type, Object... constructorArguments) { Constructor constructor = WhiteboxImpl.findUniqueConstructorOrThrowException(type, constructorArguments); ConstructorArgs constructorArgs = new ConstructorArgs(constructor, constructorArguments); return doMock(type, false, new DefaultMockStrategy(), constructorArgs, (Method[]) null); } /** * Creates a strict mock object that supports mocking of final and native * methods. * * @param the type of the mock object * @param type the type of the mock object * @param methods optionally what methods to mock * @return the mock object. */ public static synchronized T createStrictMock(Class type, Method... methods) { return doMock(type, false, new StrictMockStrategy(), null, methods); } /** * Creates a strict mock object that supports mocking of final and native * methods. * * @param the type of the mock object * @param type the type of the mock object * @return the mock object. */ public static synchronized T createStrictMock(Class type) { return doMock(type, false, new StrictMockStrategy(), null, (Method[]) null); } /** * Creates a nice mock object that supports mocking of final and native * methods. * * @param the type of the mock object * @param type the type of the mock object * @param methods optionally what methods to mock * @return the mock object. */ public static synchronized T createNiceMock(Class type, Method... methods) { return doMock(type, false, new NiceMockStrategy(), null, methods); } /** * Creates a nice mock object that supports mocking of final and native * methods. * * @param the type of the mock object * @param type the type of the mock object * @return the mock object. */ public static synchronized T createNiceMock(Class type) { return doMock(type, false, new NiceMockStrategy(), null, (Method[]) null); } /** * Creates a strict mock object that supports mocking of final and native * methods and invokes a specific constructor. * * @param the type of the mock object * @param type the type of the mock object * @param constructorArgs The constructor arguments that will be used to invoke a * special constructor. * @param methods optionally what methods to mock * @return the mock object. */ public static T createStrictMock(Class type, ConstructorArgs constructorArgs, Method... methods) { return doMock(type, false, new StrictMockStrategy(), constructorArgs, methods); } /** * Creates a nice mock object that supports mocking of final and native * methods and invokes a specific constructor. * * @param the type of the mock object * @param type the type of the mock object * @param constructorArgs The constructor arguments that will be used to invoke a * special constructor. * @param methods optionally what methods to mock * @return the mock object. */ public static T createNiceMock(Class type, ConstructorArgs constructorArgs, Method... methods) { return doMock(type, false, new NiceMockStrategy(), constructorArgs, methods); } /** * Creates a strict mock object that supports mocking of final and native * methods and invokes a specific constructor based on the supplied argument * values. * * @param the type of the mock object * @param type the type of the mock object * @param constructorArguments The constructor arguments that will be used to invoke a * certain constructor. * @return the mock object. */ public static T createStrictMock(Class type, Object... constructorArguments) { Constructor constructor = WhiteboxImpl.findUniqueConstructorOrThrowException(type, constructorArguments); ConstructorArgs constructorArgs = new ConstructorArgs(constructor, constructorArguments); return doMock(type, false, new StrictMockStrategy(), constructorArgs, (Method[]) null); } /** * Creates a nice mock object that supports mocking of final and native * methods and invokes a specific constructor based on the supplied argument * values. * * @param the type of the mock object * @param type the type of the mock object * @param constructorArguments The constructor arguments that will be used to invoke a * certain constructor. * @return the mock object. */ public static T createNiceMock(Class type, Object... constructorArguments) { Constructor constructor = WhiteboxImpl.findUniqueConstructorOrThrowException(type, constructorArguments); ConstructorArgs constructorArgs = new ConstructorArgs(constructor, constructorArguments); return doMock(type, false, new NiceMockStrategy(), constructorArgs, (Method[]) null); } /** * Enable static mocking for a class. * * @param type the class to enable static mocking * @param methods optionally what methods to mock */ public static synchronized void mockStatic(Class type, Method... methods) { doMock(type, true, new DefaultMockStrategy(), null, methods); } /** * Enable static mocking for a class. * * @param type the class to enable static mocking */ public static synchronized void mockStatic(Class type) { doMock(type, true, new DefaultMockStrategy(), null, (Method[]) null); } /** * Enable strict static mocking for a class. * * @param type the class to enable static mocking * @param methods optionally what methods to mock */ public static synchronized void mockStaticStrict(Class type, Method... methods) { doMock(type, true, new StrictMockStrategy(), null, methods); } /** * Enable strict static mocking for a class. * * @param type the class to enable static mocking */ public static synchronized void mockStaticStrict(Class type) { doMock(type, true, new StrictMockStrategy(), null, (Method[]) null); } /** * Enable nice static mocking for a class. * * @param type the class to enable static mocking * @param methods optionally what methods to mock */ public static synchronized void mockStaticNice(Class type, Method... methods) { doMock(type, true, new NiceMockStrategy(), null, methods); } /** * Enable nice static mocking for a class. * * @param type the class to enable static mocking */ public static synchronized void mockStaticNice(Class type) { doMock(type, true, new NiceMockStrategy(), null, (Method[]) null); } /** * A utility method that may be used to specify several methods that should * not be mocked in an easy manner (by just passing in the method * names of the method you wish not to mock). Note that you cannot * uniquely specify a method to exclude using this method if there are * several methods with the same name in {@code type}. This method will * mock ALL methods that doesn't match the supplied name(s) regardless of * parameter types and signature. If this is not the case you should * fall-back on using the {@link #createMock(Class, Method...)} method * instead. * * @param The type of the mock. * @param type The type that'll be used to create a mock instance. * @param methodNames The names of the methods that should be mocked. If * {@code null}, then this method will have the same effect * as just calling {@link #createMock(Class, Method...)} with the * second parameter as {@code new Method[0]} (i.e. all * methods in that class will be mocked). * @return A mock object of type . */ public static synchronized T createPartialMockForAllMethodsExcept(Class type, String... methodNames) { if (methodNames != null && methodNames.length == 0) { return createMock(type); } return createMock(type, WhiteboxImpl.getAllMethodExcept(type, methodNames)); } /** * A utility method that may be used to specify several methods that should * not be nicely mocked in an easy manner (by just passing in the * method names of the method you wish not to mock). Note that you * cannot uniquely specify a method to exclude using this method if there * are several methods with the same name in {@code type}. This method * will mock ALL methods that doesn't match the supplied name(s) regardless * of parameter types and signature. If this is not the case you should * fall-back on using the {@link #createMock(Class, Method...)} method * instead. * * @param The type of the mock. * @param type The type that'll be used to create a mock instance. * @param methodNames The names of the methods that should be mocked. If * {@code null}, then this method will have the same effect * as just calling {@link #createMock(Class, Method...)} with the * second parameter as {@code new Method[0]} (i.e. all * methods in that class will be mocked). * @return A mock object of type . */ public static synchronized T createNicePartialMockForAllMethodsExcept(Class type, String... methodNames) { if (methodNames != null && methodNames.length == 0) { return createNiceMock(type); } return createNiceMock(type, WhiteboxImpl.getAllMethodExcept(type, methodNames)); } /** * A utility method that may be used to specify several methods that should * not be strictly mocked in an easy manner (by just passing in the * method names of the method you wish not to mock). Note that you * cannot uniquely specify a method to exclude using this method if there * are several methods with the same name in {@code type}. This method * will mock ALL methods that doesn't match the supplied name(s) regardless * of parameter types and signature. If this is not the case you should * fall-back on using the {@link #createMock(Class, Method...)} method * instead. * * @param The type of the mock. * @param type The type that'll be used to create a mock instance. * @param methodNames The names of the methods that should be mocked. If * {@code null}, then this method will have the same effect * as just calling {@link #createMock(Class, Method...)} with the * second parameter as {@code new Method[0]} (i.e. all * methods in that class will be mocked). * @return A mock object of type . */ public static synchronized T createStrictPartialMockForAllMethodsExcept(Class type, String... methodNames) { if (methodNames != null && methodNames.length == 0) { return createStrictMock(type); } return createStrictMock(type, WhiteboxImpl.getAllMethodExcept(type, methodNames)); } /** * Mock all methods of a class except for a specific one. Use this method * only if you have several overloaded methods. * * @param The type of the mock. * @param type The type that'll be used to create a mock instance. * @param methodNameToExclude The name of the method not to mock. * @param firstArgumentType The type of the first parameter of the method not to mock * @param moreTypes Optionally more parameter types that defines the method. Note * that this is only needed to separate overloaded methods. * @return A mock object of type . */ public static synchronized T createPartialMockForAllMethodsExcept(Class type, String methodNameToExclude, Class firstArgumentType, Class... moreTypes) { /* * The reason why we've split the first and "additional types" is * because it should not intervene with the mockAllExcept(type, * String...methodNames) method. */ final Class[] argumentTypes = mergeArgumentTypes(firstArgumentType, moreTypes); return createMock(type, WhiteboxImpl.getAllMethodsExcept(type, methodNameToExclude, argumentTypes)); } /** * Mock all methods of a class except for a specific one nicely. Use this * method only if you have several overloaded methods. * * @param The type of the mock. * @param type The type that'll be used to create a mock instance. * @param methodNameToExclude The name of the method not to mock. * @param firstArgumentType The type of the first parameter of the method not to mock * @param moreTypes Optionally more parameter types that defines the method. Note * that this is only needed to separate overloaded methods. * @return A mock object of type . */ public static synchronized T createNicePartialMockForAllMethodsExcept(Class type, String methodNameToExclude, Class firstArgumentType, Class... moreTypes) { /* * The reason why we've split the first and "additional types" is * because it should not intervene with the mockAllExcept(type, * String...methodNames) method. */ final Class[] argumentTypes = mergeArgumentTypes(firstArgumentType, moreTypes); return createNiceMock(type, WhiteboxImpl.getAllMethodsExcept(type, methodNameToExclude, argumentTypes)); } /** * Mock all methods of a class except for a specific one strictly. Use this * method only if you have several overloaded methods. * * @param The type of the mock. * @param type The type that'll be used to create a mock instance. * @param methodNameToExclude The name of the method not to mock. * @param firstArgumentType The type of the first parameter of the method not to mock * @param moreTypes Optionally more parameter types that defines the method. Note * that this is only needed to separate overloaded methods. * @return A mock object of type . */ public static synchronized T createStrictPartialMockForAllMethodsExcept(Class type, String methodNameToExclude, Class firstArgumentType, Class... moreTypes) { /* * The reason why we've split the first and "additional types" is * because it should not intervene with the mockAllExcept(type, * String...methodNames) method. */ final Class[] argumentTypes = mergeArgumentTypes(firstArgumentType, moreTypes); return createStrictMock(type, WhiteboxImpl.getAllMethodsExcept(type, methodNameToExclude, argumentTypes)); } /** * Mock a single specific method. Use this to handle overloaded methods. * * @param The type of the mock. * @param type The type that'll be used to create a mock instance. * @param methodNameToMock The name of the method to mock * @param firstArgumentType The type of the first parameter of the method to mock * @param additionalArgumentTypes Optionally more parameter types that defines the method. Note * that this is only needed to separate overloaded methods. * @return A mock object of type . */ public static synchronized T createPartialMock(Class type, String methodNameToMock, Class firstArgumentType, Class... additionalArgumentTypes) { return doMockSpecific(type, new DefaultMockStrategy(), new String[]{methodNameToMock}, null, mergeArgumentTypes(firstArgumentType, additionalArgumentTypes)); } /** * Strictly mock a single specific method. Use this to handle overloaded * methods. * * @param The type of the mock. * @param type The type that'll be used to create a mock instance. * @param methodNameToMock The name of the method to mock * @param firstArgumentType The type of the first parameter of the method to mock * @param additionalArgumentTypes Optionally more parameter types that defines the method. Note * that this is only needed to separate overloaded methods. * @return A mock object of type . */ public static synchronized T createStrictPartialMock(Class type, String methodNameToMock, Class firstArgumentType, Class... additionalArgumentTypes) { return doMockSpecific(type, new StrictMockStrategy(), new String[]{methodNameToMock}, null, mergeArgumentTypes(firstArgumentType, additionalArgumentTypes)); } /** * Nicely mock a single specific method. Use this to handle overloaded * methods. * * @param The type of the mock. * @param type The type that'll be used to create a mock instance. * @param methodNameToMock The name of the method to mock * @param firstArgumentType The type of the first parameter of the method to mock * @param additionalArgumentTypes Optionally more parameter types that defines the method. Note * that this is only needed to separate overloaded methods. * @return A mock object of type . */ public static synchronized T createNicePartialMock(Class type, String methodNameToMock, Class firstArgumentType, Class... additionalArgumentTypes) { return doMockSpecific(type, new NiceMockStrategy(), new String[]{methodNameToMock}, null, mergeArgumentTypes(firstArgumentType, additionalArgumentTypes)); } /** * Mock a single static method. * * @param clazz The class where the method is specified in. * @param methodNameToMock The first argument * @param firstArgumentType The first argument type. * @param additionalArgumentTypes Optional additional argument types. */ public static synchronized void mockStaticPartial(Class clazz, String methodNameToMock, Class firstArgumentType, Class... additionalArgumentTypes) { doMockSpecific(clazz, new DefaultMockStrategy(), new String[]{methodNameToMock}, null, mergeArgumentTypes(firstArgumentType, additionalArgumentTypes)); } /** * Mock a single static method (strict). * * @param clazz The class where the method is specified in. * @param methodNameToMock The first argument * @param firstArgumentType The first argument type. * @param additionalArgumentTypes Optional additional argument types. */ public static synchronized void mockStaticPartialStrict(Class clazz, String methodNameToMock, Class firstArgumentType, Class... additionalArgumentTypes) { doMockSpecific(clazz, new StrictMockStrategy(), new String[]{methodNameToMock}, null, mergeArgumentTypes(firstArgumentType, additionalArgumentTypes)); } /** * Mock a single static method (nice). * * @param clazz The class where the method is specified in. * @param methodNameToMock The first argument * @param firstArgumentType The first argument type. * @param additionalArgumentTypes Optional additional argument types. */ public static synchronized void mockStaticPartialNice(Class clazz, String methodNameToMock, Class firstArgumentType, Class... additionalArgumentTypes) { doMockSpecific(clazz, new NiceMockStrategy(), new String[]{methodNameToMock}, null, mergeArgumentTypes(firstArgumentType, additionalArgumentTypes)); } /** * A utility method that may be used to mock several static methods * in an easy way (by just passing in the method names of the method you * wish to mock). Note that you cannot uniquely specify a method to mock * using this method if there are several methods with the same name in * {@code type}. This method will mock ALL methods that match the * supplied name regardless of parameter types and signature. If this is the * case you should fall-back on using the * {@link #mockStatic(Class, Method...)} method instead. * * @param clazz The class that contains the static methods that should be * mocked. * @param methodNames The names of the methods that should be mocked. If * {@code null}, then this method will have the same effect * as just calling {@link #mockStatic(Class, Method...)} with the * second parameter as {@code new Method[0]} (i.e. all * methods in that class will be mocked). */ public static synchronized void mockStaticPartial(Class clazz, String... methodNames) { mockStatic(clazz, Whitebox.getMethods(clazz, methodNames)); } /** * A utility method that may be used to mock several static methods * (strict) in an easy way (by just passing in the method names of the * method you wish to mock). Note that you cannot uniquely specify a method * to mock using this method if there are several methods with the same name * in {@code type}. This method will mock ALL methods that match the * supplied name regardless of parameter types and signature. If this is the * case you should fall-back on using the * {@link #mockStaticStrict(Class, Method...)} method instead. * * @param clazz The class that contains the static methods that should be * mocked. * @param methodNames The names of the methods that should be mocked. If * {@code null}, then this method will have the same effect * as just calling {@link #mockStatic(Class, Method...)} with the * second parameter as {@code new Method[0]} (i.e. all * methods in that class will be mocked). */ public static synchronized void mockStaticPartialStrict(Class clazz, String... methodNames) { mockStaticStrict(clazz, Whitebox.getMethods(clazz, methodNames)); } /** * A utility method that may be used to mock several static methods * (nice) in an easy way (by just passing in the method names of the method * you wish to mock). Note that you cannot uniquely specify a method to mock * using this method if there are several methods with the same name in * {@code type}. This method will mock ALL methods that match the * supplied name regardless of parameter types and signature. If this is the * case you should fall-back on using the * {@link #mockStaticStrict(Class, Method...)} method instead. * * @param clazz The class that contains the static methods that should be * mocked. * @param methodNames The names of the methods that should be mocked. If * {@code null}, then this method will have the same effect * as just calling {@link #mockStatic(Class, Method...)} with the * second parameter as {@code new Method[0]} (i.e. all * methods in that class will be mocked). */ public static synchronized void mockStaticPartialNice(Class clazz, String... methodNames) { mockStaticNice(clazz, Whitebox.getMethods(clazz, methodNames)); } static T doMockSpecific(Class type, MockStrategy mockStrategy, String[] methodNamesToMock, ConstructorArgs constructorArgs, Class... argumentTypes) { List methods = new LinkedList(); for (String methodName : methodNamesToMock) { methods.add(WhiteboxImpl.findMethodOrThrowException(type, methodName, argumentTypes)); } final Method[] methodArray = methods.toArray(new Method[0]); if (WhiteboxImpl.areAllMethodsStatic(methodArray)) { if (mockStrategy instanceof DefaultMockStrategy) { mockStatic(type, methodArray); } else if (mockStrategy instanceof StrictMockStrategy) { mockStaticStrict(type, methodArray); } else { mockStaticNice(type, methodArray); } return null; } T mock = null; if (mockStrategy instanceof DefaultMockStrategy) { mock = createMock(type, constructorArgs, methodArray); } else if (mockStrategy instanceof StrictMockStrategy) { mock = createStrictMock(type, constructorArgs, methodArray); } else { mock = createNiceMock(type, constructorArgs, methodArray); } return mock; } /** * A utility method that may be used to mock several methods in an easy way * (by just passing in the method names of the method you wish to mock). * Note that you cannot uniquely specify a method to mock using this method * if there are several methods with the same name in {@code type}. * This method will mock ALL methods that match the supplied name regardless * of parameter types and signature. If this is the case you should * fall-back on using the {@link #createMock(Class, Method...)} method * instead. * * @param The type of the mock. * @param type The type that'll be used to create a mock instance. * @param methodNames The names of the methods that should be mocked. If * {@code null}, then this method will have the same effect * as just calling {@link #createMock(Class, Method...)} with the * second parameter as {@code new Method[0]} (i.e. all * methods in that class will be mocked). * @return A mock object of type . */ public static synchronized T createPartialMock(Class type, String... methodNames) { return createMock(type, Whitebox.getMethods(type, methodNames)); } /** * A utility method that may be used to mock several methods in an easy way * (by just passing in the method names of the method you wish to mock). * Note that you cannot uniquely specify a method to mock using this method * if there are several methods with the same name in {@code type}. * This method will mock ALL methods that match the supplied name regardless * of parameter types and signature. If this is the case you should * fall-back on using the {@link #createMock(Class, Method...)} method * instead. *

* With this method you can specify where the class hierarchy the methods * are located. This is useful in, for example, situations where class A * extends B and both have a method called "mockMe" (A overrides B's mockMe * method) and you like to specify the only the "mockMe" method in B should * be mocked. "mockMe" in A should be left intact. In this case you should * do: *

*

     * A tested = createPartialMock(A.class, B.class, "mockMe");
     * 
* * @param The type of the mock. * @param type The type that'll be used to create a mock instance. * @param where Where in the class hierarchy the methods resides. * @param methodNames The names of the methods that should be mocked. If * {@code null}, then this method will have the same effect * as just calling {@link #createMock(Class, Method...)} with the * second parameter as {@code new Method[0]} (i.e. all * methods in that class will be mocked). * @return A mock object of type . */ public static synchronized T createPartialMock(Class type, Class where, String... methodNames) { return createMock(type, Whitebox.getMethods(where, methodNames)); } /** * A utility method that may be used to strictly mock several methods in an * easy way (by just passing in the method names of the method you wish to * mock). Note that you cannot uniquely specify a method to mock using this * method if there are several methods with the same name in * {@code type}. This method will mock ALL methods that match the * supplied name regardless of parameter types and signature. If this is the * case you should fall-back on using the * {@link #createMock(Class, Method...)} method instead. * * @param The type of the mock. * @param type The type that'll be used to create a mock instance. * @param methodNames The names of the methods that should be mocked. If * {@code null}, then this method will have the same effect * as just calling {@link #createMock(Class, Method...)} with the * second parameter as {@code new Method[0]} (i.e. all * methods in that class will be mocked). * @return A mock object of type . */ public static synchronized T createStrictPartialMock(Class type, String... methodNames) { return createStrictMock(type, Whitebox.getMethods(type, methodNames)); } /** * A utility method that may be used to strictly mock several methods in an * easy way (by just passing in the method names of the method you wish to * mock). Note that you cannot uniquely specify a method to mock using this * method if there are several methods with the same name in * {@code type}. This method will mock ALL methods that match the * supplied name regardless of parameter types and signature. If this is the * case you should fall-back on using the * {@link #createMock(Class, Method...)} method instead. *

* With this method you can specify where the class hierarchy the methods * are located. This is useful in, for example, situations where class A * extends B and both have a method called "mockMe" (A overrides B's mockMe * method) and you like to specify the only the "mockMe" method in B should * be mocked. "mockMe" in A should be left intact. In this case you should * do: *

*

     * A tested = createPartialMockStrict(A.class, B.class, "mockMe");
     * 
* * @param The type of the mock. * @param type The type that'll be used to create a mock instance. * @param where Where in the class hierarchy the methods resides. * @param methodNames The names of the methods that should be mocked. If * {@code null}, then this method will have the same effect * as just calling {@link #createMock(Class, Method...)} with the * second parameter as {@code new Method[0]} (i.e. all * methods in that class will be mocked). * @return A mock object of type . */ public static synchronized T createStrictPartialMock(Class type, Class where, String... methodNames) { return createStrictMock(type, Whitebox.getMethods(where, methodNames)); } /** * A utility method that may be used to nicely mock several methods in an * easy way (by just passing in the method names of the method you wish to * mock). Note that you cannot uniquely specify a method to mock using this * method if there are several methods with the same name in * {@code type}. This method will mock ALL methods that match the * supplied name regardless of parameter types and signature. If this is the * case you should fall-back on using the * {@link #createMock(Class, Method...)} method instead. * * @param The type of the mock. * @param type The type that'll be used to create a mock instance. * @param methodNames The names of the methods that should be mocked. If * {@code null}, then this method will have the same effect * as just calling {@link #createMock(Class, Method...)} with the * second parameter as {@code new Method[0]} (i.e. all * methods in that class will be mocked). * @return A mock object of type . */ public static synchronized T createNicePartialMock(Class type, String... methodNames) { return createNiceMock(type, Whitebox.getMethods(type, methodNames)); } /** * A utility method that may be used to nicely mock several methods in an * easy way (by just passing in the method names of the method you wish to * mock). Note that you cannot uniquely specify a method to mock using this * method if there are several methods with the same name in * {@code type}. This method will mock ALL methods that match the * supplied name regardless of parameter types and signature. If this is the * case you should fall-back on using the * {@link #createMock(Class, Method...)} method instead. *

* With this method you can specify where the class hierarchy the methods * are located. This is useful in, for example, situations where class A * extends B and both have a method called "mockMe" (A overrides B's mockMe * method) and you like to specify the only the "mockMe" method in B should * be mocked. "mockMe" in A should be left intact. In this case you should * do: *

*

     * A tested = createPartialMockNice(A.class, B.class, "mockMe");
     * 
* * @param The type of the mock. * @param type The type that'll be used to create a mock instance. * @param where Where in the class hierarchy the methods resides. * @param methodNames The names of the methods that should be mocked. If * {@code null}, then this method will have the same effect * as just calling {@link #createMock(Class, Method...)} with the * second parameter as {@code new Method[0]} (i.e. all * methods in that class will be mocked). * @return A mock object of type . */ public static synchronized T createNicePartialMock(Class type, Class where, String... methodNames) { return createNiceMock(type, Whitebox.getMethods(where, methodNames)); } /** * A utility method that may be used to mock several methods in an easy way * (by just passing in the method names of the method you wish to mock). The * mock object created will support mocking of final methods and invokes the * default constructor (even if it's private). * * @param the type of the mock object * @param type the type of the mock object * @param methodNames The names of the methods that should be mocked. If * {@code null}, then this method will have the same effect * as just calling {@link #createMock(Class, Method...)} with the * second parameter as {@code new Method[0]} (i.e. all * methods in that class will be mocked). * @return the mock object. */ public static T createPartialMockAndInvokeDefaultConstructor(Class type, String... methodNames) throws Exception { return createMock(type, new ConstructorArgs(Whitebox.getConstructor(type)), Whitebox.getMethods(type, methodNames)); } /** * A utility method that may be used to nicely mock several methods in an * easy way (by just passing in the method names of the method you wish to * mock). The mock object created will support mocking of final methods and * invokes the default constructor (even if it's private). * * @param the type of the mock object * @param type the type of the mock object * @param methodNames The names of the methods that should be mocked. If * {@code null}, then this method will have the same effect * as just calling {@link #createMock(Class, Method...)} with the * second parameter as {@code new Method[0]} (i.e. all * methods in that class will be mocked). * @return the mock object. */ public static T createNicePartialMockAndInvokeDefaultConstructor(Class type, String... methodNames) throws Exception { return createNiceMock(type, new ConstructorArgs(Whitebox.getConstructor(type)), Whitebox.getMethods(type, methodNames)); } /** * A utility method that may be used to strictly mock several methods in an * easy way (by just passing in the method names of the method you wish to * mock). The mock object created will support mocking of final methods and * invokes the default constructor (even if it's private). * * @param the type of the mock object * @param type the type of the mock object * @param methodNames The names of the methods that should be mocked. If * {@code null}, then this method will have the same effect * as just calling {@link #createMock(Class, Method...)} with the * second parameter as {@code new Method[0]} (i.e. all * methods in that class will be mocked). * @return the mock object. */ public static T createStrictPartialMockAndInvokeDefaultConstructor(Class type, String... methodNames) throws Exception { return createStrictMock(type, new ConstructorArgs(Whitebox.getConstructor(type)), Whitebox.getMethods(type, methodNames)); } /** * A utility method that may be used to mock several methods in an easy way * (by just passing in the method names of the method you wish to mock). The * mock object created will support mocking of final and native methods and * invokes a specific constructor based on the supplied argument values. * * @param the type of the mock object * @param type the type of the mock object * @param methodNames The names of the methods that should be mocked. If * {@code null}, then this method will have the same effect * as just calling {@link #createMock(Class, Method...)} with the * second parameter as {@code new Method[0]} (i.e. all * methods in that class will be mocked). * @param constructorArguments The constructor arguments that will be used to invoke a * certain constructor. (optional) * @return the mock object. */ public static T createPartialMock(Class type, String[] methodNames, Object... constructorArguments) { Constructor constructor = WhiteboxImpl.findUniqueConstructorOrThrowException(type, constructorArguments); ConstructorArgs constructorArgs = new ConstructorArgs(constructor, constructorArguments); return doMock(type, false, new DefaultMockStrategy(), constructorArgs, Whitebox.getMethods(type, methodNames)); } /** * * A utility method that may be used to strictly mock several methods in * an easy way (by just passing in the method names of the method you wish * to mock). The mock object created will support mocking of final and * native methods and invokes a specific constructor based on the supplied * argument values. * * @param the type of the mock object * @param type the type of the mock object * @param methodNames The names of the methods that should be mocked. If * {@code null}, then this method will have the same effect * as just calling {@link #createMock(Class, Method...)} with the * second parameter as {@code new Method[0]} (i.e. all * methods in that class will be mocked). * @param constructorArguments The constructor arguments that will be used to invoke a * certain constructor. (optional) * @return the mock object. */ public static T createStrictPartialMock(Class type, String[] methodNames, Object... constructorArguments) { Constructor constructor = WhiteboxImpl.findUniqueConstructorOrThrowException(type, constructorArguments); ConstructorArgs constructorArgs = new ConstructorArgs(constructor, constructorArguments); return doMock(type, false, new StrictMockStrategy(), constructorArgs, Whitebox.getMethods(type, methodNames)); } /** * * A utility method that may be used to nicely mock several methods in an * easy way (by just passing in the method names of the method you wish to * mock). The mock object created will support mocking of final and native * methods and invokes a specific constructor based on the supplied argument * values. * * @param the type of the mock object * @param type the type of the mock object * @param methodNames The names of the methods that should be mocked. If * {@code null}, then this method will have the same effect * as just calling {@link #createMock(Class, Method...)} with the * second parameter as {@code new Method[0]} (i.e. all * methods in that class will be mocked). * @param constructorArguments The constructor arguments that will be used to invoke a * certain constructor. (optional) * @return the mock object. */ public static T createNicePartialMock(Class type, String[] methodNames, Object... constructorArguments) { Constructor constructor = WhiteboxImpl.findUniqueConstructorOrThrowException(type, constructorArguments); ConstructorArgs constructorArgs = new ConstructorArgs(constructor, constructorArguments); return doMock(type, false, new NiceMockStrategy(), constructorArgs, Whitebox.getMethods(type, methodNames)); } /** * A utility method that may be used to mock several methods in an easy way * (by just passing in the method names of the method you wish to mock). Use * this to handle overloaded methods. The mock object created will support * mocking of final and native methods and invokes a specific constructor * based on the supplied argument values. * * @param the type of the mock object * @param type the type of the mock object * @param methodName The names of the methods that should be mocked. If * {@code null}, then this method will have the same effect * as just calling {@link #createMock(Class, Method...)} with the * second parameter as {@code new Method[0]} (i.e. all * methods in that class will be mocked). * @param methodParameterTypes Parameter types that defines the method. Note that this is * only needed to separate overloaded methods. * @param constructorArguments The constructor arguments that will be used to invoke a * certain constructor. (optional) * @return the mock object. */ public static T createPartialMock(Class type, String methodName, Class[] methodParameterTypes, Object... constructorArguments) { Constructor constructor = WhiteboxImpl.findUniqueConstructorOrThrowException(type, constructorArguments); ConstructorArgs constructorArgs = new ConstructorArgs(constructor, constructorArguments); return doMockSpecific(type, new DefaultMockStrategy(), new String[]{methodName}, constructorArgs, methodParameterTypes); } /** * A utility method that may be used to strictly mock several methods in an * easy way (by just passing in the method names of the method you wish to * mock). Use this to handle overloaded methods. The mock object created * will support mocking of final and native methods and invokes a specific * constructor based on the supplied argument values. * * @param the type of the mock object * @param type the type of the mock object * @param methodName The names of the methods that should be mocked. If * {@code null}, then this method will have the same effect * as just calling {@link #createMock(Class, Method...)} with the * second parameter as {@code new Method[0]} (i.e. all * methods in that class will be mocked). * @param methodParameterTypes Parameter types that defines the method. Note that this is * only needed to separate overloaded methods. * @param constructorArguments The constructor arguments that will be used to invoke a * certain constructor. (optional) * @return the mock object. */ public static T createStrictPartialMock(Class type, String methodName, Class[] methodParameterTypes, Object... constructorArguments) { Constructor constructor = WhiteboxImpl.findUniqueConstructorOrThrowException(type, constructorArguments); ConstructorArgs constructorArgs = new ConstructorArgs(constructor, constructorArguments); return doMockSpecific(type, new StrictMockStrategy(), new String[]{methodName}, constructorArgs, methodParameterTypes); } /** * A utility method that may be used to nicely mock several methods in an * easy way (by just passing in the method names of the method you wish to * mock). Use this to handle overloaded methods. The mock object created * will support mocking of final and native methods and invokes a specific * constructor based on the supplied argument values. * * @param the type of the mock object * @param type the type of the mock object * @param methodName The names of the methods that should be mocked. If * {@code null}, then this method will have the same effect * as just calling {@link #createMock(Class, Method...)} with the * second parameter as {@code new Method[0]} (i.e. all * methods in that class will be mocked). * @param methodParameterTypes Parameter types that defines the method. Note that this is * only needed to separate overloaded methods. * @param constructorArguments The constructor arguments that will be used to invoke a * certain constructor. (optional) * @return the mock object. */ public static T createNicePartialMock(Class type, String methodName, Class[] methodParameterTypes, Object... constructorArguments) { Constructor constructor = WhiteboxImpl.findUniqueConstructorOrThrowException(type, constructorArguments); ConstructorArgs constructorArgs = new ConstructorArgs(constructor, constructorArguments); return doMockSpecific(type, new NiceMockStrategy(), new String[]{methodName}, constructorArgs, methodParameterTypes); } /** * A utility method that may be used to mock several methods in an easy way * (by just passing in the method names of the method you wish to mock). Use * this to handle overloaded methods and overloaded constructors. The * mock object created will support mocking of final and native methods and * invokes a specific constructor based on the supplied argument values. * * @param the type of the mock object * @param type the type of the mock object * @param methodName The names of the methods that should be mocked. If * {@code null}, then this method will have the same effect * as just calling {@link #createMock(Class, Method...)} with the * second parameter as {@code new Method[0]} (i.e. all * methods in that class will be mocked). * @param methodParameterTypes Parameter types that defines the method. Note that this is * only needed to separate overloaded methods. * @param constructorArguments The constructor arguments that will be used to invoke a * certain constructor. * @param constructorParameterTypes Parameter types that defines the constructor that should be * invoked. Note that this is only needed to separate overloaded * constructors. * @return the mock object. */ public static T createPartialMock(Class type, String methodName, Class[] methodParameterTypes, Object[] constructorArguments, Class[] constructorParameterTypes) { ConstructorArgs constructorArgs = new ConstructorArgs(Whitebox.getConstructor(type, constructorParameterTypes), constructorArguments); return doMockSpecific(type, new DefaultMockStrategy(), new String[]{methodName}, constructorArgs, methodParameterTypes); } /** * A utility method that may be used to strictly mock several methods in an * easy way (by just passing in the method names of the method you wish to * mock). Use this to handle overloaded methods and overloaded * constructors. The mock object created will support mocking of final and * native methods and invokes a specific constructor based on the supplied * argument values. * * @param the type of the mock object * @param type the type of the mock object * @param methodName The names of the methods that should be mocked. If * {@code null}, then this method will have the same effect * as just calling {@link #createMock(Class, Method...)} with the * second parameter as {@code new Method[0]} (i.e. all * methods in that class will be mocked). * @param methodParameterTypes Parameter types that defines the method. Note that this is * only needed to separate overloaded methods. * @param constructorArguments The constructor arguments that will be used to invoke a * certain constructor. * @param constructorParameterTypes Parameter types that defines the constructor that should be * invoked. Note that this is only needed to separate overloaded * constructors. * @return the mock object. */ public static T createStrictPartialMock(Class type, String methodName, Class[] methodParameterTypes, Object[] constructorArguments, Class[] constructorParameterTypes) { ConstructorArgs constructorArgs = new ConstructorArgs(Whitebox.getConstructor(type, constructorParameterTypes), constructorArguments); return doMockSpecific(type, new StrictMockStrategy(), new String[]{methodName}, constructorArgs, methodParameterTypes); } /** * A utility method that may be used to nicely mock several methods in an * easy way (by just passing in the method names of the method you wish to * mock). Use this to handle overloaded methods and overloaded * constructors. The mock object created will support mocking of final and * native methods and invokes a specific constructor based on the supplied * argument values. * * @param the type of the mock object * @param type the type of the mock object * @param methodName The names of the methods that should be mocked. If * {@code null}, then this method will have the same effect * as just calling {@link #createMock(Class, Method...)} with the * second parameter as {@code new Method[0]} (i.e. all * methods in that class will be mocked). * @param methodParameterTypes Parameter types that defines the method. Note that this is * only needed to separate overloaded methods. * @param constructorArguments The constructor arguments that will be used to invoke a * certain constructor. * @param constructorParameterTypes Parameter types that defines the constructor that should be * invoked. Note that this is only needed to separate overloaded * constructors. * @return the mock object. */ public static T createNicePartialMock(Class type, String methodName, Class[] methodParameterTypes, Object[] constructorArguments, Class[] constructorParameterTypes) { ConstructorArgs constructorArgs = new ConstructorArgs(Whitebox.getConstructor(type, constructorParameterTypes), constructorArguments); return doMockSpecific(type, new NiceMockStrategy(), new String[]{methodName}, constructorArgs, methodParameterTypes); } /** * Used to specify expectations on private static methods. If possible use * variant with only method name. */ public static synchronized IExpectationSetters expectPrivate(Class clazz, Method method, Object... arguments) throws Exception { return doExpectPrivate(clazz, method, arguments); } /** * Used to specify expectations on private methods. If possible use variant * with only method name. */ public static synchronized IExpectationSetters expectPrivate(Object instance, Method method, Object... arguments) throws Exception { return doExpectPrivate(instance, method, arguments); } /** * Used to specify expectations on private methods. Use this method to * handle overloaded methods. */ @SuppressWarnings("all") public static synchronized IExpectationSetters expectPrivate(Object instance, String methodName, Class[] parameterTypes, Object... arguments) throws Exception { if (arguments == null) { arguments = new Object[0]; } if (instance == null) { throw new IllegalArgumentException("instance cannot be null."); } else if (arguments.length != parameterTypes.length) { throw new IllegalArgumentException( "The length of the arguments must be equal to the number of parameter types."); } Method foundMethod = Whitebox.getMethod(instance.getClass(), methodName, parameterTypes); WhiteboxImpl.throwExceptionIfMethodWasNotFound(instance.getClass(), methodName, foundMethod, parameterTypes); return doExpectPrivate(instance, foundMethod, arguments); } /** * Used to specify expectations on methods using the method name. Works on * for example private or package private methods. */ public static synchronized IExpectationSetters expectPrivate(Object instance, String methodName, Object... arguments) throws Exception { if (instance == null) { throw new IllegalArgumentException("Instance or class cannot be null."); } return expectPrivate(instance, methodName, Whitebox.getType(instance), arguments); } /** * Used to specify expectations on methods without specifying a method name. * Works on for example private or package private methods. PowerMock tries * to find a unique method to expect based on the argument parameters. If * PowerMock is unable to locate a unique method you need to revert to using * {@link #expectPrivate(Object, String, Object...)}. */ public static synchronized IExpectationSetters expectPrivate(Object instance, Object... arguments) throws Exception { return expectPrivate(instance, null, Whitebox.getType(instance), arguments); } /** * Used to specify expectations on methods using the method name at a * specific place in the class hierarchy (specified by the * {@code where} parameter). Works on for example private or package * private methods. *

* Use this for overloaded methods. */ public static synchronized IExpectationSetters expectPrivate(Object instance, String methodName, Class where, Class[] parameterTypes, Object... arguments) throws Exception { if (instance == null) { throw new IllegalArgumentException("Instance or class to expect cannot be null."); } Method[] methods = null; if (methodName != null) { if (parameterTypes == null) { methods = Whitebox.getMethods(where, methodName); } else { methods = new Method[]{Whitebox.getMethod(where, methodName, parameterTypes)}; } } Method methodToExpect; if (methods != null && methods.length == 1) { methodToExpect = methods[0]; } else { methodToExpect = WhiteboxImpl.findMethodOrThrowException(instance, null, methodName, arguments); } return doExpectPrivate(instance, methodToExpect, arguments); } /** * Used to specify expectations on methods using the method name at a * specific place in the class hierarchy (specified by the * {@code where} parameter). Works on for example private or package * private methods. */ public static synchronized IExpectationSetters expectPrivate(Object instance, String methodName, Class where, Object... arguments) throws Exception { return expectPrivate(instance, methodName, where, null, arguments); } /** * This method just delegates to EasyMock class extensions * {@link org.easymock.EasyMock#expectLastCall()} method. * * @return The expectation setter. * @see org.easymock.EasyMock#expectLastCall() */ public static synchronized IExpectationSetters expectLastCall() { return org.easymock.EasyMock.expectLastCall(); } /** * Sometimes it is useful to allow replay and verify on non-mocks. For * example when using partial mocking in some tests and no mocking in other * test-methods, but using the same setUp and tearDown. */ public static synchronized void niceReplayAndVerify() { MockRepository.putAdditionalState(NICE_REPLAY_AND_VERIFY_KEY, true); } /** * Test if a object is a mock created by EasyMock or not. */ private static boolean isEasyMocked(Object mock) { return Enhancer.isEnhanced(mock.getClass()) || Proxy.isProxyClass(mock.getClass()); } /** * Replay all classes and mock objects known by PowerMock. This includes all * classes that are prepared for test using the {@link PrepareForTest} or * {@link PrepareOnlyThisForTest} annotations and all classes that have had * their static initializers removed by using the * {@link SuppressStaticInitializationFor} annotation. It also includes all * mock instances created by PowerMock such as those created or used by * {@link #createMock(Class, Method...)}, * {@link #mockStatic(Class, Method...)}, * {@link #expectNew(Class, Object...)}, * {@link #createPartialMock(Class, String...)} etc. *

* To make it easy to pass in additional mocks not created by the * PowerMock API you can optionally specify them as additionalMocks * . These are typically those mock objects you have created using pure * EasyMock or EasyMock class extensions. No additional mocks needs to be * specified if you're only using PowerMock API methods. *

* Note that the additionalMocks are also automatically verified * when invoking the {@link #verifyAll()} method. * * @param additionalMocks Mocks not created by the PowerMock API. These are typically * those mock objects you have created using pure EasyMock or * EasyMock class extensions. */ public static synchronized void replayAll(Object... additionalMocks) { MockRepository.addObjectsToAutomaticallyReplayAndVerify(additionalMocks); for (Object classToReplayOrVerify : MockRepository.getObjectsToAutomaticallyReplayAndVerify()) { replay(classToReplayOrVerify); } } /** * Reset all classes and mock objects known by PowerMock. This includes all * classes that are prepared for test using the {@link PrepareForTest} or * {@link PrepareOnlyThisForTest} annotations and all classes that have had * their static initializers removed by using the * {@link SuppressStaticInitializationFor} annotation. It also includes all * mock instances created by PowerMock such as those created or used by * {@link #createMock(Class, Method...)}, * {@link #mockStatic(Class, Method...)}, * {@link #expectNew(Class, Object...)}, * {@link #createPartialMock(Class, String...)} etc. *

* To make it easy to pass in additional mocks not created by the * PowerMock API you can optionally specify them as additionalMocks * . These are typically those mock objects you have created using pure * EasyMock or EasyMock class extensions. No additional mocks needs to be * specified if you're only using PowerMock API methods. * * @param additionalMocks Mocks not created by the PowerMock API. These are typically * those mock objects you have created using pure EasyMock or * EasyMock class extensions. */ public static synchronized void resetAll(Object... additionalMocks) { MockRepository.addObjectsToAutomaticallyReplayAndVerify(additionalMocks); for (Object classToReplayOrVerify : MockRepository.getObjectsToAutomaticallyReplayAndVerify()) { reset(classToReplayOrVerify); } } /** * Reset a list of class mocks. */ public static synchronized void reset(Class... classMocks) { for (Class type : classMocks) { final MethodInvocationControl invocationHandler = MockRepository.getStaticMethodInvocationControl(type); if (invocationHandler != null) { invocationHandler.reset(); } NewInvocationControl newInvocationControl = MockRepository.getNewInstanceControl(type); if (newInvocationControl != null) { try { newInvocationControl.reset(); } catch (AssertionError e) { NewInvocationControlAssertionError.throwAssertionErrorForNewSubstitutionFailure(e, type); } } } } /** * Reset a list of mock objects or classes. */ public static synchronized void reset(Object... mocks) { try { for (Object mock : mocks) { if (mock instanceof Class) { reset((Class) mock); } else { MethodInvocationControl invocationControl = MockRepository.getInstanceMethodInvocationControl(mock); if (invocationControl != null) { invocationControl.reset(); } else { if (isNiceReplayAndVerifyMode() && !isEasyMocked(mock)) { // ignore non-mock } else { /* * Delegate to easy mock class extension if we have * no handler registered for this object. */ try { org.easymock.EasyMock.reset(mock); } catch (RuntimeException e) { throw new RuntimeException(mock + " is not a mock object", e); } } } } } } catch (Throwable t) { MockRepository.putAdditionalState(NICE_REPLAY_AND_VERIFY_KEY, false); if (t instanceof RuntimeException) { throw (RuntimeException) t; } else if (t instanceof Error) { throw (Error) t; } throw new RuntimeException(t); } } /** * Verify all classes and mock objects known by PowerMock. This includes all * classes that are prepared for test using the {@link PrepareForTest} or * {@link PrepareOnlyThisForTest} annotations and all classes that have had * their static initializers removed by using the * {@link SuppressStaticInitializationFor} annotation. It also includes all * mock instances created by PowerMock such as those created or used by * {@link #createMock(Class, Method...)}, * {@link #mockStatic(Class, Method...)}, * {@link #expectNew(Class, Object...)}, * {@link #createPartialMock(Class, String...)} etc. *

* Note that all additionalMocks passed to the * {@link #replayAll(Object...)} method are also verified here * automatically. */ public static synchronized void verifyAll() { for (Object classToReplayOrVerify : MockRepository.getObjectsToAutomaticallyReplayAndVerify()) { verify(classToReplayOrVerify); } } /** * Switches the mocks or classes to replay mode. Note that you must use this * method when using PowerMock! * * @param mocks mock objects or classes loaded by PowerMock. * @throws RuntimeException If something unexpected goes wrong. */ public static synchronized void replay(Object... mocks) { try { for (Object mock : mocks) { if (mock instanceof Class) { replay((Class) mock); } else { MethodInvocationControl invocationControl = MockRepository.getInstanceMethodInvocationControl(mock); if (invocationControl != null) { invocationControl.replay(); } else { if (isNiceReplayAndVerifyMode() && !isEasyMocked(mock)) { // ignore non-mock } else { /* * Delegate to easy mock class extension if we have * no handler registered for this object. */ try { org.easymock.EasyMock.replay(mock); } catch (RuntimeException e) { throw new RuntimeException(mock + " is not a mock object", e); } } } } } } catch (Throwable t) { MockRepository.putAdditionalState(NICE_REPLAY_AND_VERIFY_KEY, false); if (t instanceof RuntimeException) { throw (RuntimeException) t; } else if (t instanceof Error) { throw (Error) t; } throw new RuntimeException(t); } } /** * Switches the mocks or classes to verify mode. Note that you must use this * method when using PowerMock! * * @param objects mock objects or classes loaded by PowerMock. */ public static synchronized void verify(Object... objects) { for (Object mock : objects) { if (mock instanceof Class) { verifyClass((Class) mock); } else { EasyMockMethodInvocationControl invocationControl = (EasyMockMethodInvocationControl) MockRepository.getInstanceMethodInvocationControl(mock); if (invocationControl != null) { invocationControl.verify(); } else { if (isNiceReplayAndVerifyMode() && !isEasyMocked(mock)) { // ignore non-mock } else { /* * Delegate to easy mock class extension if we have no * handler registered for this object. */ try { org.easymock.EasyMock.verify(mock); } catch (RuntimeException e) { throw new RuntimeException(mock + " is not a mock object", e); } } } } } } /** * Convenience method for createMock followed by expectNew. * * @param type The class that should be mocked. * @param arguments The constructor arguments. * @return A mock object of the same type as the mock. * @throws Exception */ public static synchronized T createMockAndExpectNew(Class type, Object... arguments) throws Exception { T mock = createMock(type); expectNew(type, arguments).andReturn(mock); return mock; } /** * Convenience method for createMock followed by expectNew when PowerMock * cannot determine which constructor to use automatically. This happens * when you have one constructor taking a primitive type and another one * taking the wrapper type of the primitive. For example {@code int} * and {@code Integer}. * * @param type The class that should be mocked. * @param parameterTypes The constructor parameter types. * @param arguments The constructor arguments. * @return A mock object of the same type as the mock. * @throws Exception */ public static synchronized T createMockAndExpectNew(Class type, Class[] parameterTypes, Object... arguments) throws Exception { T mock = createMock(type); expectNew(type, parameterTypes, arguments).andReturn(mock); return mock; } /** * Convenience method for createNiceMock followed by expectNew. * * @param type The class that should be mocked. * @param arguments The constructor arguments. * @return A mock object of the same type as the mock. * @throws Exception */ public static synchronized T createNiceMockAndExpectNew(Class type, Object... arguments) throws Exception { T mock = createNiceMock(type); IExpectationSetters expectationSetters = expectNiceNew(type, arguments); if (expectationSetters != null) { expectationSetters.andReturn(mock); } return mock; } /** * Convenience method for createNiceMock followed by expectNew when * PowerMock cannot determine which constructor to use automatically. This * happens when you have one constructor taking a primitive type and another * one taking the wrapper type of the primitive. For example * {@code int} and {@code Integer}. * * @param type The class that should be mocked. * @param parameterTypes The constructor parameter types. * @param arguments The constructor arguments. * @return A mock object of the same type as the mock. * @throws Exception */ public static synchronized T createNiceMockAndExpectNew(Class type, Class[] parameterTypes, Object... arguments) throws Exception { T mock = createNiceMock(type); IExpectationSetters expectationSetters = expectNiceNew(type, parameterTypes, arguments); if (expectationSetters != null) { expectationSetters.andReturn(mock); } return mock; } /** * Convenience method for createStrictMock followed by expectNew. * * @param type The class that should be mocked. * @param arguments The constructor arguments. * @return A mock object of the same type as the mock. * @throws Exception */ public static synchronized T createStrictMockAndExpectNew(Class type, Object... arguments) throws Exception { T mock = createStrictMock(type); expectStrictNew(type, arguments).andReturn(mock); return mock; } /** * Convenience method for createStrictMock followed by expectNew when * PowerMock cannot determine which constructor to use automatically. This * happens when you have one constructor taking a primitive type and another * one taking the wrapper type of the primitive. For example * {@code int} and {@code Integer}. * * @param type The class that should be mocked. * @param parameterTypes The constructor parameter types. * @param arguments The constructor arguments. * @return A mock object of the same type as the mock. * @throws Exception */ public static synchronized T createStrictMockAndExpectNew(Class type, Class[] parameterTypes, Object... arguments) throws Exception { T mock = createStrictMock(type); expectStrictNew(type, parameterTypes, arguments).andReturn(mock); return mock; } /** * Allows specifying expectations on new invocations. For example you might * want to throw an exception or return a mock. Note that you must replay * the class when using this method since this behavior is part of the class * mock. *

* Use this method when you need to specify parameter types for the * constructor when PowerMock cannot determine which constructor to use * automatically. In most cases you should use * {@link #expectNew(Class, Object...)} instead. */ public static synchronized IExpectationSetters expectNew(Class type, Class[] parameterTypes, Object... arguments) throws Exception { return doExpectNew(type, new DefaultMockStrategy(), parameterTypes, arguments); } @SuppressWarnings("unchecked") private static IExpectationSetters doExpectNew(Class type, MockStrategy mockStrategy, Class[] parameterTypes, Object... arguments) throws Exception { if (type == null) { throw new IllegalArgumentException("type cannot be null"); } else if (mockStrategy == null) { throw new IllegalArgumentException("Internal error: Mock strategy cannot be null"); } final boolean isNiceMock = mockStrategy instanceof NiceMockStrategy; final Class unmockedType = (Class) WhiteboxImpl.getOriginalUnmockedType(type); if (!isNiceMock) { if (parameterTypes == null) { WhiteboxImpl.findUniqueConstructorOrThrowException(type, arguments); } else { WhiteboxImpl.getConstructor(unmockedType, parameterTypes); } } /* * Check if this type has been mocked before */ NewInvocationControl> newInvocationControl = (NewInvocationControl>) MockRepository .getNewInstanceControl(unmockedType); if (newInvocationControl == null) { InvocationSubstitute mock = doMock(InvocationSubstitute.class, false, mockStrategy, null, (Method[]) null); newInvocationControl = new EasyMockNewInvocationControl(mock, type); MockRepository.putNewInstanceControl(type, newInvocationControl); MockRepository.addObjectsToAutomaticallyReplayAndVerify(WhiteboxImpl.getOriginalUnmockedType(type)); } if (isNiceMock && (arguments == null || arguments.length == 0)) { return null; } return newInvocationControl.expectSubstitutionLogic(arguments); } /** * Allows specifying expectations on new invocations. For example you might * want to throw an exception or return a mock. Note that you must replay * the class when using this method since this behavior is part of the class * mock. */ public static synchronized IExpectationSetters expectNew(Class type, Object... arguments) throws Exception { return doExpectNew(type, new DefaultMockStrategy(), null, arguments); } /** * Allows specifying expectations on new invocations for private member * (inner) classes, local or anonymous classes. For example you might want * to throw an exception or return a mock. Note that you must replay the * class when using this method since this behavior is part of the class * mock. * * @param fullyQualifiedName The fully-qualified name of the inner/local/anonymous type to * expect. * @param arguments Optional number of arguments. */ @SuppressWarnings("unchecked") public static synchronized IExpectationSetters expectNew(String fullyQualifiedName, Object... arguments) throws Exception { final Class forName = Class.forName(fullyQualifiedName); return (IExpectationSetters) doExpectNew(forName, new DefaultMockStrategy(), null, arguments); } /** * Allows specifying expectations on new invocations. For example you might * want to throw an exception or return a mock. *

* This method checks the order of constructor invocations. *

* Note that you must replay the class when using this method since this * behavior is part of the class mock. */ public static synchronized IExpectationSetters expectStrictNew(Class type, Object... arguments) throws Exception { return doExpectNew(type, new StrictMockStrategy(), null, arguments); } /** * Allows specifying expectations on new invocations. For example you might * want to throw an exception or return a mock. Note that you must replay * the class when using this method since this behavior is part of the class * mock. *

* This method checks the order of constructor invocations. *

* Use this method when you need to specify parameter types for the * constructor when PowerMock cannot determine which constructor to use * automatically. In most cases you should use * {@link #expectNew(Class, Object...)} instead. */ public static synchronized IExpectationSetters expectStrictNew(Class type, Class[] parameterTypes, Object... arguments) throws Exception { return doExpectNew(type, new StrictMockStrategy(), parameterTypes, arguments); } /** * Allows specifying expectations on new invocations. For example you might * want to throw an exception or return a mock. *

* This method allows any number of calls to a new constructor without * throwing an exception. *

* Note that you must replay the class when using this method since this * behavior is part of the class mock. */ public static synchronized IExpectationSetters expectNiceNew(Class type, Object... arguments) throws Exception { return doExpectNew(type, new NiceMockStrategy(), null, arguments); } /** * Allows specifying expectations on new invocations. For example you might * want to throw an exception or return a mock. Note that you must replay * the class when using this method since this behavior is part of the class * mock. *

* This method allows any number of calls to a new constructor without * throwing an exception. *

* Use this method when you need to specify parameter types for the * constructor when PowerMock cannot determine which constructor to use * automatically. In most cases you should use * {@link #expectNew(Class, Object...)} instead. */ public static synchronized IExpectationSetters expectNiceNew(Class type, Class[] parameterTypes, Object... arguments) throws Exception { return doExpectNew(type, new NiceMockStrategy(), parameterTypes, arguments); } /** * Suppress constructor calls on specific constructors only. * * @deprecated Use {@link #suppress(Constructor[])} instead. */ @Deprecated public static synchronized void suppressConstructor(Constructor... constructors) { SuppressCode.suppressConstructor(constructors); } /** * This method can be used to suppress the code in a specific constructor. * * @param clazz The class where the constructor is located. * @param parameterTypes The parameter types of the constructor to suppress. * @deprecated Use {@link #suppress(Constructor)} instead. */ @Deprecated public static synchronized void suppressSpecificConstructor(Class clazz, Class... parameterTypes) { SuppressCode.suppressSpecificConstructor(clazz, parameterTypes); } /** * Suppress all constructors in the given class and it's super classes. * * @param classes The classes whose constructors will be suppressed. * @deprecated Use {@link #suppress(Constructor[])} instead. */ @Deprecated public static synchronized void suppressConstructor(Class... classes) { SuppressCode.suppressConstructor(classes); } /** * Suppress all constructors in the given class. * * @param clazz The classes whose constructors will be suppressed. * @param excludePrivateConstructors optionally keep code in private constructors * @deprecated Use {@link #suppress(Constructor[])} instead. */ @Deprecated public static synchronized void suppressConstructor(Class clazz, boolean excludePrivateConstructors) { SuppressCode.suppressConstructor(clazz, excludePrivateConstructors); } /** * Suppress specific fields. This works on both instance methods and static * methods. Note that replay and verify are not needed as this is not part * of a mock behavior. * * @deprecated Use {@link #suppress(Field[])} instead. */ @Deprecated public static synchronized void suppressField(Field... fields) { SuppressCode.suppressField(fields); } /** * Suppress all fields for these classes. * * @deprecated Use {@link #suppress(Field[])} instead. */ @Deprecated public static synchronized void suppressField(Class[] classes) { SuppressCode.suppressField(classes); } /** * Suppress multiple methods for a class. * * @param clazz The class whose methods will be suppressed. * @param fieldNames The names of the methods that'll be suppressed. If field names * are empty, all fields in the supplied class will be * suppressed. * @deprecated Use {@link #suppress(Field)} instead. */ @Deprecated public static synchronized void suppressField(Class clazz, String... fieldNames) { SuppressCode.suppressField(clazz, fieldNames); } /** * Suppress specific method calls on all types containing this method. This * works on both instance methods and static methods. Note that replay and * verify are not needed as this is not part of a mock behavior. * * @deprecated Use {@link #suppress(Method[])} instead. */ @Deprecated public static synchronized void suppressMethod(Method... methods) { SuppressCode.suppressMethod(methods); } /** * Suppress all methods for these classes. * * @param cls The first class whose methods will be suppressed. * @param additionalClasses Additional classes whose methods will be suppressed. * @deprecated Use {@link #suppress(Method[])} instead. */ @Deprecated public static synchronized void suppressMethod(Class cls, Class... additionalClasses) { SuppressCode.suppressMethod(cls, additionalClasses); } /** * Suppress all methods for these classes. * * @param classes Classes whose methods will be suppressed. * @deprecated Use {@link #suppress(Method[])} instead. */ @Deprecated public static synchronized void suppressMethod(Class[] classes) { SuppressCode.suppressMethod(classes); } /** * Suppress multiple methods for a class. * * @param clazz The class whose methods will be suppressed. * @param methodName The first method to be suppress in class {@code clazz}. * @param additionalMethodNames Additional methods to suppress in class {@code clazz}. * @deprecated Use {@link #suppress(Method[])} instead. */ @Deprecated public static synchronized void suppressMethod(Class clazz, String methodName, String... additionalMethodNames) { SuppressCode.suppressMethod(clazz, methodName, additionalMethodNames); } /** * Suppress multiple methods for a class. * * @param clazz The class whose methods will be suppressed. * @param methodNames Methods to suppress in class {@code clazz}. * @deprecated Use {@link #suppress(Method[])} instead. */ @Deprecated public static synchronized void suppressMethod(Class clazz, String[] methodNames) { SuppressCode.suppressMethod(clazz, methodNames); } /** * Suppress all methods for this class. * * @param clazz The class which methods will be suppressed. * @param excludePrivateMethods optionally not suppress private methods * @deprecated Use {@link #suppress(Method[])} instead. */ @Deprecated public static synchronized void suppressMethod(Class clazz, boolean excludePrivateMethods) { SuppressCode.suppressMethod(clazz, excludePrivateMethods); } /** * Suppress a specific method call. Use this for overloaded methods. * * @deprecated Use {@link #suppress(Method)} instead. */ @Deprecated public static synchronized void suppressMethod(Class clazz, String methodName, Class[] parameterTypes) { SuppressCode.suppressMethod(clazz, methodName, parameterTypes); } @SuppressWarnings("unchecked") private static T doMock(Class type, boolean isStatic, MockStrategy mockStrategy, ConstructorArgs constructorArgs, Method... methods) { if (type == null) { throw new IllegalArgumentException("The class to mock cannot be null"); } /* * Clear the EasyMock state after the test method is executed. */ MockRepository.addAfterMethodRunner(new Runnable() { @Override public void run() { LastControl.reportLastControl(null); } }); IMocksControl control = mockStrategy.createMockControl(type); MockRepository.addAfterMethodRunner(new EasyMockStateCleaner()); T mock; if (type.isInterface()) { mock = control.createMock(type); } else if (type.getName().startsWith("java.") && Modifier.isFinal(type.getModifiers())) { Class replicaType = createReplicaType(type, isStatic, constructorArgs); final Object replica = doCreateMock(replicaType, constructorArgs, control, methods); control = mockStrategy.createMockControl(replicaType); MockInvocationHandler h = new MockInvocationHandler((MocksControl) control); final Set methodsToMock = toSet(methods); if (isStatic) { MockRepository.putStaticMethodInvocationControl(type, new EasyMockMethodInvocationControl(h, methodsToMock, replica)); MockRepository.addObjectsToAutomaticallyReplayAndVerify(type); return null; } else { final T newInstance; if (constructorArgs == null) { newInstance = Whitebox.newInstance(type); DefaultFieldValueGenerator.fillWithDefaultValues(newInstance); } else { try { newInstance = (T) constructorArgs.getConstructor().newInstance(constructorArgs.getInitArgs()); } catch (Exception e) { throw new RuntimeException("Internal error", e); } } MockRepository.putInstanceMethodInvocationControl(newInstance, new EasyMockMethodInvocationControl(h, methodsToMock, replica)); if (!(newInstance instanceof InvocationSubstitute)) { MockRepository.addObjectsToAutomaticallyReplayAndVerify(newInstance); } return newInstance; } } else { mock = doCreateMock(type, constructorArgs, control, methods); } MockInvocationHandler h = new MockInvocationHandler((MocksControl) control); final Set methodsToMock = toSet(methods); if (isStatic) { MockRepository.putStaticMethodInvocationControl(type, new EasyMockMethodInvocationControl(h, methodsToMock, mock)); MockRepository.addObjectsToAutomaticallyReplayAndVerify(type); } else { MockRepository.putInstanceMethodInvocationControl(mock, new EasyMockMethodInvocationControl(h, methodsToMock)); if (!(mock instanceof InvocationSubstitute)) { MockRepository.addObjectsToAutomaticallyReplayAndVerify(mock); } } ClassLoader classLoader = mock.getClass().getClassLoader(); if (classLoader instanceof MockClassLoader) { ((MockClassLoader) classLoader).cache(mock.getClass()); } return mock; } private static Class createReplicaType(Class type, boolean isStatic, ConstructorArgs constructorArgs) { final ClassReplicaCreator classReplicaCreator = new ClassReplicaCreator(); final Class replicaType; if (isStatic || constructorArgs == null) { replicaType = classReplicaCreator.createClassReplica(type); } else { try { replicaType = classReplicaCreator.createInstanceReplica(constructorArgs.getConstructor().newInstance( constructorArgs.getInitArgs())); } catch (RuntimeException e) { throw e; } catch (InvocationTargetException e) { Throwable targetException = e.getTargetException(); if (targetException instanceof RuntimeException) { throw (RuntimeException) targetException; } throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); } } return replicaType; } private static T doCreateMock(Class type, ConstructorArgs constructorArgs, final IMocksControl control, Method... methods) { T mock; MocksControl mocksControl = ((MocksControl) control); if (constructorArgs == null) { if (methods == null) { mock = mocksControl.createMock(type); } else { mock = mocksControl.createMock(null, type, null, methods); } } else { if (methods == null) { mock = mocksControl.createMock(null, type, constructorArgs); } else { mock = mocksControl.createMock(null, type, constructorArgs, methods); } } return mock; } private static Set toSet(Method[] methods) { return methods == null ? null : new HashSet(Arrays.asList(methods)); } private static Class[] mergeArgumentTypes(Class firstArgumentType, Class... additionalArgumentTypes) { if (firstArgumentType == null) { return additionalArgumentTypes == null ? new Class[0] : additionalArgumentTypes; } else if (additionalArgumentTypes == null) { additionalArgumentTypes = new Class[0]; } final Class[] argumentTypes = new Class[additionalArgumentTypes.length + 1]; argumentTypes[0] = firstArgumentType; if (additionalArgumentTypes.length != 0) { System.arraycopy(additionalArgumentTypes, 0, argumentTypes, 1, additionalArgumentTypes.length); } return argumentTypes; } @SuppressWarnings("unchecked") private static IExpectationSetters doExpectPrivate(Object instance, Method methodToExpect, Object... arguments) throws Exception { WhiteboxImpl.performMethodInvocation(instance, methodToExpect, arguments); return (IExpectationSetters) org.easymock.EasyMock.expectLastCall(); } private static synchronized void replay(Class... types) { for (Class type : types) { final MethodInvocationControl invocationHandler = MockRepository.getStaticMethodInvocationControl(type); if (invocationHandler != null) { invocationHandler.replay(); } NewInvocationControl newInvocationControl = MockRepository.getNewInstanceControl(type); if (newInvocationControl != null) { newInvocationControl.replay(); } } } /** * Note: doesn't clear PowerMock state. */ private static synchronized void verifyClass(Class... types) { for (Class type : types) { final EasyMockMethodInvocationControl invocationHandler = (EasyMockMethodInvocationControl) MockRepository.getStaticMethodInvocationControl(type); if (invocationHandler != null) { invocationHandler.verify(); } EasyMockNewInvocationControl newInvocationControl = (EasyMockNewInvocationControl) MockRepository.getNewInstanceControl(type); if (newInvocationControl != null) { try { newInvocationControl.verify(); } catch (AssertionError e) { NewInvocationControlAssertionError.throwAssertionErrorForNewSubstitutionFailure(e, type); } } } } private static boolean isNiceReplayAndVerifyMode() { final Boolean mode = MockRepository.getAdditionalState(NICE_REPLAY_AND_VERIFY_KEY); return mode != null && mode; } /** * Clears the state in LastControl that deals with MocksControl. */ private static class EasyMockStateCleaner implements Runnable { @Override public void run() { LastControl.reportLastControl(null); clearStateFromOtherClassLoaders(); } private void clearStateFromOtherClassLoaders() { for (ClassLoader cl : classloadersToClear()) { try { final Class lastControlClassByCL = Class.forName(LastControl.class.getName(), false, cl); final Class mocksControlClassByCL = Class.forName(MocksControl.class.getName(), false, cl); final Method reportLastControl = lastControlClassByCL.getMethod("reportLastControl", mocksControlClassByCL); reportLastControl.invoke(lastControlClassByCL, new Object[]{null}); } catch (Exception e) { // Should never happen throw new RuntimeException("Failed to clean up state", e); } } } private Iterable classloadersToClear() { List loaders = new ArrayList(); final ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader(); final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); if (classFoundInClassloader(LastControl.class, systemClassLoader)) { loaders.add(systemClassLoader); } if (classFoundInClassloader(LastControl.class, contextClassLoader)) { loaders.add(contextClassLoader); } return loaders; } private boolean classFoundInClassloader(Class cls, ClassLoader classLoader) { try { Class.forName(cls.getName(), false, classLoader); return true; } catch (ClassNotFoundException e) { return false; } } } } ================================================ FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/annotation/Mock.java ================================================ package org.powermock.api.easymock.annotation; import org.powermock.core.classloader.annotations.PowerMockListener; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * This annotation can be placed on those fields in your test class that should * be mocked. This eliminates the need to setup and tear-down mocks manually * which minimizes repetitive test code and makes the test more readable. In * order for PowerMock to control the life-cycle of the mocks you must supply * the {@link PowerMockListener} annotation to the class-level of the test case. * For example: * *
 * ...
 * @PowerMockListener(AnnotationEnabler.class)
 * public class PersonServiceTest {
 * 
 * 	@Mock
 * 	private PersonDao personDaoMock;
 * 
 * 	private PersonService classUnderTest;
 * 
 * 	@Before
 * 	public void setUp() {
 * 		classUnderTest = new PersonService(personDaoMock);
 * 	}
 *  ...
 * }
 * 
*

* * Note that you can also create partial mocks by using the annotation. Let's * say that the PersonService has a method called "getPerson" and another method * called "savePerson" and these are the only two methods that you'd like to * mock. Rewriting the previous example to accommodate this will give us the * following test: * *

 * ...
 * @PowerMockListener(AnnotationEnabler.class)
 * public class PersonServiceTest {
 * 
 * 	@Mock({"getPerson", "savePerson"})
 * 	private PersonDao personDaoMock;
 * 
 * 	private PersonService classUnderTest;
 * 
 * 	@Before
 * 	public void setUp() {
 * 		classUnderTest = new PersonService(personDaoMock);
 * 	}
 *  ...
 * }
 * 
*

*/ @Target( { ElementType.FIELD }) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Mock { String[] value() default ""; /** * Name of the test subject field to which this mock will be assigned. Use to disambiguate the case where * a mock may be assigned to multiple fields of the same type. * When set, this mock will be assigned to the given field name in any test subject with a matching field name. * If not set, injection is to all type-compatible fields in all test subjects. * A given field name may only be used once, and there must be a matching field in at least one test subject. * * @return name of the field to inject to **/ String fieldName() default ""; } ================================================ FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/annotation/MockNice.java ================================================ package org.powermock.api.easymock.annotation; import org.powermock.core.classloader.annotations.PowerMockListener; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * This annotation can be placed on those fields in your test class that should * be mocked in a nice manner (i.e. by default allows all method calls and * returns appropriate empty values (0, {@code null} or {@code false} * )). This eliminates the need to setup and tear-down mocks manually which * minimizes repetitive test code and makes the test more readable. In order for * PowerMock to control the life-cycle of the mocks you must supply the * {@link PowerMockListener} annotation to the class-level of the test case. For * example when using the EasyMock API: * *

 * @PowerMockListener(EasyMockAnnotationEnabler.class)
 * public class PersonServiceTest {
 * 
 * 	@MockNice
 * 	private PersonDao personDaoMock;
 * 
 * 	private PersonService classUnderTest;
 * 
 * 	@Before
 * 	public void setUp() {
 * 		classUnderTest = new PersonService(personDaoMock);
 * 	}
 *  ...
 * }
 * 
*

* * Note that you can also create partial mocks by using the annotation. Let's * say that the PersonService has a method called "getPerson" and another method * called "savePerson" and these are the only two methods that you'd like to * mock. Rewriting the previous example to accommodate this will give us the * following test: * *

 * @PowerMockListener(EasyMockAnnotationEnabler.class)
 * public class PersonServiceTest {
 * 
 * 	@MockNice({"getPerson", "savePerson"})
 * 	private PersonDao personDaoMock;
 * 
 * 	private PersonService classUnderTest;
 * 
 * 	@Before
 * 	public void setUp() {
 * 		classUnderTest = new PersonService(personDaoMock);
 * 	}
 *  ...
 * }
 * 
*

* */ @Target( { ElementType.FIELD }) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited public @interface MockNice { String[] value() default ""; } ================================================ FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/annotation/MockStrict.java ================================================ package org.powermock.api.easymock.annotation; import org.powermock.core.classloader.annotations.PowerMockListener; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * This annotation can be placed on those fields in your test class that should * be mocked in a strict manner (i.e. the order of method calls are checked). * This eliminates the need to setup and tear-down mocks manually which * minimizes repetitive test code and makes the test more readable. In order for * PowerMock to control the life-cycle of the mocks you must supply the * {@link PowerMockListener} annotation to the class-level of the test case. For * example when using the EasyMock API: * *

 * @PowerMockListener(EasyMockAnnotationEnabler.class)
 * public class PersonServiceTest {
 * 
 * 	@MockStrict
 * 	private PersonDao personDaoMock;
 * 
 * 	private PersonService classUnderTest;
 * 
 * 	@Before
 * 	public void setUp() {
 * 		classUnderTest = new PersonService(personDaoMock);
 * 	}
 *  ...
 * }
 * 
*

* * Note that you can also create partial mocks by using the annotation. Let's * say that the PersonService has a method called "getPerson" and another method * called "savePerson" and these are the only two methods that you'd like to * mock. Rewriting the previous example to accommodate this will give us the * following test: * *

 * @PowerMockListener(EasyMockAnnotationEnabler.class)
 * public class PersonServiceTest {
 * 
 * 	@MockStrict({"getPerson", "savePerson"})
 * 	private PersonDao personDaoMock;
 * 
 * 	private PersonService classUnderTest;
 * 
 * 	@Before
 * 	public void setUp() {
 * 		classUnderTest = new PersonService(personDaoMock);
 * 	}
 *  ...
 * }
 * 
*

* */ @Target( { ElementType.FIELD }) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited public @interface MockStrict { String[] value() default ""; } ================================================ FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/internal/invocationcontrol/EasyMockMethodInvocationControl.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.api.easymock.internal.invocationcontrol; import org.easymock.MockType; import org.easymock.internal.MockInvocationHandler; import org.easymock.internal.MocksControl; import org.powermock.core.spi.MethodInvocationControl; import org.powermock.reflect.internal.WhiteboxImpl; import java.lang.reflect.Method; import java.util.Set; /** * The default implementation of the {@link MethodInvocationControl} interface. */ public class EasyMockMethodInvocationControl implements MethodInvocationControl { private MockInvocationHandler invocationHandler; private Set mockedMethods; private T mockInstance; private boolean hasReplayed; private boolean hasVerified; /** * Initializes internal state. * * @param invocationHandler The mock invocation handler to be associated with this * instance. * @param methodsToMock The methods that are mocked for this instance. If * {@code methodsToMock} is null all methods for the * {@code invocationHandler} are considered to be mocked. * @param mockInstance The actual mock instance. May be {@code null}. Even * though the mock instance may not be used it's needed to keep a * reference to this object otherwise it may be garbage collected * in some situations. For example when mocking static methods we * don't return the mock object and thus it will be garbage * collected (and thus the finalize method will be invoked which * will be caught by the proxy and the test will fail because we * haven't setup expectations for this method) because then that * object has no reference. In order to avoid this we keep a * reference to this instance here. */ public EasyMockMethodInvocationControl(MockInvocationHandler invocationHandler, Set methodsToMock, T mockInstance) { if (invocationHandler == null) { throw new IllegalArgumentException("Invocation Handler cannot be null."); } this.invocationHandler = invocationHandler; this.mockedMethods = methodsToMock; this.mockInstance = mockInstance; } /** * Initializes internal state. * * @param invocationHandler The mock invocation handler to be associated with this * instance. * @param methodsToMock The methods that are mocked for this instance. If * {@code methodsToMock} is null all methods for the * {@code invocationHandler} are considered to be mocked. */ public EasyMockMethodInvocationControl(MockInvocationHandler invocationHandler, Set methodsToMock) { this(invocationHandler, methodsToMock, null); } @Override public boolean isMocked(Method method) { return mockedMethods == null || (mockedMethods != null && mockedMethods.contains(method)); } @Override public Object invoke(Object proxy, Method method, Object[] arguments) throws Throwable { return invocationHandler.invoke(mockInstance == null ? proxy : mockInstance, method, arguments); } public MockType getMockType() { final MocksControl control = invocationHandler.getControl(); if (WhiteboxImpl.getFieldsOfType(control, MockType.class).isEmpty()) { // EasyMock is of version 3.2+ final MockType mockType = WhiteboxImpl.getInternalState(control, MockType.class); switch (mockType) { case DEFAULT: return MockType.DEFAULT; case NICE: return MockType.NICE; case STRICT: return MockType.STRICT; default: throw new IllegalStateException("PowerMock doesn't seem to work with the used EasyMock version. Please report to the PowerMock mailing list"); } } else { return WhiteboxImpl.getInternalState(control, MockType.class); } } @Override public synchronized Object replay(Object... mocks) { // Silently ignore replay if someone has replayed the mock before. if (!hasReplayed) { invocationHandler.getControl().replay(); hasReplayed = true; } return null; } public synchronized Object verify(Object... mocks) { // Silently ignore verify if someone has verified the mock before. if (!hasVerified) { invocationHandler.getControl().verify(); hasVerified = true; } return null; } @Override public synchronized Object reset(Object... mocks) { invocationHandler.getControl().reset(); hasReplayed = false; hasVerified = false; return null; } } ================================================ FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/internal/invocationcontrol/EasyMockNewInvocationControl.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.api.easymock.internal.invocationcontrol; import org.easymock.EasyMock; import org.easymock.IExpectationSetters; import org.easymock.MockType; import org.easymock.internal.MocksControl; import org.powermock.core.MockRepository; import org.powermock.core.spi.NewInvocationControl; import org.powermock.core.spi.support.InvocationSubstitute; import org.powermock.reflect.internal.WhiteboxImpl; import java.lang.reflect.Constructor; public class EasyMockNewInvocationControl implements NewInvocationControl> { private final InvocationSubstitute substitute; private final Class subsitutionType; private boolean hasReplayed; private boolean hasVerified; public EasyMockNewInvocationControl(InvocationSubstitute substitute, Class type) { if (substitute == null) { throw new IllegalArgumentException("Internal error: substitute cannot be null."); } this.subsitutionType = type; this.substitute = substitute; } @Override public Object invoke(Class type, Object[] args, Class[] sig) throws Exception { Constructor constructor = WhiteboxImpl.getConstructor(type, sig); if (constructor.isVarArgs()) { /* * Get the last argument because this contains the actual varargs * arguments. */ int length = constructor.getParameterTypes().length; args = (Object[]) args[length-1]; } try { final MockType mockType = ((EasyMockMethodInvocationControl) MockRepository.getInstanceMethodInvocationControl(substitute)) .getMockType(); Object result = substitute.performSubstitutionLogic(args); if (result == null) { if (mockType == MockType.NICE) { result = EasyMock.createNiceMock(subsitutionType); } else { throw new IllegalStateException("Must replay class " + type.getName() + " to get configured expectation."); } } return result; } catch (AssertionError e) { NewInvocationControlAssertionError.throwAssertionErrorForNewSubstitutionFailure(e, type); } // Won't happen return null; } @Override public IExpectationSetters expectSubstitutionLogic(Object... arguments) throws Exception { return EasyMock.expect(substitute.performSubstitutionLogic(arguments)); } @Override public synchronized Object replay(Object... mocks) { if (!hasReplayed) { EasyMock.replay(substitute); hasReplayed = true; } return null; } public synchronized Object verify(Object... mocks) { if (!hasVerified) { EasyMock.verify(substitute); hasVerified = true; } return null; } @Override public synchronized Object reset(Object... mocks) { EasyMock.reset(substitute); hasReplayed = false; hasVerified = false; return null; } } ================================================ FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/internal/invocationcontrol/NewInvocationControlAssertionError.java ================================================ package org.powermock.api.easymock.internal.invocationcontrol; import org.powermock.core.spi.support.InvocationSubstitute; import java.util.regex.Matcher; public class NewInvocationControlAssertionError { public static void throwAssertionErrorForNewSubstitutionFailure(AssertionError oldError, Class type) { /* * We failed to verify the new substitution mock. This happens when, for * example, the user has done something like * expectNew(MyClass.class).andReturn(myMock).times(3) when in fact an * instance of MyClass has been created less or more times than 3. */ String message = oldError.getMessage(); final String newSubsitutionMethodName = InvocationSubstitute.class.getDeclaredMethods()[0].getName(); final String className = InvocationSubstitute.class.getSimpleName(); message = message.replaceAll(className+"."+newSubsitutionMethodName, Matcher.quoteReplacement(type.getName())); message = message.replaceAll("method", "constructor"); throw new AssertionError(message); } } ================================================ FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/internal/mockstrategy/MockStrategy.java ================================================ package org.powermock.api.easymock.internal.mockstrategy; import org.easymock.IMocksControl; public interface MockStrategy { IMocksControl createMockControl(Class type); } ================================================ FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/internal/mockstrategy/impl/AbstractMockStrategyBase.java ================================================ package org.powermock.api.easymock.internal.mockstrategy.impl; import org.easymock.IMocksControl; import org.easymock.internal.MocksControl; import org.easymock.MockType; import org.powermock.api.easymock.internal.mockstrategy.MockStrategy; /** * Base class that should be used by all mock strategies. Enables mocking of * signed classes. */ public abstract class AbstractMockStrategyBase implements MockStrategy { private final MockType mockType; public AbstractMockStrategyBase(MockType mockType) { if (mockType == null) { throw new IllegalArgumentException("Internal error: mockType cannot be null"); } this.mockType = mockType; } @Override public IMocksControl createMockControl(Class type) { return new MocksControl(mockType); } } ================================================ FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/internal/mockstrategy/impl/DefaultMockStrategy.java ================================================ package org.powermock.api.easymock.internal.mockstrategy.impl; import org.easymock.MockType; public class DefaultMockStrategy extends AbstractMockStrategyBase { public DefaultMockStrategy() { super(MockType.DEFAULT); } } ================================================ FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/internal/mockstrategy/impl/NiceMockStrategy.java ================================================ package org.powermock.api.easymock.internal.mockstrategy.impl; import org.easymock.MockType; public class NiceMockStrategy extends AbstractMockStrategyBase { public NiceMockStrategy() { super(MockType.NICE); } } ================================================ FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/internal/mockstrategy/impl/StrictMockStrategy.java ================================================ package org.powermock.api.easymock.internal.mockstrategy.impl; import org.easymock.MockType; public class StrictMockStrategy extends AbstractMockStrategyBase { public StrictMockStrategy() { super(MockType.STRICT); } } ================================================ FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/mockpolicies/AbstractEasyMockLogPolicyBase.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.api.easymock.mockpolicies; import org.powermock.core.spi.PowerMockPolicy; import org.powermock.mockpolicies.MockPolicyClassLoadingSettings; import org.powermock.mockpolicies.MockPolicyInterceptionSettings; import org.powermock.mockpolicies.support.LogPolicySupport; import java.lang.reflect.Method; import static org.easymock.EasyMock.makeThreadSafe; import static org.powermock.api.easymock.PowerMock.createNiceMock; /** * A base class for EasyMock log policies. */ abstract class AbstractEasyMockLogPolicyBase implements PowerMockPolicy { @Override public void applyClassLoadingPolicy(MockPolicyClassLoadingSettings settings) { settings.addFullyQualifiedNamesOfClassesToLoadByMockClassloader(getFullyQualifiedNamesOfClassesToLoadByMockClassloader()); } @Override public void applyInterceptionPolicy(MockPolicyInterceptionSettings settings) { LogPolicySupport support = new LogPolicySupport(); Method[] loggerFactoryMethods = support.getLoggerMethods(getLoggerFactoryClassName(), getLoggerMethodName(), getLogFrameworkName()); Class loggerType = null; try { loggerType = support.getType(getLoggerClassToMock(), getLogFrameworkName()); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } final Object loggerMock = createNiceMock(loggerType); // Allow the mock to be used in a multi-threaded environment makeThreadSafe(loggerMock, true); for (Method method : loggerFactoryMethods) { settings.stubMethod(method, loggerMock); } } /** * @return The name of the methods in the Logger Factory that should return * a mock upon invocation. */ protected abstract String getLoggerMethodName(); /** * @return The fully-qualified class name of the Logger Factory that * contains the methods that should return a mock upon invocation. */ protected abstract String getLoggerFactoryClassName(); /** * @return The fully-qualified class name of the class that should be * mocked. The mock instance of this class will then be returned * each time a specified method in the Logger Factory is invoked. */ protected abstract String getLoggerClassToMock(); /** * @return The name of the log framework. Used in error messages, for * example if the {@link #getLoggerFactoryClassName()} cannot be * found in the classpath. */ protected abstract String getLogFrameworkName(); /** * @return The fully-qualified names of the classes that should be loaded by * the mock classloader. */ protected abstract String[] getFullyQualifiedNamesOfClassesToLoadByMockClassloader(); } ================================================ FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/mockpolicies/JclMockPolicy.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.api.easymock.mockpolicies; /** * A Jakarta Commons-Logging (JCL) mock policy. This mock policy deals with * solving JCL related mocking issues. It takes care of loading all concerned * JCL classes through the correct class-loader and automatically prepares and * injects logger instances. This policy does the following: *

    *
  1. Prepares all classes in the org.apache.commons.logging for test * as well as org.apache.log4j.Appender and * org.apache.log4j.xml.DOMConfigurator.
  2. *
  3. All calls to the * org.apache.commons.logging.LogFactory#getLog(..) methods are * intercepted and returns a nice mock of type * org.apache.commons.logging.Log.
  4. *
*/ public class JclMockPolicy extends AbstractEasyMockLogPolicyBase { /** * Loads all log4j classes with the mock classloader. */ protected String[] getFullyQualifiedNamesOfClassesToLoadByMockClassloader() { return new String[] { "org.apache.commons.logging.*", "org.apache.log4j.Appender", "org.apache.log4j.xml.DOMConfigurator" }; } @Override protected String getLogFrameworkName() { return "commons-logging"; } @Override protected String getLoggerClassToMock() { return "org.apache.commons.logging.Log"; } @Override protected String getLoggerFactoryClassName() { return "org.apache.commons.logging.LogFactory"; } @Override protected String getLoggerMethodName() { return "getLog"; } } ================================================ FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/mockpolicies/Log4jMockPolicy.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.api.easymock.mockpolicies; /** * A log4j mock policy. This mock policy deals with solving log4j related * mocking issues. It takes care of loading all concerned log4j classes through * the correct class-loader and automatically prepares and injects logger * instances. This policy does the following: *
    *
  1. Prepares all log4j classes and interfaces for testing.
  2. *
  3. All calls to the org.apache.log4j.Logger#getLogger(..) methods * are intercepted and returns a nice mock of type * org.apache.log4j.Logger.
  4. *
*/ public class Log4jMockPolicy extends AbstractEasyMockLogPolicyBase { private static final String LOGGER_CLASS = "org.apache.log4j.Logger"; /** * Loads all log4j classes with the mock classloader. */ @Override protected String[] getFullyQualifiedNamesOfClassesToLoadByMockClassloader() { return new String[] { "org.apache.log4j.*" }; } @Override protected String getLogFrameworkName() { return "log4j"; } @Override protected String getLoggerClassToMock() { return LOGGER_CLASS; } @Override protected String getLoggerFactoryClassName() { return LOGGER_CLASS; } @Override protected String getLoggerMethodName() { return "getLogger"; } } ================================================ FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/mockpolicies/Slf4jMockPolicy.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.api.easymock.mockpolicies; /** * An slf4j mock policy. This mock policy deals with solving slf4j related * mocking issues. It takes care of loading all concerned slf4j and log4j * classes through the correct class-loader and automatically prepares and * injects logger instances. This policy does the following: *
    *
  1. Prepares org.apache.log4j.Appender, * org.slf4j.LoggerFactory and * org.apache.log4j.xml.DOMConfigurator for testing.
  2. *
  3. All calls to the org.slf4j.LoggerFactory#getLogger(..) methods * are intercepted and returns a nice mock of type org.slf4j.Logger.
  4. *
*/ public class Slf4jMockPolicy extends AbstractEasyMockLogPolicyBase { @Override protected String[] getFullyQualifiedNamesOfClassesToLoadByMockClassloader() { return new String[] { "org.apache.log4j.Appender", "org.slf4j.LoggerFactory", "org.apache.log4j.xml.DOMConfigurator" }; } @Override protected String getLogFrameworkName() { return "slf4j"; } @Override protected String getLoggerClassToMock() { return "org.slf4j.Logger"; } @Override protected String getLoggerFactoryClassName() { return "org.slf4j.LoggerFactory"; } @Override protected String getLoggerMethodName() { return "getLogger"; } } ================================================ FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/powermocklistener/AnnotationEnabler.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.api.easymock.powermocklistener; import org.powermock.api.easymock.annotation.MockNice; import org.powermock.api.easymock.annotation.MockStrict; /** * Before each test method all fields annotated with {@link org.powermock.api.easymock.annotation.Mock}, * {@link MockNice} or {@link MockStrict} will have mock objects created for * them and injected to the fields. * * @deprecated Test Runners uses an annotation enabling listener per default * since version 1.3. You should just remove this listener. */ @Deprecated public class AnnotationEnabler extends org.powermock.api.extension.listener.AnnotationEnabler { } ================================================ FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/InjectFieldSearcher.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.api.extension; import org.powermock.api.extension.listener.MockMetadata; import java.lang.reflect.Field; /** * */ public interface InjectFieldSearcher { Field findField(Object instance, MockMetadata mockMetadata); } ================================================ FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/agent/JavaAgentFrameworkRegisterImpl.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.api.extension.agent; import org.powermock.core.agent.JavaAgentClassRegister; import org.powermock.core.agent.JavaAgentFrameworkRegister; /** * Implementation of JavaAgentFrameworkRegister for EasyMock framework. */ public class JavaAgentFrameworkRegisterImpl implements JavaAgentFrameworkRegister { @Override public void set(JavaAgentClassRegister javaAgentClassRegister) { } @Override public void clear() { } } ================================================ FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/AnnotationEnabler.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.api.extension.listener; import org.powermock.api.easymock.EasyMockConfiguration; import org.powermock.api.easymock.annotation.Mock; import org.powermock.api.easymock.annotation.MockNice; import org.powermock.api.easymock.annotation.MockStrict; import org.powermock.core.spi.listener.AnnotationEnablerListener; import org.powermock.core.spi.support.AbstractPowerMockTestListenerBase; import org.powermock.reflect.Whitebox; import java.lang.annotation.Annotation; import java.lang.reflect.Method; /** *

* Before each test method all fields annotated with * {@link Mock}, {@link org.powermock.api.easymock.annotation.Mock}, {@link org.easymock.Mock} * {@link MockNice} or {@link MockStrict} will have mock objects created for * them and injected to the fields. *

*

* Also all fields annotated with {@link org.easymock.TestSubject} will be processed and mocks are injected to fields * object, if these fields not null. *

*

* It will only inject to fields that haven't been set before (i.e that are * {@code null}). *

* * @see org.powermock.api.easymock.annotation.Mock * @see org.easymock.Mock * @see org.easymock.TestSubject * */ @SuppressWarnings({"deprecation", "JavadocReference"}) public class AnnotationEnabler extends AbstractPowerMockTestListenerBase implements AnnotationEnablerListener { @SuppressWarnings("unchecked") public Class[] getMockAnnotations() { return new Class[]{Mock.class, MockNice.class, MockStrict.class}; } @Override public void beforeTestMethod(Object testInstance, Method method, Object[] arguments) throws Exception { EasyMockConfiguration easyMockConfiguration = EasyMockConfiguration.getConfiguration(); if (!easyMockConfiguration.isReallyEasyMock()) { // Easymock API could be used as depends for JMock. return; } // first emulate default EasyMockRunner behavior if (easyMockConfiguration.isInjectMocksSupported()) { Whitebox.invokeMethod(Class.forName("org.easymock.EasyMockSupport"), "injectMocks", testInstance); } // then inject in empty fields mock created via PowerMock getEasyMockAnnotationSupport(testInstance).injectMocks(); } @SuppressWarnings("WeakerAccess") protected EasyMockAnnotationSupport getEasyMockAnnotationSupport(Object testInstance) { return new EasyMockAnnotationSupport(testInstance); } } ================================================ FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/AnnotationGlobalMetadata.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.api.extension.listener; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * */ class AnnotationGlobalMetadata { private final List qualifiedInjections = new ArrayList(5); private final List unqualifiedInjections = new ArrayList(5); private final Set qualifiers = new HashSet(); public List getQualifiedInjections() { return qualifiedInjections; } public List getUnqualifiedInjections() { return unqualifiedInjections; } public void add(List mocksMetadata) { for (MockMetadata mockMetadata : mocksMetadata) { add(mockMetadata); } } private void add(MockMetadata mockMetadata) { String qualifier = mockMetadata.getQualifier(); if (qualifier.length() != 0) { blockDuplicateQualifiers(qualifier); qualifiedInjections.add(mockMetadata); } else { unqualifiedInjections.add(mockMetadata); } } private void blockDuplicateQualifiers(String qualifier) { if (!qualifiers.add(qualifier)) { throw new RuntimeException(String.format("At least two mocks have fieldName qualifier '%s'", qualifier)); } } } ================================================ FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/AnnotationMockCreator.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.api.extension.listener; import java.lang.reflect.Method; /** * */ interface AnnotationMockCreator { Object createMockInstance(final Class type, final Method[] methods); } ================================================ FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/AnnotationMockCreatorFactory.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.api.extension.listener; import java.lang.reflect.Method; import static org.powermock.api.easymock.PowerMock.createMock; import static org.powermock.api.easymock.PowerMock.createNiceMock; import static org.powermock.api.easymock.PowerMock.createStrictMock; /** * */ class AnnotationMockCreatorFactory { public AnnotationMockCreator createDefaultMockCreator() { return new AnnotationMockCreator() { @Override public Object createMockInstance(Class type, Method[] methods) { return createMock(type, methods); } }; } public AnnotationMockCreator createNiceMockCreator() { return new AnnotationMockCreator() { @Override public Object createMockInstance(Class type, Method[] methods) { return createNiceMock(type, methods); } }; } public AnnotationMockCreator createStrictMockCreator() { return new AnnotationMockCreator() { @Override public Object createMockInstance(Class type, Method[] methods) { return createStrictMock(type, methods); } }; } } ================================================ FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/AnnotationMockMetadata.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.api.extension.listener; import org.powermock.reflect.Whitebox; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Arrays; @SuppressWarnings("WeakerAccess") public class AnnotationMockMetadata implements MockMetadata { private final Class type; private final Method[] methods; private final String qualifier; private final Class annotation; private final Annotation annotationInstance; private final String fieldName; private Object mock; public AnnotationMockMetadata(Class annotation, Field field) throws Exception { this.annotation = annotation; this.annotationInstance = field.getAnnotation(annotation); this.type = field.getType(); this.fieldName = field.getName(); this.methods = getMethod(); this.qualifier = findQualifier(); } private String findQualifier() { String fieldName = ""; try { fieldName = Whitebox.invokeMethod(annotationInstance, "fieldName"); } catch (Exception e) { // do nothing, because it means that Mock annotation doesn't support qualifier. S // ee org.easymock.Mock.fieldName } if (fieldName.length() == 0) { return ""; } else { return fieldName; } } @Override public String getFieldName() { return fieldName; } @Override public String getQualifier() { return qualifier; } @Override public Class getAnnotation() { return annotation; } @Override public Class getType() { return type; } @Override public Method[] getMethods() { return methods; } private Method[] getMethod() throws Exception { final String[] value = Whitebox.invokeMethod(annotationInstance, "value"); if (value.length != 1 || !"".equals(value[0])) { return Whitebox.getMethods(type, value); } return null; } @Override public Object getMock() { return mock; } @Override public void setMock(Object mock) { this.mock = mock; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } AnnotationMockMetadata that = (AnnotationMockMetadata) o; if (type != null ? !type.equals(that.type) : that.type != null) { return false; } // Probably incorrect - comparing Object[] arrays with Arrays.equals return Arrays.equals(methods, that.methods) && (qualifier != null ? qualifier.equals(that.qualifier) : that.qualifier == null); } @Override public int hashCode() { int result = type != null ? type.hashCode() : 0; result = 31 * result + Arrays.hashCode(methods); result = 31 * result + (qualifier != null ? qualifier.hashCode() : 0); return result; } } ================================================ FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/AnnotationMockScanner.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.api.extension.listener; import org.powermock.reflect.Whitebox; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import java.util.Set; class AnnotationMockScanner { private final Class annotation; public AnnotationMockScanner(Class annotation) { this.annotation = annotation; } public List scan(Object instance) throws Exception { final List mocksMetadata = new ArrayList(); final Set fields = getFields(instance); for (Field field : fields) { if (field.get(instance) != null) { continue; } mocksMetadata.add(new AnnotationMockMetadata(annotation, field)); } return mocksMetadata; } @SuppressWarnings("unchecked") private Set getFields(Object instance) { final Set fields; if (annotation != null) { fields = Whitebox.getFieldsAnnotatedWith(instance, annotation); }else{ fields = Whitebox.getAllInstanceFields(instance); } return fields; } } ================================================ FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/DefaultInjectFieldSearcher.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.api.extension.listener; import org.powermock.api.extension.InjectFieldSearcher; import org.powermock.reflect.Whitebox; import java.lang.reflect.Field; import java.util.HashSet; import java.util.Set; /** * */ @SuppressWarnings("unchecked") class DefaultInjectFieldSearcher implements InjectFieldSearcher { @Override public Field findField(Object instance, MockMetadata mockMetadata) { Set candidates = Whitebox.getFieldsAnnotatedWith(instance, mockMetadata.getAnnotation()); if (candidates.size() == 1) { return candidates.iterator().next(); } candidates = filterByQualifier(candidates, mockMetadata.getQualifier()); if (candidates.size() == 1) { return candidates.iterator().next(); } candidates = filterByType(candidates, mockMetadata.getType()); if (candidates.size() == 1) { return candidates.iterator().next(); } candidates = filterByFieldName(candidates, mockMetadata.getFieldName()); if (candidates.size() == 1) { return candidates.iterator().next(); } return null; } private Set filterByFieldName(final Set candidates, final String fieldName) { if (fieldName == null || fieldName.length() == 0) { return candidates; } return doFilterByQualifier(candidates, fieldName); } private Set filterByType(Set candidates, Class type) { if (type == null) { return candidates; } return doFilterByType(candidates, type); } private Set doFilterByType(Set candidates, Class type) { Set fields = new HashSet(); for (Field candidate : candidates) { if (candidate.getType().isAssignableFrom(type)) { fields.add(candidate); } } return fields; } private Set filterByQualifier(Set candidates, String qualifier) { if (qualifier == null || qualifier.length() == 0) { return candidates; } return doFilterByQualifier(candidates, qualifier); } private Set doFilterByQualifier(Set candidates, String qualifier) { Set fields = new HashSet(); for (Field candidate : candidates) { if (candidate.getName().equals(qualifier)) { fields.add(candidate); } } return fields; } } ================================================ FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/EasyMockAnnotationSupport.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.api.extension.listener; import org.powermock.api.easymock.EasyMockConfiguration; import org.powermock.api.easymock.annotation.Mock; import org.powermock.api.easymock.annotation.MockNice; import org.powermock.api.easymock.annotation.MockStrict; import org.powermock.api.extension.InjectFieldSearcher; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.util.List; /** * This class works like as {@link org.easymock.EasyMockSupport} and is used to create and inject mocks to * annotated fields of an instance of test class. * * @see Mock * @see org.easymock.Mock * @see org.easymock.TestSubject */ @SuppressWarnings({"WeakerAccess", "JavadocReference"}) public class EasyMockAnnotationSupport { private final Object testInstance; private final AnnotationMockCreatorFactory annotationMockCreatorFactory; private final AnnotationGlobalMetadata globalMetadata; private final EasyMockConfiguration easyMockConfiguration; public EasyMockAnnotationSupport(Object testInstance) { this.testInstance = testInstance; this.annotationMockCreatorFactory = new AnnotationMockCreatorFactory(); this.globalMetadata = new AnnotationGlobalMetadata(); this.easyMockConfiguration = EasyMockConfiguration.getConfiguration(); } public void injectMocks() throws Exception { injectStrictMocks(); injectNiceMocks(); injectDefaultMocks(); injectTestSubjectMocks(); } protected void injectStrictMocks() throws Exception { inject(testInstance, MockStrict.class, annotationMockCreatorFactory.createStrictMockCreator()); } protected void injectNiceMocks() throws Exception { inject(testInstance, MockNice.class, annotationMockCreatorFactory.createNiceMockCreator()); } @SuppressWarnings("deprecation") protected void injectDefaultMocks() throws Exception { inject(testInstance, Mock.class, annotationMockCreatorFactory.createDefaultMockCreator()); } @SuppressWarnings("unchecked") protected void injectTestSubjectMocks() throws IllegalAccessException { if (easyMockConfiguration.isTestSubjectSupported()) { TestSubjectInjector testSubjectInjector = new TestSubjectInjector(testInstance, globalMetadata); testSubjectInjector.injectTestSubjectMocks(); } } protected void inject(Object injectCandidateInstance, Class annotation, AnnotationMockCreator mockCreator) throws Exception { AnnotationMockScanner scanner = new AnnotationMockScanner(annotation); List mocksMetadata = scanner.scan(injectCandidateInstance); globalMetadata.add(mocksMetadata); for (MockMetadata mockMetadata : mocksMetadata) { injectMock(injectCandidateInstance, mockMetadata, mockCreator, new DefaultInjectFieldSearcher()); } } protected void injectMock(Object injectCandidateInstance, MockMetadata mockMetadata, AnnotationMockCreator mockCreator, InjectFieldSearcher fieldSearch) throws IllegalAccessException { Object mock = createMock(mockCreator, mockMetadata); Field field = fieldSearch.findField(injectCandidateInstance, mockMetadata); if (field != null && mock != null) { field.setAccessible(true); field.set(injectCandidateInstance, mock); } } protected Object createMock(AnnotationMockCreator mockCreator, MockMetadata mockMetadata) { if (mockMetadata.getMock() == null) { Object mock = mockCreator.createMockInstance(mockMetadata.getType(), mockMetadata.getMethods()); mockMetadata.setMock(mock); } return mockMetadata.getMock(); } } ================================================ FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/MockMetadata.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.api.extension.listener; import java.lang.annotation.Annotation; import java.lang.reflect.Method; /** * */ public interface MockMetadata { String getFieldName(); String getQualifier(); Class getAnnotation(); Class getType(); Method[] getMethods(); Object getMock(); void setMock(Object mock); } ================================================ FILE: powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/TestSubjectInjector.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.api.extension.listener; import org.easymock.Mock; import org.easymock.TestSubject; import org.powermock.reflect.Whitebox; import java.lang.reflect.Field; import java.util.HashSet; import java.util.Set; /** * The class injects mocks created with {@link Mock}, {@link org.powermock.api.easymock.annotation.Mock} * to fields of objects which is annotated with {@link TestSubject} * @see TestSubject * @since 1.6.5 */ @SuppressWarnings({"deprecation", "WeakerAccess"}) class TestSubjectInjector { private final Object testInstance; private final AnnotationGlobalMetadata globalMetadata; public TestSubjectInjector(Object testInstance, AnnotationGlobalMetadata globalMetadata) { this.testInstance = testInstance; this.globalMetadata = globalMetadata; } @SuppressWarnings("unchecked") protected void injectTestSubjectMocks() throws IllegalAccessException { Set testSubjectFields = Whitebox.getFieldsAnnotatedWith(testInstance, TestSubject.class); for (Field testSubjectField : testSubjectFields) { Object testSubject = testSubjectField.get(testInstance); if (testSubject == null) { throw new NullPointerException("Have you forgotten to instantiate " + testSubjectField.getName() + "?"); } injectTestSubjectFields(testSubject); } } protected void injectTestSubjectFields(Object testSubject) throws IllegalAccessException { Set targetFields = new HashSet(Whitebox.getAllInstanceFields(testSubject)); targetFields = injectByName(targetFields, testSubject); injectByType(targetFields, testSubject); } void injectByType(Set targetFields, Object testSubject) throws IllegalAccessException { for (Field targetField : targetFields) { InjectionTarget target = new InjectionTarget(targetField); MockMetadata toAssign = findUniqueAssignable(target); if (toAssign == null) { continue; } target.inject(testSubject, toAssign); } } MockMetadata findUniqueAssignable(InjectionTarget target) { MockMetadata toAssign = null; for (MockMetadata mockMetadata : globalMetadata.getUnqualifiedInjections()) { if (target.accepts(mockMetadata)) { if (toAssign != null) { throw new RuntimeException(String.format("At least two mocks can be assigned to '%s': %s and %s", target.getField(), toAssign.getMock(), mockMetadata.getMock())); } toAssign = mockMetadata; } } return toAssign; } Set injectByName(Set targetFields, Object targetObject) throws IllegalAccessException { Class targetClass = targetObject.getClass(); for (MockMetadata mockMetadata : globalMetadata.getQualifiedInjections()) { Field targetField = getFieldByName(targetClass, mockMetadata.getQualifier()); if (targetField == null) { continue; } InjectionTarget target = new InjectionTarget(targetField); if (target.accepts(mockMetadata)) { target.inject(targetObject, mockMetadata); targetFields.remove(targetField); } } return targetFields; } private Field getFieldByName(Class clazz, String fieldName) { try { return clazz.getDeclaredField(fieldName); } catch (NoSuchFieldException e) { return null; } catch (SecurityException e) { return null; } } private static class InjectionTarget { private final Field field; public InjectionTarget(Field field) { this.field = field; } public Field getField() { return field; } public boolean accepts(MockMetadata mockMetadata) { return field.getType().isAssignableFrom(mockMetadata.getType()); } public void inject(Object targetObject, MockMetadata mockMetadata) throws IllegalAccessException { field.setAccessible(true); Object value = field.get(targetObject); if (value == null) { field.set(targetObject, mockMetadata.getMock()); } } } } ================================================ FILE: powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/extension/agent/JavaAgentFrameworkRegisterImpl.java ================================================ package org.powermock.api.extension.agent; import org.powermock.api.mockito.internal.mockcreation.MockCreator; import org.powermock.core.agent.JavaAgentClassRegister; import org.powermock.core.agent.JavaAgentFrameworkRegister; import org.powermock.reflect.Whitebox; /** * Implementation of JavaAgentFrameworkRegister for Mockito framework. */ public class JavaAgentFrameworkRegisterImpl implements JavaAgentFrameworkRegister { public static final String MOCK_CREATOR_IMPLEMENTATION_CLASS = "org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator"; private MockCreator mockCreator; @Override public void set(JavaAgentClassRegister javaAgentClassRegister) { setToPowerMockito(javaAgentClassRegister); } private void setToPowerMockito(JavaAgentClassRegister javaAgentClassRegister) { mockCreator = getPowerMockCoreForCurrentClassLoader(); Whitebox.setInternalState(mockCreator, "agentClassRegister", javaAgentClassRegister); } private MockCreator getPowerMockCoreForCurrentClassLoader() { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); try { return Whitebox.getInternalState(classLoader.loadClass(MOCK_CREATOR_IMPLEMENTATION_CLASS), "MOCK_CREATOR"); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } @Override public void clear() { if (mockCreator == null) { throw new IllegalStateException("Cannot clear JavaAgentClassRegister. Set method has not been called."); } Whitebox.setInternalState(mockCreator, "agentClassRegister", (Object) null); } } ================================================ FILE: powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/extension/listener/AnnotationEnabler.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.api.extension.listener; import org.mockito.Answers; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.MockSettings; import org.mockito.exceptions.base.MockitoException; import org.mockito.internal.configuration.InjectingAnnotationEngine; import org.mockito.internal.util.reflection.GenericMaster; import org.powermock.api.mockito.internal.configuration.PowerMockitoInjectingAnnotationEngine; import org.powermock.core.spi.listener.AnnotationEnablerListener; import org.powermock.core.spi.support.AbstractPowerMockTestListenerBase; import org.powermock.reflect.Whitebox; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Set; import static org.mockito.Mockito.withSettings; import static org.powermock.api.mockito.PowerMockito.mock; /** * Before each test method all fields annotated with {@link Mock}, * {@link org.mockito.Mock} or {@link Mock} have mock objects created for them * and injected to the fields. It will also delegate to a special implementation * of the {@link InjectingAnnotationEngine} in Mockito which inject's spies, * captors etc. *

* It will only inject to fields that haven't been set before (i.e that are * {@code null}). */ @SuppressWarnings("deprecation") public class AnnotationEnabler extends AbstractPowerMockTestListenerBase implements AnnotationEnablerListener { @Override public void beforeTestMethod(Object testInstance, Method method, Object[] arguments) throws Exception { standardInject(testInstance); injectSpiesAndInjectToSetters(testInstance); injectCaptor(testInstance); } private void injectSpiesAndInjectToSetters(Object testInstance) { new PowerMockitoInjectingAnnotationEngine().process(testInstance.getClass(), testInstance); } private void injectCaptor(Object testInstance) throws Exception { Set fieldsAnnotatedWithCaptor = Whitebox.getFieldsAnnotatedWith(testInstance, Captor.class); for (Field field : fieldsAnnotatedWithCaptor) { final Object captor = processAnnotationOn(field.getAnnotation(Captor.class), field); field.set(testInstance, captor); } } private void standardInject(Object testInstance) throws IllegalAccessException { Set fields = Whitebox.getFieldsAnnotatedWith(testInstance, getMockAnnotations()); for (Field field : fields) { if (field.get(testInstance) != null) { continue; } final Class type = field.getType(); if (field.isAnnotationPresent(org.mockito.Mock.class)) { org.mockito.Mock mockAnnotation = field.getAnnotation(org.mockito.Mock.class); MockSettings mockSettings = withSettings(); Answers answers = mockAnnotation.answer(); if (answers != null) { mockSettings.defaultAnswer(answers); } Class[] extraInterfaces = mockAnnotation.extraInterfaces(); if (extraInterfaces != null && extraInterfaces.length > 0) { mockSettings.extraInterfaces(extraInterfaces); } String name = mockAnnotation.name(); if (name != null && name.length() > 0) { mockSettings.name(name); } field.set(testInstance, mock(type, mockSettings)); } else { field.set(testInstance, mock(type)); } } } @SuppressWarnings("unchecked") @Override public Class[] getMockAnnotations() { return new Class[]{org.mockito.Mock.class, Mock.class}; } private Object processAnnotationOn(Captor annotation, Field field) { Class type = field.getType(); if (!ArgumentCaptor.class.isAssignableFrom(type)) { throw new MockitoException("@Captor field must be of the type ArgumentCaptor.\n" + "Field: '" + field.getName() + "' has wrong type\n" + "For info how to use @Captor annotations see examples in javadoc for MockitoAnnotations class."); } Class cls = new GenericMaster().getGenericType(field); return ArgumentCaptor.forClass(cls); } } ================================================ FILE: powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/ClassNotPreparedException.java ================================================ package org.powermock.api.mockito; /** * The exception is thrown when a user tries to mock class which is't prepared, but should be. For example it could * be case mocking static call. */ public class ClassNotPreparedException extends RuntimeException { public ClassNotPreparedException(String message) { super(message); } } ================================================ FILE: powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/PowerMockito.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.api.mockito; import org.mockito.MockSettings; import org.mockito.Mockito; import org.mockito.stubbing.Answer; import org.mockito.stubbing.OngoingStubbing; import org.mockito.verification.VerificationMode; import org.powermock.api.mockito.expectation.ConstructorAwareExpectationSetup; import org.powermock.api.mockito.expectation.ConstructorExpectationSetup; import org.powermock.api.mockito.expectation.DefaultConstructorExpectationSetup; import org.powermock.api.mockito.expectation.PowerMockitoStubber; import org.powermock.api.mockito.expectation.WithOrWithoutExpectedArguments; import org.powermock.api.mockito.internal.PowerMockitoCore; import org.powermock.api.mockito.internal.expectation.DefaultMethodExpectationSetup; import org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator; import org.powermock.api.mockito.internal.verification.DefaultPrivateMethodVerification; import org.powermock.api.mockito.internal.verification.VerifyNoMoreInteractions; import org.powermock.api.mockito.verification.ConstructorArgumentsVerification; import org.powermock.api.mockito.verification.PrivateMethodVerification; import org.powermock.api.support.membermodification.MemberModifier; import org.powermock.reflect.Whitebox; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import static org.mockito.Mockito.times; import static org.mockito.Mockito.withSettings; /** * PowerMockito extends Mockito functionality with several new features such as * mocking static and private methods and more. Use PowerMock instead of Mockito * where applicable. * * @see Mockito */ public class PowerMockito extends MemberModifier { private static final PowerMockitoCore POWERMOCKITO_CORE = new PowerMockitoCore(); /** * Enable static mocking for all methods of a class. * * @param type the class to enable static mocking */ public static synchronized void mockStatic(Class type, Class... types) { DefaultMockCreator.mock(type, true, false, null, null, (Method[]) null); if (types != null && types.length > 0) { for (Class aClass : types) { DefaultMockCreator.mock(aClass, true, false, null, null, (Method[]) null); } } } /** * Creates class mock with a specified strategy for its answers to * interactions. It's quite advanced feature and typically you don't need it * to write decent tests. However it can be helpful when working with legacy * systems. *

* It is the default answer so it will be used only when you don't * stub the method call. *

*

     * mockStatic(Foo.class, RETURNS_SMART_NULLS);
     * mockStatic(Foo.class, new YourOwnAnswer());
     * 
* * @param classMock class to mock * @param defaultAnswer default answer for unstubbed methods */ public static void mockStatic(Class classMock, @SuppressWarnings("rawtypes") Answer defaultAnswer) { mockStatic(classMock, withSettings().defaultAnswer(defaultAnswer)); } /** * Creates a class mock with some non-standard settings. *

* The number of configuration points for a mock grows so we need a fluent * way to introduce new configuration without adding more and more * overloaded PowerMockito.mockStatic() methods. Hence {@link MockSettings}. *

*

     *   mockStatic(Listener.class, withSettings()
     *     .name("firstListner").defaultBehavior(RETURNS_SMART_NULLS));
     *   );
     * 
*

* Use it carefully and occasionally. What might be reason your test * needs non-standard mocks? Is the code under test so complicated that it * requires non-standard mocks? Wouldn't you prefer to refactor the code * under test so it is testable in a simple way? *

* See also {@link Mockito#withSettings()} * * @param classToMock class to mock * @param mockSettings additional mock settings */ public static void mockStatic(Class classToMock, MockSettings mockSettings) { DefaultMockCreator.mock(classToMock, true, false, null, mockSettings, (Method[]) null); } /** * Creates a mock object that supports mocking of final and native methods. * * @param the type of the mock object * @param type the type of the mock object * @return the mock object. */ public static synchronized T mock(Class type) { return DefaultMockCreator.mock(type, false, false, null, null, (Method[]) null); } /** * Creates mock with a specified strategy for its answers to interactions. * It's quite advanced feature and typically you don't need it to write * decent tests. However it can be helpful when working with legacy systems. *

* It is the default answer so it will be used only when you don't * stub the method call. *

*

     * Foo mock = mock(Foo.class, RETURNS_SMART_NULLS);
     * Foo mockTwo = mock(Foo.class, new YourOwnAnswer());
     * 
*

*

* See examples in javadoc for {@link Mockito} class *

* * @param classToMock class or interface to mock * @param defaultAnswer default answer for unstubbed methods * @return mock object */ public static T mock(Class classToMock, @SuppressWarnings("rawtypes") Answer defaultAnswer) { return mock(classToMock, withSettings().defaultAnswer(defaultAnswer)); } /** * Creates a mock with some non-standard settings. *

* The number of configuration points for a mock grows so we need a fluent * way to introduce new configuration without adding more and more * overloaded Mockito.mock() methods. Hence {@link MockSettings}. *

*

     *   Listener mock = mock(Listener.class, withSettings()
     *     .name("firstListner").defaultBehavior(RETURNS_SMART_NULLS));
     *   );
     * 
*

* Use it carefully and occasionally. What might be reason your test * needs non-standard mocks? Is the code under test so complicated that it * requires non-standard mocks? Wouldn't you prefer to refactor the code * under test so it is testable in a simple way? *

* See also {@link Mockito#withSettings()} *

* See examples in javadoc for {@link Mockito} class * * @param classToMock class or interface to mock * @param mockSettings additional mock settings * @return mock object */ public static T mock(Class classToMock, MockSettings mockSettings) { return DefaultMockCreator.mock(classToMock, false, false, null, mockSettings, (Method[]) null); } /** * Spy on objects that are final or otherwise not "spyable" from * normal Mockito. * * @param the type of the mock object * @param object the object to spy on * @return the spy object. * @see PowerMockito#spy(Object) */ @SuppressWarnings("unchecked") public static synchronized T spy(T object) { return POWERMOCKITO_CORE.spy(object); } /** * Spy on classes (not "spyable" from normal Mockito). * * @param the type of the class mock * @param type the type of the class mock * @see PowerMockito#spy(Object) */ public static synchronized void spy(Class type) { MockSettings mockSettings = Mockito.withSettings().defaultAnswer(Mockito.CALLS_REAL_METHODS); DefaultMockCreator.mock(type, true, true, type, mockSettings, (Method[]) null); } /** * Verifies certain behavior of the mockedClass happened once *

* Alias to {@code verifyStatic(classMock, times(1))} E.g: *

*

     * verifyStatic(ClassWithStaticMethod.class);
     * ClassWithStaticMethod.someStaticMethod("some arg");
     * 
*

* Above is equivalent to: *

*

     * verifyStatic(ClassWithStaticMethod.class, times(1));
     * ClassWithStaticMethod.someStaticMethod("some arg");
     * 
*

*

* Although it is possible to verify a stubbed invocation, usually it's * just redundant. Let's say you've stubbed foo.bar(). If your code * cares what foo.bar() returns then something else breaks(often before even * verify() gets executed). If your code doesn't care what get(0) returns * then it should not be stubbed. * * @param mockedClass the mocked class behavior of that have to be verified. */ public static synchronized void verifyStatic(Class mockedClass) { verifyStatic(mockedClass, times(1)); } /** * Verifies certain behavior of the mockedClass happened at least once / exact number of times * / never. E.g: *

*

     *   verifyStatic(ClassWithStaticMethod.class, times(5));
     *   ClassWithStaticMethod.someStaticMethod("was called five times");
     *
     *   verifyStatic(ClassWithStaticMethod.class, atLeast(2));
     *   ClassWithStaticMethod.someStaticMethod("was called at least two times");
     *
     *   //you can use flexible argument matchers, e.g:
     *   verifyStatic(ClassWithStaticMethod.class, atLeastOnce());
     *   ClassWithStaticMethod.someMethod(<b>anyString()</b>);
     * 
*

* times(1) is the default and can be omitted *

* * @param mockedClass the mocked class behavior of that have to be verified. * @param verificationMode times(x), atLeastOnce() or never() */ public static synchronized void verifyStatic(Class mockedClass, VerificationMode verificationMode) { Mockito.verify(mockedClass, verificationMode); } /** * Verify a private method invocation for an instance. * * @see Mockito#verify(Object) */ public static PrivateMethodVerification verifyPrivate(Object object) { return verifyPrivate(object, times(1)); } /** * Verify a private method invocation with a given verification mode. * * @see Mockito#verify(Object) */ public static PrivateMethodVerification verifyPrivate(Object object, VerificationMode verificationMode) { Mockito.verify(object, verificationMode); return new DefaultPrivateMethodVerification(object); } /** * Verify a private method invocation for a class. * * @throws Exception If something unexpected goes wrong. * @see Mockito#verify(Object) */ public static PrivateMethodVerification verifyPrivate(Class clazz) throws Exception { return verifyPrivate((Object) clazz); } /** * Verify a private method invocation for a class with a given verification * mode. * * @see Mockito#verify(Object) */ public static PrivateMethodVerification verifyPrivate(Class clazz, VerificationMode verificationMode) { return verifyPrivate((Object) clazz, verificationMode); } /** * Verifies certain behavior happened once *

* Alias to verifyNew(mockClass, times(1)) E.g: *

*

     * verifyNew(ClassWithStaticMethod.class);
     * 
*

* Above is equivalent to: *

*

     * verifyNew(ClassWithStaticMethod.class, times(1));
     * 
*

*

* * @param mock Class mocked by PowerMock. */ @SuppressWarnings("unchecked") public static synchronized ConstructorArgumentsVerification verifyNew(Class mock) { return verifyNew(mock, times(1)); } /** * Verifies certain behavior happened at least once / exact number of times * / never. E.g: *

*

     * verifyNew(ClassWithStaticMethod.class, times(5));
     *
     * verifyNew(ClassWithStaticMethod.class, atLeast(2));
     *
     * //you can use flexible argument matchers, e.g:
     * verifyNew(ClassWithStaticMethod.class, atLeastOnce());
     * 
*

* times(1) is the default and can be omitted *

* * @param mock to be verified * @param mode times(x), atLeastOnce() or never() */ @SuppressWarnings("unchecked") public static ConstructorArgumentsVerification verifyNew(Class mock, VerificationMode mode) { return POWERMOCKITO_CORE.verifyNew(mock, mode); } /** * Expect calls to private methods. * * @throws Exception If something unexpected goes wrong. * @see PowerMockito#when(Object) */ public static OngoingStubbing when(Object instance, String methodName, Object... arguments) throws Exception { return Mockito.when(Whitebox.invokeMethod(instance, methodName, arguments)); } /** * Expect calls to private methods. * * @see PowerMockito#when(Object) */ public static WithOrWithoutExpectedArguments when(Object instance, Method method) { return new DefaultMethodExpectationSetup(instance, method); } /** * Expect calls to private static methods. * * @see PowerMockito#when(Object) */ public static WithOrWithoutExpectedArguments when(Class cls, Method method) { return new DefaultMethodExpectationSetup(cls, method); } /** * Expect calls to private methods without having to specify the method * name. The method will be looked up using the parameter types (if * possible). * * @throws Exception If something unexpected goes wrong. * @see PowerMockito#when(Object) */ public static OngoingStubbing when(Object instance, Object... arguments) throws Exception { return Mockito.when(Whitebox.invokeMethod(instance, arguments)); } /** * Expect a static private or inner class method call. * * @throws Exception If something unexpected goes wrong. * @see PowerMockito#when(Object) */ public static OngoingStubbing when(Class clazz, String methodToExpect, Object... arguments) throws Exception { return Mockito.when(Whitebox.invokeMethod(clazz, methodToExpect, arguments)); } /** * Expect calls to private static methods without having to specify the * method name. The method will be looked up using the parameter types if * possible * * @throws Exception If something unexpected goes wrong. * @see PowerMockito#when(Object) */ public static OngoingStubbing when(Class klass, Object... arguments) throws Exception { return Mockito.when(Whitebox.invokeMethod(klass, arguments)); } /** * Just delegates to the original {@link Mockito#when(Object)} method. * * @see PowerMockito#when(Object) */ public static OngoingStubbing when(T methodCall) { return Mockito.when(methodCall); } /** * Allows specifying expectations on new invocations. For example you might * want to throw an exception or return a mock. */ public static synchronized WithOrWithoutExpectedArguments whenNew(Constructor ctor) { return new ConstructorAwareExpectationSetup(ctor); } /** * Allows specifying expectations on new invocations. For example you might * want to throw an exception or return a mock. */ public static synchronized ConstructorExpectationSetup whenNew(Class type) { return new DefaultConstructorExpectationSetup(type); } /** * Allows specifying expectations on new invocations for private member * (inner) classes, local or anonymous classes. For example you might want * to throw an exception or return a mock. * * @param fullyQualifiedName The fully-qualified name of the inner/local/anonymous type to * expect. */ @SuppressWarnings("unchecked") public static synchronized ConstructorExpectationSetup whenNew(String fullyQualifiedName) throws Exception { final Class forName = (Class) Class.forName(fullyQualifiedName); return new DefaultConstructorExpectationSetup(forName); } /** * Checks if any of given mocks (can be both instance and class mocks) has * any unverified interaction. Delegates to the original * {@link Mockito#verifyNoMoreInteractions(Object...)} if the mock is not a * PowerMockito mock. *

* You can use this method after you verified your mocks - to make sure that * nothing else was invoked on your mocks. *

* See also {@link Mockito#never()} - it is more explicit and communicates * the intent well. *

* Stubbed invocations (if called) are also treated as interactions. *

* A word of warning: Some users who did a lot of classic, * expect-run-verify mocking tend to use verifyNoMoreInteractions() very * often, even in every test method. verifyNoMoreInteractions() is not * recommended to use in every test method. verifyNoMoreInteractions() is a * handy assertion from the interaction testing toolkit. Use it only when * it's relevant. Abusing it leads to over-specified, less maintainable * tests. You can find further reading here. *

* This method will also detect unverified invocations that occurred before * the test method, for example: in setUp(), @Before method or in * constructor. Consider writing nice code that makes interactions only in * test methods. *

*

* Example: *

*

     * //interactions
     * mock.doSomething();
     * mock.doSomethingUnexpected();
     *
     * //verification
     * verify(mock).doSomething();
     *
     * //following will fail because 'doSomethingUnexpected()' is unexpected
     * verifyNoMoreInteractions(mock);
     *
     * 
*

* See examples in javadoc for {@link Mockito} class * * @param mocks to be verified */ public static void verifyNoMoreInteractions(Object... mocks) { VerifyNoMoreInteractions.verifyNoMoreInteractions(mocks); } /** * Verifies that no interactions happened on given mocks (can be both * instance and class mocks). Delegates to the original * {@link PowerMockito#verifyNoMoreInteractions(Object...)} if the mock is not a * PowerMockito mock. *

*

     * verifyZeroInteractions(mockOne, mockTwo);
     * 
*

* This method will also detect invocations that occurred before the test * method, for example: in setUp(), @Before method or in constructor. * Consider writing nice code that makes interactions only in test methods. *

* See also {@link Mockito#never()} - it is more explicit and communicates * the intent well. *

* See examples in javadoc for {@link Mockito} class * * @param mocks to be verified */ public static void verifyZeroInteractions(Object... mocks) { VerifyNoMoreInteractions.verifyNoMoreInteractions(mocks); } /** * Use doAnswer() when you want to stub a void method with generic * {@link Answer}. *

* Stubbing voids requires different approach from * {@link PowerMockito#when(Object)} because the compiler does not like void * methods inside brackets... *

* Example: *

*

     * doAnswer(new Answer() {
     *     public Object answer(InvocationOnMock invocation) {
     *         Object[] args = invocation.getArguments();
     *         Mock mock = invocation.getMock();
     *         return null;
     *     }
     * }).when(mock).someMethod();
     * 
*

* See examples in javadoc for {@link Mockito} class * * @param answer to answer when the stubbed method is called * @return stubber - to select a method for stubbing */ public static PowerMockitoStubber doAnswer(Answer answer) { return POWERMOCKITO_CORE.doAnswer(answer); } /** * Use doThrow() when you want to stub the void method with an exception. *

* Stubbing voids requires different approach from * {@link PowerMockito#when(Object)} because the compiler does not like void * methods inside brackets... *

* Example: *

*

     * doThrow(new RuntimeException()).when(mock).someVoidMethod();
     * 
* * @param toBeThrown to be thrown when the stubbed method is called * @return stubber - to select a method for stubbing */ public static PowerMockitoStubber doThrow(Throwable toBeThrown) { return POWERMOCKITO_CORE.doThrow(toBeThrown); } /** * Use doCallRealMethod() when you want to call the real implementation of a * method. *

* As usual you are going to read the partial mock warning: Object * oriented programming is more less tackling complexity by dividing the * complexity into separate, specific, SRPy objects. How does partial mock * fit into this paradigm? Well, it just doesn't... Partial mock usually * means that the complexity has been moved to a different method on the * same object. In most cases, this is not the way you want to design your * application. *

* However, there are rare cases when partial mocks come handy: dealing with * code you cannot change easily (3rd party interfaces, interim refactoring * of legacy code etc.) However, I wouldn't use partial mocks for new, * test-driven & well-designed code. *

* See also javadoc {@link PowerMockito#spy(Object)} to find out more about * partial mocks. Mockito.spy() is a recommended way of creating partial * mocks. The reason is it guarantees real methods are called against * correctly constructed object because you're responsible for constructing * the object passed to spy() method. *

* Example: *

*

     * Foo mock = mock(Foo.class);
     * doCallRealMethod().when(mock).someVoidMethod();
     *
     * // this will call the real implementation of Foo.someVoidMethod()
     * mock.someVoidMethod();
     * 
*

* See examples in javadoc for {@link Mockito} class * * @return stubber - to select a method for stubbing */ public static PowerMockitoStubber doCallRealMethod() { return POWERMOCKITO_CORE.doCallRealMethod(); } /** * Use doNothing() for setting void methods to do nothing. Beware that * void methods on mocks do nothing by default! However, there are rare * situations when doNothing() comes handy: *

* 1. Stubbing consecutive calls on a void method: *

*

     * doNothing().doThrow(new RuntimeException()).when(mock).someVoidMethod();
     *
     * //does nothing the first time:
     * mock.someVoidMethod();
     *
     * //throws RuntimeException the next time:
     * mock.someVoidMethod();
     * 
*

* 2. When you spy real objects and you want the void method to do nothing: *

*

     * List list = new LinkedList();
     * List spy = spy(list);
     *
     * //let's make clear() do nothing
     * doNothing().when(spy).clear();
     *
     * spy.add("one");
     *
     * //clear() does nothing, so the list still contains "one"
     * spy.clear();
     * 
*

* See examples in javadoc for {@link Mockito} class * * @return stubber - to select a method for stubbing */ public static PowerMockitoStubber doNothing() { return POWERMOCKITO_CORE.doNothing(); } /** * Use doReturn() in those rare occasions when you cannot use * {@link PowerMockito#when(Object)}. *

* Beware that {@link PowerMockito#when(Object)} is always recommended for * stubbing because it is argument type-safe and more readable * (especially when stubbing consecutive calls). *

* Here are those rare occasions when doReturn() comes handy: *

*

* 1. When spying real objects and calling real methods on a spy brings side * effects *

*

     * List list = new LinkedList();
     * List spy = spy(list);
     *
     * //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)
     * when(spy.get(0)).thenReturn("foo");
     *
     * //You have to use doReturn() for stubbing:
     * doReturn("foo").when(spy).get(0);
     * 
*

* 2. Overriding a previous exception-stubbing: *

*

     * when(mock.foo()).thenThrow(new RuntimeException());
     *
     * //Impossible: the exception-stubbed foo() method is called so RuntimeException is thrown.
     * when(mock.foo()).thenReturn("bar");
     *
     * //You have to use doReturn() for stubbing:
     * doReturn("bar").when(mock).foo();
     * 
*

* Above scenarios shows a trade off of Mockito's elegant syntax. Note that * the scenarios are very rare, though. Spying should be sporadic and * overriding exception-stubbing is very rare. *

* See examples in javadoc for {@link Mockito} class * * @param toBeReturned to be returned when the stubbed method is called * @return stubber - to select a method for stubbing */ public static PowerMockitoStubber doReturn(Object toBeReturned) { return POWERMOCKITO_CORE.doReturn(toBeReturned); } /** * Same as {@link #doReturn(Object)} but sets consecutive values to be returned. Remember to use * doReturn() in those rare occasions when you cannot use {@link PowerMockito#when(Object)}. *

* Beware that {@link PowerMockito#when(Object)} is always recommended for stubbing because it is argument type-safe * and more readable (especially when stubbing consecutive calls). *

* Here are those rare occasions when doReturn() comes handy: *

*

*

    *
  1. When spying real objects and calling real methods on a spy brings side effects *

    *

    
         * List list = new LinkedList();
         * List spy = spy(list);
         * 

    * //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty) * when(spy.get(0)).thenReturn("foo", "bar", "qix"); *

    * //You have to use doReturn() for stubbing: * doReturn("foo", "bar", "qix").when(spy).get(0); *

    *
  2. *

    *

  3. Overriding a previous exception-stubbing: *
    
         * when(mock.foo()).thenThrow(new RuntimeException());
         * 

    * //Impossible: the exception-stubbed foo() method is called so RuntimeException is thrown. * when(mock.foo()).thenReturn("bar", "foo", "qix"); *

    * //You have to use doReturn() for stubbing: * doReturn("bar", "foo", "qix").when(mock).foo(); *

    *
  4. *
*

* Above scenarios shows a trade-off of Mockito's elegant syntax. Note that the scenarios are very rare, though. * Spying should be sporadic and overriding exception-stubbing is very rare. Not to mention that in general * overriding stubbing is a potential code smell that points out too much stubbing. *

* See examples in javadoc for {@link PowerMockito} class * * @param toBeReturned to be returned when the stubbed method is called * @param othersToBeReturned to be returned in consecutive calls when the stubbed method is called * @return stubber - to select a method for stubbing * @since 1.6.5 */ public static PowerMockitoStubber doReturn(Object toBeReturned, Object... othersToBeReturned) { return POWERMOCKITO_CORE.doAnswer(toBeReturned, othersToBeReturned); } } ================================================ FILE: powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/expectation/ConstructorAwareExpectationSetup.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.api.mockito.expectation; import org.mockito.stubbing.OngoingStubbing; import java.lang.reflect.Constructor; public class ConstructorAwareExpectationSetup implements WithOrWithoutExpectedArguments { private final Constructor ctor; private final DefaultConstructorExpectationSetup expectationSetup; public ConstructorAwareExpectationSetup(Constructor ctor) { if (ctor == null) { throw new IllegalArgumentException("Constructor to expect cannot be null"); } this.ctor = ctor; this.expectationSetup = setupExpectation(); } @Override public OngoingStubbing withArguments(Object firstArgument, Object... additionalArguments) throws Exception { return expectationSetup.withArguments(firstArgument, additionalArguments); } @Override public OngoingStubbing withNoArguments() throws Exception { return expectationSetup.withNoArguments(); } private DefaultConstructorExpectationSetup setupExpectation() { DefaultConstructorExpectationSetup setup = new DefaultConstructorExpectationSetup(ctor.getDeclaringClass()); setup.setParameterTypes(ctor.getParameterTypes()); return setup; } } ================================================ FILE: powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/expectation/ConstructorExpectationSetup.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.api.mockito.expectation; public interface ConstructorExpectationSetup extends WithOrWithoutExpectedArguments, WithExpectedParameterTypes, WithAnyArguments { } ================================================ FILE: powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/expectation/DefaultConstructorExpectationSetup.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.api.mockito.expectation; import org.mockito.ArgumentMatchers; import org.mockito.stubbing.OngoingStubbing; import org.powermock.api.mockito.internal.expectation.DelegatingToConstructorsOngoingStubbing; import org.powermock.api.mockito.internal.invocation.MockitoNewInvocationControl; import org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator; import org.powermock.core.MockRepository; import org.powermock.core.spi.NewInvocationControl; import org.powermock.core.spi.support.InvocationSubstitute; import org.powermock.reflect.internal.WhiteboxImpl; import org.powermock.tests.utils.ArrayMerger; import org.powermock.tests.utils.impl.ArrayMergerImpl; import java.lang.reflect.Constructor; import java.lang.reflect.Method; public class DefaultConstructorExpectationSetup implements ConstructorExpectationSetup { private final Class mockType; private final ArrayMerger arrayMerger; private final DefaultMockCreator mockCreator; private Class[] parameterTypes = null; private final InvocationSubstitute mock; public DefaultConstructorExpectationSetup(Class mockType) { this.arrayMerger = new ArrayMergerImpl(); this.mockType = mockType; this.mockCreator = new DefaultMockCreator(); this.mock = getMockCreator().createMock(InvocationSubstitute.class, false, false, null, null, (Method[]) null); } @Override public OngoingStubbing withArguments(Object firstArgument, Object... additionalArguments) throws Exception { return createNewSubstituteMock(mockType, parameterTypes, arrayMerger.mergeArrays(Object.class, new Object[]{firstArgument}, additionalArguments)); } @SuppressWarnings({"unchecked", "rawtypes"}) private OngoingStubbing createNewSubstituteMock(Class type, Class[] parameterTypes, Object... arguments) throws Exception { if (type == null) { throw new IllegalArgumentException("type cannot be null"); } final Class unmockedType = (Class) WhiteboxImpl.getOriginalUnmockedType(type); if (parameterTypes == null) { WhiteboxImpl.findUniqueConstructorOrThrowException(type, arguments); } else { WhiteboxImpl.getConstructor(unmockedType, parameterTypes); } NewInvocationControl> newInvocationControl = createNewInvocationControl(type, unmockedType); return newInvocationControl.expectSubstitutionLogic(arguments); } private NewInvocationControl> createNewInvocationControl(final Class type, final Class unmockedType) { /* * Check if this type has been mocked before */ NewInvocationControl> newInvocationControl = (NewInvocationControl>) MockRepository.getNewInstanceControl(unmockedType); if (newInvocationControl == null) { newInvocationControl = createNewInvocationControl(mock); MockRepository.putNewInstanceControl(type, newInvocationControl); MockRepository.addObjectsToAutomaticallyReplayAndVerify(WhiteboxImpl.getOriginalUnmockedType(type)); } return newInvocationControl; } @Override public OngoingStubbing withAnyArguments() throws Exception { if (mockType == null) { throw new IllegalArgumentException("Class to expected cannot be null"); } final Class unmockedType = (Class) WhiteboxImpl.getOriginalUnmockedType(mockType); final Constructor[] allConstructors = WhiteboxImpl.getAllConstructors(unmockedType); final Constructor constructor = allConstructors[0]; final Class[] parameterTypes = constructor.getParameterTypes(); Object[] paramArgs = new Object[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { Class paramType = parameterTypes[i]; paramArgs[i] = createParamArgMatcher(paramType); } Constructor[] otherCtors = new Constructor[allConstructors.length - 1]; System.arraycopy(allConstructors, 1, otherCtors, 0, allConstructors.length - 1); final OngoingStubbing ongoingStubbing = createNewSubstituteMock(mockType, parameterTypes, paramArgs); return new DelegatingToConstructorsOngoingStubbing(otherCtors, ongoingStubbing); } private Object createParamArgMatcher(Class paramType) { return ArgumentMatchers.nullable(paramType); } @Override public OngoingStubbing withNoArguments() throws Exception { return createNewSubstituteMock(mockType, parameterTypes); } @Override public WithExpectedArguments withParameterTypes(Class parameterType, Class... additionalParameterTypes) { this.parameterTypes = arrayMerger.mergeArrays(Class.class, new Class[]{parameterType}, additionalParameterTypes); return this; } private DefaultMockCreator getMockCreator() {return mockCreator;} private NewInvocationControl> createNewInvocationControl(InvocationSubstitute mock) { return new MockitoNewInvocationControl(mock); } void setParameterTypes(Class[] parameterTypes) { this.parameterTypes = parameterTypes; } } ================================================ FILE: powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/expectation/PowerMockitoStubber.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.api.mockito.expectation; import org.mockito.Mockito; import org.mockito.stubbing.Answer; import org.mockito.stubbing.Stubber; import java.lang.reflect.Method; /** * Setup stubbing for private or void methods in final class, final void * methods, or static (final) methods. */ public interface PowerMockitoStubber extends Stubber { /** * Allows to choose a static method when stubbing in * doThrow()|doAnswer()|doNothing()|doReturn() style *

* Example: *

*
     * doThrow(new RuntimeException()).when(StaticList.class);
     * StaticList.clear();
     *
     * //following throws RuntimeException:
     * StaticList.clear();
     * 
*

* Read more about those methods: *

*

* {@link Mockito#doThrow(Class)} *

*

* {@link Mockito#doAnswer(Answer)} *

*

* {@link Mockito#doNothing()} *

*

* {@link Mockito#doReturn(Object)} *

* * @param classMock the mock class * @see Mockito */ void when(Class classMock); /** * Allows to mock a private instance method when stubbing in * doThrow()|doAnswer()|doNothing()|doReturn() style. *

* Example: *

     * doThrow(new RuntimeException()).when(instance, method("myMethod")).withNoArguments();
     * 
*

*

* Read more about those methods: *

*

* {@link Mockito#doThrow(Class)} *

*

* {@link Mockito#doAnswer(Answer)} *

*

* {@link Mockito#doNothing()} *

*

* {@link Mockito#doReturn(Object)} *

* * @param mock the method * @param method private method to be mocked * @see Mockito */ PrivatelyExpectedArguments when(T mock, Method method) throws Exception; /** * Allows to mock a private instance method based on the parameters when * stubbing in doThrow()|doAnswer()|doNothing()|doReturn() style. *

* Example: *

*

*

     * doThrow(new RuntimeException()).when(instance, parameter1, parameter2);
     * 
*

*

* Read more about those methods: *

*

* {@link Mockito#doThrow(Throwable...)} *

*

* {@link Mockito#doAnswer(Answer)} *

*

* {@link Mockito#doNothing()} *

*

* {@link Mockito#doReturn(Object)} *

* * @param mock the Mock * @param arguments array of arguments is used to find suitable method to be mocked. * @see Mockito */ void when(T mock, Object... arguments) throws Exception; /** * Allows to mock a private instance method based on method name and * parameters when stubbing in doThrow()|doAnswer()|doNothing()|doReturn() * style. *

* Example: *

*
     * doThrow(new RuntimeException()).when(instance, "methodName", parameter1, parameter2);
     * 
*

*

* Read more about those methods: *

*

* {@link Mockito#doThrow(Throwable...)} *

*

* {@link Mockito#doAnswer(Answer)} *

*

* {@link Mockito#doNothing()} *

*

* {@link Mockito#doReturn(Object)} *

* * @param mock the Mock * @param methodToExpect name of method which have to mocked * @param arguments array of arguments of methodToExpect * @see Mockito */ void when(T mock, String methodToExpect, Object... arguments) throws Exception; /** * Allows to mock a static private method when stubbing in * doThrow()|doAnswer()|doNothing()|doReturn() style. *

* Example: *

     * doThrow(new RuntimeException()).when(MyClass.class, method("myMethod")).withNoArguments();
     * 
*

*

* Read more about those methods: *

*

* {@link Mockito#doThrow(Throwable...)} *

*

* {@link Mockito#doAnswer(Answer)} *

*

* {@link Mockito#doNothing()} *

*

* {@link Mockito#doReturn(Object)} *

* * @param classMock class owner of private static method * @param method private static method to be mocked * @see Mockito */ PrivatelyExpectedArguments when(Class classMock, Method method) throws Exception; /** * Allows to mock a static private method based on the parameters when * stubbing in doThrow()|doAnswer()|doNothing()|doReturn() style. *

* Example: *

     * doThrow(new RuntimeException()).when(MyClass.class, parameter1, parameter2);
     * 
*

*

* Read more about those methods: *

*

* {@link Mockito#doThrow(Throwable...)} *

*

* {@link Mockito#doAnswer(Answer)} *

*

* {@link Mockito#doNothing()} *

*

* {@link Mockito#doReturn(Object)} *

* * @param classMock class owner of private static method * @param arguments array of arguments is used to find suitable method to be mocked. * @see Mockito */ void when(Class classMock, Object... arguments) throws Exception; /** * Allows to mock a static private method based on method name and * parameters when stubbing in doThrow()|doAnswer()|doNothing()|doReturn() * style. *

* Example: *

     * doThrow(new RuntimeException()).when(MyClass.class, "methodName", parameter1, parameter2);
     * 
*

*

* Read more about those methods: *

*

* {@link Mockito#doThrow(Throwable...)} *

*

* {@link Mockito#doAnswer(Answer)} *

*

* {@link Mockito#doNothing()} *

*

* {@link Mockito#doReturn(Object)} *

* * @param classMock the class owner of static private method * @param methodToExpect name of method which have to mocked * @param arguments array of arguments of methodToExpect * @see Mockito */ void when(Class classMock, String methodToExpect, Object... arguments) throws Exception; } ================================================ FILE: powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/expectation/PrivatelyExpectedArguments.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */package org.powermock.api.mockito.expectation; public interface PrivatelyExpectedArguments { void withArguments(Object firstArgument, Object... additionalArguments) throws Exception; void withNoArguments() throws Exception; } ================================================ FILE: powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/expectation/WithAnyArguments.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.api.mockito.expectation; import org.mockito.stubbing.OngoingStubbing; public interface WithAnyArguments { OngoingStubbing withAnyArguments() throws Exception; } ================================================ FILE: powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/expectation/WithExpectedArguments.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.api.mockito.expectation; import org.mockito.stubbing.OngoingStubbing; public interface WithExpectedArguments { OngoingStubbing withArguments(Object firstArgument, Object... additionalArguments) throws Exception; } ================================================ FILE: powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/expectation/WithExpectedParameterTypes.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.api.mockito.expectation; public interface WithExpectedParameterTypes { WithExpectedArguments withParameterTypes(Class parameterType, Class... additionalParameterTypes); } ================================================ FILE: powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/expectation/WithOrWithoutExpectedArguments.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.api.mockito.expectation; public interface WithOrWithoutExpectedArguments extends WithExpectedArguments, WithoutExpectedArguments { } ================================================ FILE: powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/expectation/WithoutExpectedArguments.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.api.mockito.expectation; import org.mockito.stubbing.OngoingStubbing; public interface WithoutExpectedArguments { OngoingStubbing withNoArguments() throws Exception; } ================================================ FILE: powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/expectation/reporter/MockitoPowerMockReporter.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.api.mockito.expectation.reporter; import org.powermock.api.mockito.ClassNotPreparedException; import org.powermock.core.reporter.PowerMockReporter; import static org.powermock.utils.StringJoiner.join; public class MockitoPowerMockReporter implements PowerMockReporter { @Override public void classNotPrepared(Class type) { throw new ClassNotPreparedException(join(String.format("The class %s not prepared for test.", type.getName()), "To prepare this class, add class to the '@PrepareForTest' annotation.", "In case if you don't use this annotation, add the annotation on class or method level. ")); } } ================================================ FILE: powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/PowerMockitoCore.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.api.mockito.internal; import org.mockito.MockSettings; import org.mockito.Mockito; import org.mockito.stubbing.Answer; import org.mockito.stubbing.Stubber; import org.mockito.verification.VerificationMode; import org.powermock.api.mockito.expectation.PowerMockitoStubber; import org.powermock.api.mockito.internal.expectation.PowerMockitoStubberImpl; import org.powermock.api.mockito.internal.invocation.MockitoNewInvocationControl; import org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator; import org.powermock.api.mockito.internal.stubbing.PowerMockCallRealMethod; import org.powermock.api.mockito.internal.verification.DefaultConstructorArgumentsVerification; import org.powermock.core.MockRepository; import org.powermock.core.classloader.ClassloaderWrapper; import org.powermock.core.spi.NewInvocationControl; import org.powermock.reflect.Whitebox; import java.lang.reflect.Method; import java.util.concurrent.Callable; import static org.powermock.utils.Asserts.assertNotNull; public class PowerMockitoCore { private static final PowerMockCallRealMethod POWER_MOCK_CALL_REAL_METHOD = new PowerMockCallRealMethod(); 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."; public PowerMockitoStubber doAnswer(final Answer answer) { return doAnswer(new Callable() { @Override public Stubber call() throws Exception { return Mockito.doAnswer(answer); } }); } public PowerMockitoStubber doThrow(final Throwable toBeThrown) { return doAnswer(new Callable() { @Override public Stubber call() throws Exception { return Mockito.doThrow(toBeThrown); } }); } public PowerMockitoStubber doCallRealMethod() { return doAnswer(new Callable() { @Override public Stubber call() throws Exception { return Mockito.doCallRealMethod(); } }); } public PowerMockitoStubber doNothing() { return doAnswer(new Callable() { @Override public Stubber call() throws Exception { return Mockito.doNothing(); } }); } public PowerMockitoStubber doReturn(final Object toBeReturned) { return doAnswer(new Callable() { @Override public Stubber call() throws Exception { return Mockito.doReturn(toBeReturned); } }); } public PowerMockitoStubber doAnswer(final Object toBeReturned, final Object... othersToBeReturned) { return doAnswer(new Callable() { @Override public Stubber call() throws Exception { return Mockito.doReturn(toBeReturned, othersToBeReturned); } }); } public DefaultConstructorArgumentsVerification verifyNew(final Class mock, final VerificationMode mode) { assertNotNull(mock, "Class to verify cannot be null"); assertNotNull(mode, "Verify mode cannot be null"); @SuppressWarnings("unchecked") MockitoNewInvocationControl invocationControl = (MockitoNewInvocationControl) MockRepository.getNewInstanceControl(mock); assertNotNull(invocationControl, String.format(NO_OBJECT_CREATION_ERROR_MESSAGE_TEMPLATE, Whitebox.getType(mock).getName())); invocationControl.verify(mode); //noinspection unchecked return new DefaultConstructorArgumentsVerification((NewInvocationControl) invocationControl, mock); } public T spy(final T object) { MockSettings mockSettings = Mockito.withSettings() .spiedInstance(object) .defaultAnswer(POWER_MOCK_CALL_REAL_METHOD); //noinspection unchecked return DefaultMockCreator.mock((Class) Whitebox.getType(object), false, true, object, mockSettings, (Method[]) null); } private PowerMockitoStubber doAnswer(final Callable callable) { final Stubber stubber = ClassloaderWrapper.runWithClass(callable); return new PowerMockitoStubberImpl(stubber); } } ================================================ FILE: powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/configuration/PowerMockitoInjectingAnnotationEngine.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.api.mockito.internal.configuration; import org.mockito.Mock; import org.mockito.internal.MockitoCore; import org.mockito.internal.configuration.InjectingAnnotationEngine; import org.mockito.internal.configuration.plugins.Plugins; import org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator; /** * The same as {@link InjectingAnnotationEngine} with the exception that it * doesn't create/injects mocks annotated with the standard annotations such as * {@link Mock}. */ public class PowerMockitoInjectingAnnotationEngine extends InjectingAnnotationEngine { @SuppressWarnings("deprecation") @Override public AutoCloseable process(Class context, Object testClass) { // this will create @Spies: new PowerMockitoSpyAnnotationEngine().process(context, testClass); preLoadPluginLoader(); // this injects mocks injectMocks(testClass); return null; } private void preLoadPluginLoader() { final ClassLoader originalCL = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(DefaultMockCreator.class.getClassLoader()); try { MockitoCore mc = new MockitoCore(); Plugins.getMockMaker(); } finally { Thread.currentThread().setContextClassLoader(originalCL); } } } ================================================ FILE: powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/configuration/PowerMockitoSpyAnnotationEngine.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.api.mockito.internal.configuration; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.exceptions.base.MockitoException; import org.mockito.internal.configuration.SpyAnnotationEngine; import org.powermock.api.mockito.PowerMockito; import org.powermock.reflect.Whitebox; import java.lang.reflect.Field; /** * More or less a copy of the {@link SpyAnnotationEngine} but it uses * {@link PowerMockito#spy(Object)} instead. */ public class PowerMockitoSpyAnnotationEngine extends SpyAnnotationEngine { @SuppressWarnings("deprecation") @Override public AutoCloseable process(Class context, Object testClass) { Field[] fields = context.getDeclaredFields(); for (Field field : fields) { if (field.isAnnotationPresent(Spy.class)) { try { Whitebox.invokeMethod(this, Spy.class, field, new Class[] { Mock.class, org.mockito.Mock.class, Captor.class }); } catch (RuntimeException e) { throw e; } catch (Exception e1) { throw new RuntimeException(e1); } boolean wasAccessible = field.isAccessible(); field.setAccessible(true); try { Object instance = field.get(testClass); if (instance == null) { throw new MockitoException("Cannot create a @Spy for '" + field.getName() + "' field because the *instance* is missing\n" + "Example of correct usage of @Spy:\n" + " @Spy List mock = new LinkedList();\n"); } field.set(testClass, PowerMockito.spy(instance)); } catch (IllegalAccessException e) { throw new MockitoException("Problems initiating spied field " + field.getName(), e); } finally { field.setAccessible(wasAccessible); } } } return null; } } ================================================ FILE: powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/exceptions/StackTraceCleanerProvider.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.api.mockito.internal.exceptions; import org.mockito.exceptions.stacktrace.StackTraceCleaner; public class StackTraceCleanerProvider implements org.mockito.plugins.StackTraceCleanerProvider { @Override public StackTraceCleaner getStackTraceCleaner(final StackTraceCleaner defaultCleaner) { return new StackTraceCleaner() { @Override public boolean isIn(StackTraceElement candidate) { return defaultCleaner.isIn(candidate) && !candidate.getClassName().startsWith("org.powermock.") && !candidate.getClassName().startsWith("sun.reflect.") && !candidate.getClassName().startsWith("java.lang.reflect.") && !candidate.getClassName().startsWith("jdk.internal.reflect.") && candidate.getLineNumber() != -1; } }; } } ================================================ FILE: powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/expectation/DefaultMethodExpectationSetup.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.api.mockito.internal.expectation; import org.mockito.Mockito; import org.mockito.stubbing.OngoingStubbing; import org.powermock.api.mockito.expectation.WithOrWithoutExpectedArguments; import java.lang.reflect.Method; public class DefaultMethodExpectationSetup implements WithOrWithoutExpectedArguments { private final Object object; private final Method method; public DefaultMethodExpectationSetup(Object object, Method method) { if (object == null) { throw new IllegalArgumentException("object to expect cannot be null"); } else if (method == null) { throw new IllegalArgumentException("method to expect cannot be null"); } this.object = object; this.method = method; this.method.setAccessible(true); } private static Object[] join(Object o, Object[] array) { Object[] res = new Object[array.length + 1]; res[0] = o; System.arraycopy(array, 0, res, 1, array.length); return res; } @SuppressWarnings("unchecked") @Override public OngoingStubbing withArguments(Object firstArgument, Object... additionalArguments) throws Exception { if (additionalArguments == null || additionalArguments.length == 0) { return (OngoingStubbing) Mockito.when(method.invoke(object, firstArgument)); } else { return (OngoingStubbing) Mockito.when(method.invoke(object, join(firstArgument, additionalArguments))); } } @SuppressWarnings("unchecked") @Override public OngoingStubbing withNoArguments() throws Exception { return (OngoingStubbing) Mockito.when(method.invoke(object)); } } ================================================ FILE: powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/expectation/DefaultPrivatelyExpectedArguments.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.api.mockito.internal.expectation; import org.powermock.api.mockito.expectation.PrivatelyExpectedArguments; import java.lang.reflect.Method; public class DefaultPrivatelyExpectedArguments implements PrivatelyExpectedArguments { private final Method method; private final Object mock; public DefaultPrivatelyExpectedArguments(Object mock, Method method) { this.mock = mock; this.method = method; method.setAccessible(true); } @Override public void withArguments(Object firstArgument, Object... additionalArguments) throws Exception { if (additionalArguments == null || additionalArguments.length == 0) { method.invoke(mock, firstArgument); } else { Object[] allArgs = new Object[additionalArguments.length + 1]; allArgs[0] = firstArgument; if (additionalArguments.length > 0) { System.arraycopy(additionalArguments, 0, allArgs, 1, additionalArguments.length); } method.invoke(mock, allArgs); } } @Override public void withNoArguments() throws Exception { method.invoke(mock); } } ================================================ FILE: powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/expectation/DelegatingToConstructorsOngoingStubbing.java ================================================ /* * Copyright 2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.api.mockito.internal.expectation; import org.mockito.ArgumentMatchers; import org.mockito.stubbing.Answer; import org.mockito.stubbing.OngoingStubbing; import org.powermock.core.spi.support.InvocationSubstitute; import java.lang.reflect.Constructor; import static org.mockito.Mockito.when; /** * Implementation of OngoingStubbing that delegates invocations to all supplied ctors * @param */ public class DelegatingToConstructorsOngoingStubbing implements OngoingStubbing{ private final OngoingStubbing stubbing; private final Constructor[] ctors; public DelegatingToConstructorsOngoingStubbing(Constructor[] ctors, OngoingStubbing stubbing) { if(stubbing == null) { throw new IllegalArgumentException("Internal error: Ongoing stubbing must be provided"); } this.ctors = ctors; this.stubbing = stubbing; } @Override public OngoingStubbing thenReturn(final T value) { stubbing.thenReturn(value); return new InvokeStubMethod() { @Override public void performStubbing(OngoingStubbing when) { when.thenReturn(value); } }.invoke(); } @Override public OngoingStubbing thenReturn(final T value, final T... values) { stubbing.thenReturn(value, values); return new InvokeStubMethod() { @Override public void performStubbing(OngoingStubbing when) { when.thenReturn(value, values); } }.invoke(); } @Override public OngoingStubbing thenThrow(final Throwable... throwables) { stubbing.thenThrow(throwables); return new InvokeStubMethod() { @Override public void performStubbing(OngoingStubbing when) { when.thenThrow(throwables); } }.invoke(); } @Override public OngoingStubbing thenThrow(final Class throwableType) { stubbing.thenThrow(throwableType); return new InvokeStubMethod() { @Override public void performStubbing(OngoingStubbing when) { when.thenThrow(throwableType); } }.invoke(); } @Override public OngoingStubbing thenThrow(final Class toBeThrown, final Class[] nextToBeThrown) { stubbing.thenThrow(toBeThrown, nextToBeThrown); return new InvokeStubMethod() { @Override public void performStubbing(OngoingStubbing when) { when.thenThrow(toBeThrown, nextToBeThrown); } }.invoke(); } @Override public OngoingStubbing thenCallRealMethod() { stubbing.thenCallRealMethod(); return new InvokeStubMethod() { @Override public void performStubbing(OngoingStubbing when) { when.thenCallRealMethod(); } }.invoke(); } @Override public OngoingStubbing thenAnswer(final Answer answer) { stubbing.thenAnswer(answer); return new InvokeStubMethod() { @Override public void performStubbing(OngoingStubbing when) { when.thenAnswer(answer); } }.invoke(); } @Override public OngoingStubbing then(final Answer answer) { stubbing.then(answer); return new InvokeStubMethod() { @Override public void performStubbing(OngoingStubbing when) { when.then(answer); } }.invoke(); } @Override public M getMock() { return stubbing.getMock(); } private abstract class InvokeStubMethod { public OngoingStubbing invoke() { final InvocationSubstitute mock = stubbing.getMock(); for (Constructor constructor : ctors) { final Class[] parameterTypesForCtor = constructor.getParameterTypes(); Object[] paramArgs = new Object[parameterTypesForCtor.length]; for (int i = 0; i < parameterTypesForCtor.length; i++) { Class paramType = parameterTypesForCtor[i]; paramArgs[i] = ArgumentMatchers.nullable(paramType); } try { final OngoingStubbing when = when(mock.performSubstitutionLogic(paramArgs)); performStubbing(when); } catch (Exception e) { throw new RuntimeException("PowerMock internal error",e); } } return stubbing; } public abstract void performStubbing(OngoingStubbing when); } } ================================================ FILE: powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/expectation/PowerMockitoStubberImpl.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.api.mockito.internal.expectation; import org.mockito.stubbing.Answer; import org.mockito.stubbing.Stubber; import org.powermock.api.mockito.expectation.PowerMockitoStubber; import org.powermock.api.mockito.expectation.PrivatelyExpectedArguments; import org.powermock.api.mockito.invocation.MockitoMethodInvocationControl; import org.powermock.core.MockRepository; import org.powermock.reflect.Whitebox; import java.lang.reflect.Method; /** * Extension of the standard Mocktio stubber implementation that also support * PowerMockito created mocks. */ public class PowerMockitoStubberImpl implements PowerMockitoStubber, Stubber { private final Stubber stubber; public PowerMockitoStubberImpl(final Stubber stubber) {this.stubber = stubber;} @Override public T when(final T instanceMock) { final MockitoMethodInvocationControl invocationControl = (MockitoMethodInvocationControl) MockRepository.getInstanceMethodInvocationControl(instanceMock); final T returnValue; if (invocationControl == null) { returnValue = stubber.when(instanceMock); } else { final Object mock = invocationControl.getMockHandlerAdaptor().getMock(); stubber.when(mock); returnValue = instanceMock; } return returnValue; } @Override public Stubber doThrow(final Throwable... toBeThrown) {return stubber.doThrow(toBeThrown);} @Override public Stubber doThrow(final Class toBeThrown) {return stubber.doThrow(toBeThrown);} @Override public Stubber doThrow(final Class toBeThrown, final Class[] nextToBeThrown) {return stubber.doThrow(toBeThrown, nextToBeThrown);} @Override public Stubber doAnswer(final Answer answer) {return stubber.doAnswer(answer);} @Override public Stubber doNothing() {return stubber.doNothing();} @Override public Stubber doReturn(final Object toBeReturned) {return stubber.doReturn(toBeReturned);} @Override public Stubber doReturn(final Object toBeReturned, final Object... nextToBeReturned) {return stubber.doReturn(toBeReturned, nextToBeReturned);} @Override public Stubber doCallRealMethod() {return stubber.doCallRealMethod();} @Override public void when(Class classMock) { MockitoMethodInvocationControl invocationControl = (MockitoMethodInvocationControl) MockRepository.getStaticMethodInvocationControl(classMock); final Object mock = invocationControl.getMockHandlerAdaptor().getMock(); stubber.when(mock); } @Override public PrivatelyExpectedArguments when(T mock, Method method) throws Exception { assertNotNull(mock, "mock"); assertNotNull(method, "Method"); this.when(mock); return new DefaultPrivatelyExpectedArguments(mock, method); } @Override public void when(T mock, Object... arguments) throws Exception { assertNotNull(mock, "mock"); this.when(mock); Whitebox.invokeMethod(mock, arguments); } @Override public void when(T mock, String methodToExpect, Object... arguments) throws Exception { assertNotNull(mock, "mock"); assertNotNull(methodToExpect, "methodToExpect"); this.when(mock); Whitebox.invokeMethod(mock, methodToExpect, arguments); } @Override public void when(Class classMock, Object... arguments) throws Exception { assertNotNull(classMock, "classMock"); when(classMock); Whitebox.invokeMethod(classMock, arguments); } @Override public void when(Class classMock, String methodToExpect, Object... parameters) throws Exception { assertNotNull(classMock, "classMock"); assertNotNull(methodToExpect, "methodToExpect"); when(classMock); Whitebox.invokeMethod(classMock, methodToExpect, parameters); } @Override public PrivatelyExpectedArguments when(Class classMock, Method method) throws Exception { assertNotNull(classMock, "classMock"); assertNotNull(method, "Method"); when(classMock); return new DefaultPrivatelyExpectedArguments(classMock, method); } private void assertNotNull(Object object, String name) { if (object == null) { throw new IllegalArgumentException(name + " cannot be null"); } } } ================================================ FILE: powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/invocation/InvocationControlAssertionError.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.api.mockito.internal.invocation; import org.powermock.core.spi.support.InvocationSubstitute; import org.powermock.reflect.Whitebox; import java.util.regex.Matcher; public class InvocationControlAssertionError { private static final String AT = "at"; private static final String ERROR_LOCATION_MARKER = "->"; private static final String COLON_NEWLINE = ":\n"; private static final String NEWLINE_POINT = "\n."; private static final String HERE_TEXT = "here:\n"; private static final String UNDESIRED_INVOCATION_TEXT = " Undesired invocation:"; private static final String POWER_MOCKITO_CLASS_NAME = "org.powermock.api.mockito.PowerMockito"; public static void updateErrorMessageForVerifyNoMoreInteractions(AssertionError errorToUpdate) { /* * VerifyNoMoreInteractions failed, we need to update the error message. */ String verifyNoMoreInteractionsInvocation = null; StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); for (int i = stackTrace.length - 1; i >= 0; i--) { final StackTraceElement stackTraceElement = stackTrace[i]; if (stackTraceElement.getClassName().equals(POWER_MOCKITO_CLASS_NAME) && stackTraceElement.getMethodName().equals("verifyNoMoreInteractions")) { final int invocationStackTraceIndex; if (stackTrace[i + 1].getClassName().equals(POWER_MOCKITO_CLASS_NAME) && stackTrace[i + 1].getMethodName().equals("verifyZeroInteractions")) { invocationStackTraceIndex = i + 2; } else { invocationStackTraceIndex = i + 1; } verifyNoMoreInteractionsInvocation = stackTrace[invocationStackTraceIndex].toString(); } } if (verifyNoMoreInteractionsInvocation == null) { // Something unexpected happened, just return return; } String message = errorToUpdate.getMessage(); StringBuilder builder = new StringBuilder(); builder.append(message); final int indexOfFirstAt = message.indexOf(AT); final int startOfVerifyNoMoreInteractionsInvocation = indexOfFirstAt + AT.length() + 1; final int endOfVerifyNoMoreInteractionsInvocation = message.indexOf('\n', indexOfFirstAt + AT.length()); builder.replace(startOfVerifyNoMoreInteractionsInvocation, endOfVerifyNoMoreInteractionsInvocation, verifyNoMoreInteractionsInvocation); builder.delete(builder.indexOf("\n", endOfVerifyNoMoreInteractionsInvocation + 1), builder.lastIndexOf("\n")); Whitebox.setInternalState(errorToUpdate, "detailMessage", builder.toString()); } public static void updateErrorMessageForMethodInvocation(AssertionError errorToUpdate) { /* * We failed to verify the new substitution mock. This happens when, for * example, the user has done something like * whenNew(MyClass.class).thenReturn(myMock).times(3) when in fact an * instance of MyClass has been created less or more times than 3. */ Whitebox.setInternalState(errorToUpdate, "detailMessage", "\n" + changeMessageContent(errorToUpdate.getMessage())); } public static void throwAssertionErrorForNewSubstitutionFailure(AssertionError oldError, Class type) { /* * We failed to verify the new substitution mock. This happens when, for * example, the user has done something like * whenNew(MyClass.class).thenReturn(myMock).times(3) when in fact an * instance of MyClass has been created less or more times than 3. */ final String newSubsitutionClassName = InvocationSubstitute.class.getSimpleName(); final String newSubsitutionClassNameInMockito = newSubsitutionClassName.substring(0, 1).toLowerCase() + newSubsitutionClassName.substring(1); String message = oldError.getMessage(); final String newSubsitutionMethodName = InvocationSubstitute.class.getDeclaredMethods()[0].getName(); message = message.replaceAll(newSubsitutionClassNameInMockito + "." + newSubsitutionMethodName, Matcher .quoteReplacement(type.getName())); message = message.replaceAll("method", "constructor"); throw new AssertionError(changeMessageContent(message)); } private static String changeMessageContent(String message) { /* * Temp fix: Remove powermock internal "at locations" (points to which * line the expectation went wrong in Mockito). We should try to find * the real ones instead */ StringBuilder builder = removeFailureLocations(message); // Remove "Undesired invocation:" removeText(builder, UNDESIRED_INVOCATION_TEXT); removeAndReplaceText(builder, HERE_TEXT, ' '); removeAndReplaceText(builder, COLON_NEWLINE, ' '); return builder.toString().trim(); } private static StringBuilder removeFailureLocations(String message) { StringBuilder builder = new StringBuilder(); builder.append(message); int indexOfBeginLocation = builder.indexOf(ERROR_LOCATION_MARKER); while (indexOfBeginLocation > 0) { int indexOfLocationEnd = builder.indexOf("\n", indexOfBeginLocation); builder.delete(indexOfBeginLocation, indexOfLocationEnd < 0 ? builder.length() : indexOfLocationEnd + 1); indexOfBeginLocation = builder.indexOf(ERROR_LOCATION_MARKER); } return builder; } private static void removeAndReplaceText(StringBuilder builder, String text, char appender) { int currentTextIndex = builder.indexOf(text); int previousTextIndex; boolean isSingleConcat = true; while (currentTextIndex > 0) { previousTextIndex = currentTextIndex; builder.delete(currentTextIndex, currentTextIndex + text.length()); currentTextIndex = builder.indexOf(text); final int length = builder.length(); if (isLastFinding(currentTextIndex) && !isSingleConcat) { final int start = builder.charAt(length - 1) == '\n' ? length - 1 : length; builder.replace(start, length, "."); } else { final int end = previousTextIndex < length ? previousTextIndex + 1 : length; builder.replace( previousTextIndex, end, String.valueOf(builder.charAt(previousTextIndex)).toLowerCase() ); builder.insert(previousTextIndex, String.valueOf(appender)); currentTextIndex++; isSingleConcat = false; } } } private static boolean isLastFinding(int index) { return index < 0; } private static void removeText(StringBuilder builder, String text) { int textIndex = builder.indexOf(text); while (textIndex > 0) { builder.delete(textIndex, textIndex + text.length()); textIndex = builder.indexOf(text); } } } ================================================ FILE: powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/invocation/MockitoNewInvocationControl.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.api.mockito.internal.invocation; import org.mockito.Mockito; import org.mockito.exceptions.base.MockitoAssertionError; import org.mockito.stubbing.OngoingStubbing; import org.mockito.verification.VerificationMode; import org.powermock.core.spi.NewInvocationControl; import org.powermock.core.spi.support.InvocationSubstitute; import org.powermock.reflect.internal.WhiteboxImpl; import java.lang.reflect.Array; import java.lang.reflect.Constructor; public class MockitoNewInvocationControl implements NewInvocationControl> { private final InvocationSubstitute substitute; public MockitoNewInvocationControl(InvocationSubstitute substitute) { if (substitute == null) { throw new IllegalArgumentException("Internal error: substitute cannot be null."); } this.substitute = substitute; } @Override public Object invoke(Class type, Object[] args, Class[] sig) throws Exception { Constructor constructor = WhiteboxImpl.getConstructor(type, sig); if (constructor.isVarArgs()) { Object varArgs = args[args.length - 1]; final int varArgsLength = Array.getLength(varArgs); Object[] oldArgs = args; args = new Object[args.length + varArgsLength - 1]; System.arraycopy(oldArgs, 0, args, 0, oldArgs.length - 1); for (int i = oldArgs.length - 1, j=0; i < args.length; i++, j++) { args[i] = Array.get(varArgs, j); } } try { return substitute.performSubstitutionLogic(args); } catch (MockitoAssertionError e) { InvocationControlAssertionError.throwAssertionErrorForNewSubstitutionFailure(e, type); } // Won't happen return null; } @Override public OngoingStubbing expectSubstitutionLogic(Object... arguments) throws Exception { return Mockito.when(substitute.performSubstitutionLogic(arguments)); } public InvocationSubstitute getSubstitute() { return substitute; } @Override public synchronized Object replay(Object... mocks) { return null; } public synchronized void verify(final VerificationMode verificationMode) { Mockito.verify(substitute, verificationMode); } @SuppressWarnings("unchecked") @Override public synchronized Object reset(Object... mocks) { Mockito.reset(substitute); return null; } public void verifyNoMoreInteractions() { try { Mockito.verifyNoMoreInteractions(substitute); } catch (MockitoAssertionError e) { InvocationControlAssertionError.updateErrorMessageForVerifyNoMoreInteractions(e); throw e; } } } ================================================ FILE: powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/mockcreation/AbstractMockCreator.java ================================================ package org.powermock.api.mockito.internal.mockcreation; import org.powermock.core.agent.JavaAgentClassRegister; public abstract class AbstractMockCreator implements MockCreator { private JavaAgentClassRegister agentClassRegister; void validateType(Class type, boolean isStatic, boolean isSpy) { createTypeValidator(type, isStatic, isSpy).validate(); } private MockTypeValidator createTypeValidator(Class type, boolean isStatic, boolean isSpy) { return MockTypeValidatorFactory.createValidator(type, isStatic, isSpy, agentClassRegister); } } ================================================ FILE: powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/mockcreation/DefaultMockCreator.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.api.mockito.internal.mockcreation; import org.mockito.MockSettings; import org.mockito.Mockito; import org.powermock.api.mockito.invocation.MockitoMethodInvocationControl; import org.powermock.core.ClassReplicaCreator; import org.powermock.core.DefaultFieldValueGenerator; import org.powermock.core.MockRepository; import org.powermock.core.classloader.MockClassLoader; import org.powermock.reflect.Whitebox; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import static org.powermock.utils.Asserts.assertNotNull; public class DefaultMockCreator extends AbstractMockCreator { private static final DefaultMockCreator MOCK_CREATOR = new DefaultMockCreator(); @SuppressWarnings("unchecked") public static T mock(Class type, boolean isStatic, boolean isSpy, Object delegator, MockSettings mockSettings, Method... methods) { return MOCK_CREATOR.createMock(type, isStatic, isSpy, delegator, mockSettings, methods); } @SuppressWarnings("unchecked") public T createMock(Class type, boolean isStatic, boolean isSpy, Object delegatorCandidate, MockSettings mockSettings, Method... methods) { assertNotNull(type, "The class to mock cannot be null"); validateType(type, isStatic, isSpy); registerAfterMethodRunner(); return doCreateMock(type, isStatic, isSpy, delegatorCandidate, mockSettings, methods); } private T doCreateMock(final Class type, final boolean isStatic, final boolean isSpy, final Object delegatorCandidate, final MockSettings mockSettings, final Method[] methods) { final Class typeToMock = getMockType(type); final Object delegator = isSpy && delegatorCandidate == null ? new Object() : delegatorCandidate; final MockData mockData = createMethodInvocationControl(typeToMock, methods, delegator, mockSettings); T mock = mockData.getMock(); if (isFinalJavaSystemClass(type) && !isStatic) { mock = Whitebox.newInstance(type); DefaultFieldValueGenerator.fillWithDefaultValues(mock); } putMethodInvocationControlToRepository(type, isStatic, mockData, mock); return mock; } private void registerAfterMethodRunner() { MockRepository.addAfterMethodRunner(new Runnable() { @Override public void run() { Mockito.reset(); } }); } private void putMethodInvocationControlToRepository(final Class type, final boolean isStatic, final MockData mockData, final T mock) { if (isStatic) { MockRepository.putStaticMethodInvocationControl(type, mockData.getMethodInvocationControl()); } else { MockRepository.putInstanceMethodInvocationControl(mock, mockData.getMethodInvocationControl()); } } private Class getMockType(final Class type) { final Class typeToMock; if (isFinalJavaSystemClass(type)) { typeToMock = new ClassReplicaCreator().createClassReplica(type); } else { typeToMock = type; } return typeToMock; } private static boolean isFinalJavaSystemClass(Class type) { return type.getName().startsWith("java.") && Modifier.isFinal(type.getModifiers()); } @SuppressWarnings("unchecked") private MockData createMethodInvocationControl(Class type, Method[] methods, Object delegator, MockSettings mockSettings) { final T mock = Mockito.mock(type, mockSettings != null ? mockSettings : Mockito.withSettings()); cacheMockClass(mock.getClass()); return new MockData(new MockitoMethodInvocationControl(delegator, mock, methods), mock); } private void cacheMockClass(final Class mockClass) { ClassLoader classLoader = mockClass.getClassLoader(); if (classLoader instanceof MockClassLoader) { MockClassLoader mcl = (MockClassLoader) classLoader; mcl.cache(mockClass); } } /** * Class that encapsulate a mock and its corresponding invocation control. */ private static class MockData { private final MockitoMethodInvocationControl methodInvocationControl; private final T mock; private MockData(MockitoMethodInvocationControl methodInvocationControl, T mock) { this.methodInvocationControl = methodInvocationControl; this.mock = mock; } private MockitoMethodInvocationControl getMethodInvocationControl() { return methodInvocationControl; } private T getMock() { return mock; } } } ================================================ FILE: powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/mockcreation/MockCreator.java ================================================ package org.powermock.api.mockito.internal.mockcreation; import java.lang.reflect.Method; /** * An implementer of interface is reasonable for creating of an mocked instance of specific type. */ public interface MockCreator { T createMock(Class type, boolean isStatic, boolean isSpy, Object delegator, org.mockito.MockSettings mockSettings, Method... methods); } ================================================ FILE: powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/mockcreation/MockTypeValidator.java ================================================ package org.powermock.api.mockito.internal.mockcreation; /** * */ public interface MockTypeValidator { void validate(); } ================================================ FILE: powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/mockcreation/MockTypeValidatorFactory.java ================================================ package org.powermock.api.mockito.internal.mockcreation; import org.powermock.api.mockito.expectation.reporter.MockitoPowerMockReporter; import org.powermock.core.agent.JavaAgentClassRegister; import org.powermock.core.classloader.PowerMockModified; import org.powermock.core.reporter.PowerMockReporter; /** * */ public class MockTypeValidatorFactory { public static MockTypeValidator createValidator(Class type, boolean isStatic, boolean isSpy, JavaAgentClassRegister agentClassRegister) { if (!isStatic || isSpy || isLoadedByBootstrap(type)) { return new NullMockTypeValidator(); } else if (agentClassRegister == null) { return new DefaultMockTypeValidator(type); } else { return new JavaAgentMockTypeValidator(type, agentClassRegister); } } private static boolean isLoadedByBootstrap(Class type) { return type.getClassLoader() == null; } private static class DefaultMockTypeValidator extends AbstractMockTypeValidator { DefaultMockTypeValidator(Class type) { super(type); } @Override public void validate() { if (!isModifiedByPowerMock()) { reporter.classNotPrepared(type); } } private boolean isModifiedByPowerMock() { return PowerMockModified.class.isAssignableFrom(type); } } private static class JavaAgentMockTypeValidator extends AbstractMockTypeValidator { private final JavaAgentClassRegister agentClassRegister; private JavaAgentMockTypeValidator(Class type, JavaAgentClassRegister agentClassRegister) { super(type); this.agentClassRegister = agentClassRegister; } @Override public void validate() { if (!isModifiedByAgent()) { reporter.classNotPrepared(type); } } private boolean isModifiedByAgent() { return agentClassRegister.isModifiedByAgent(type.getClassLoader(), type.getName()); } } private abstract static class AbstractMockTypeValidator implements MockTypeValidator { final PowerMockReporter reporter; final Class type; private AbstractMockTypeValidator(Class type) { this.type = type; this.reporter = new MockitoPowerMockReporter(); } @Override public abstract void validate(); } private static class NullMockTypeValidator implements MockTypeValidator { @Override public void validate() { // NUll validator validates nothing } } } ================================================ FILE: powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/mockcreation/RuntimeExceptionProxy.java ================================================ package org.powermock.api.mockito.internal.mockcreation; public class RuntimeExceptionProxy extends RuntimeException { public RuntimeExceptionProxy(Throwable t) { super(t); } } ================================================ FILE: powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/stubbing/MockitoRealMethodInvocation.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.api.mockito.internal.stubbing; public class MockitoRealMethodInvocation { private static final ThreadLocal handledByMockito = new ThreadLocal(); private MockitoRealMethodInvocation() { } public static void mockitoInvocationStarted() { handledByMockito.set(true); } public static void mockitoInvocationFinished() { handledByMockito.set(false); } public static boolean isHandledByMockito() { final Boolean handled = handledByMockito.get(); return handled == null ? false : handled; } } ================================================ FILE: powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/stubbing/PowerMockCallRealMethod.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.api.mockito.internal.stubbing; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; public class PowerMockCallRealMethod implements Answer { @Override public Object answer(InvocationOnMock invocation) throws Throwable { MockitoRealMethodInvocation.mockitoInvocationStarted(); try { return Mockito.CALLS_REAL_METHODS.answer(invocation); } finally { MockitoRealMethodInvocation.mockitoInvocationFinished(); } } } ================================================ FILE: powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/verification/DefaultConstructorArgumentsVerification.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.api.mockito.internal.verification; import org.mockito.exceptions.base.MockitoAssertionError; import org.powermock.api.mockito.internal.invocation.InvocationControlAssertionError; import org.powermock.api.mockito.internal.invocation.MockitoNewInvocationControl; import org.powermock.api.mockito.verification.ConstructorArgumentsVerification; import org.powermock.core.spi.NewInvocationControl; public class DefaultConstructorArgumentsVerification implements ConstructorArgumentsVerification { private final MockitoNewInvocationControl invocationControl; private final Class type; @SuppressWarnings("unchecked") public DefaultConstructorArgumentsVerification(NewInvocationControl invocationControl, Class type) { this.type = type; this.invocationControl = (MockitoNewInvocationControl) invocationControl; } @Override public void withArguments(Object argument, Object... arguments) throws Exception { final Object[] realArguments; if (arguments == null) { realArguments = new Object[]{argument, null}; } else { realArguments = new Object[arguments.length + 1]; realArguments[0] = argument; System.arraycopy(arguments, 0, realArguments, 1, arguments.length); } invokeSubstitute(realArguments); } private void invokeSubstitute(Object... arguments) throws Exception { try { invocationControl.getSubstitute().performSubstitutionLogic(arguments); } catch (MockitoAssertionError e) { InvocationControlAssertionError.throwAssertionErrorForNewSubstitutionFailure(e, type); } } @Override public void withNoArguments() throws Exception { invokeSubstitute(); } } ================================================ FILE: powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/verification/DefaultPrivateMethodVerification.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.api.mockito.internal.verification; import org.powermock.api.mockito.verification.PrivateMethodVerification; import org.powermock.api.mockito.verification.WithOrWithoutVerifiedArguments; import org.powermock.reflect.Whitebox; import org.powermock.tests.utils.impl.ArrayMergerImpl; import java.lang.reflect.Method; public class DefaultPrivateMethodVerification implements PrivateMethodVerification { private final Object objectToVerify; public DefaultPrivateMethodVerification(Object objectToVerify) { this.objectToVerify = objectToVerify; } @Override public void invoke(Object... arguments) throws Exception { Whitebox.invokeMethod(objectToVerify, arguments); } @Override public void invoke(String methodToExecute, Object... arguments) throws Exception { Whitebox.invokeMethod(objectToVerify, methodToExecute, (Object[]) arguments); } @Override public WithOrWithoutVerifiedArguments invoke(Method method) throws Exception { return new VerificationArguments(method); } private class VerificationArguments implements WithOrWithoutVerifiedArguments { private final Method method; public VerificationArguments(Method method) { if (method == null) { throw new IllegalArgumentException("method cannot be null"); } this.method = method; this.method.setAccessible(true); } @Override public void withArguments(Object firstArgument, Object... additionalArguments) throws Exception { if (additionalArguments == null || additionalArguments.length == 0) { method.invoke(objectToVerify, firstArgument); } else { Object[] arguments = new ArrayMergerImpl().mergeArrays(Object.class, new Object[]{firstArgument}, additionalArguments); method.invoke(objectToVerify, arguments); } } @Override public void withNoArguments() throws Exception { method.invoke(objectToVerify); } } } ================================================ FILE: powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/verification/VerifyNoMoreInteractions.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.api.mockito.internal.verification; import org.mockito.Mockito; import org.powermock.api.mockito.internal.invocation.MockitoNewInvocationControl; import org.powermock.api.mockito.invocation.MockitoMethodInvocationControl; import org.powermock.core.MockRepository; /** * Verifies no more interactions, delegates to Mockito if PowerMockito doesn't * find a supplied mock. */ public class VerifyNoMoreInteractions { public static void verifyNoMoreInteractions(Object... objects) { for (Object mock : objects) { if (mock instanceof Class) { verifyNoMoreInteractions((Class) mock); } else { MockitoMethodInvocationControl invocationControl = (MockitoMethodInvocationControl) MockRepository .getInstanceMethodInvocationControl(mock); if (invocationControl != null) { invocationControl.verifyNoMoreInteractions(); } else { /* * Delegate to Mockito if we have no handler registered for * this object. */ Mockito.verifyNoMoreInteractions(mock); } } } } private static void verifyNoMoreInteractions(Class... types) { for (Class type : types) { final MockitoMethodInvocationControl invocationHandler = (MockitoMethodInvocationControl) MockRepository .getStaticMethodInvocationControl(type); if (invocationHandler != null) { invocationHandler.verifyNoMoreInteractions(); } MockitoNewInvocationControl newInvocationControl = (MockitoNewInvocationControl) MockRepository.getNewInstanceControl(type); if (newInvocationControl != null) { newInvocationControl.verifyNoMoreInteractions(); } } } } ================================================ FILE: powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/invocation/InvocationFactory.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.api.mockito.invocation; import org.mockito.Mockito; import org.mockito.invocation.Invocation; import org.mockito.invocation.InvocationFactory.RealMethodBehavior; import org.mockito.mock.MockCreationSettings; import org.powermock.api.support.SafeExceptionRethrower; import org.powermock.core.MockGateway; import org.powermock.core.MockRepository; import org.powermock.reflect.Whitebox; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; class InvocationFactory { Invocation createInvocation(final Object mock, final Method method, final MockCreationSettings settings, final Object... arguments) { final RealMethodBehavior realMethod = createRealMethod(mock, method, arguments); return Mockito.framework() .getInvocationFactory() .createInvocation(mock, settings, method, realMethod, arguments); } private RealMethodBehavior createRealMethod(final Object delegator, final Method method, final Object... arguments) { return new RealMethodBehavior() { @Override public Object call() throws Exception { final Class type = Whitebox.getType(delegator); final boolean isFinalSystemClass = type.getName().startsWith("java.") && Modifier.isFinal(type.getModifiers()); if (!isFinalSystemClass) { MockRepository.putAdditionalState(MockGateway.DONT_MOCK_NEXT_CALL, true); } try { return method.invoke(delegator, arguments); } catch (InvocationTargetException e) { SafeExceptionRethrower.safeRethrow(e.getCause()); } return null; } }; } } ================================================ FILE: powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/invocation/MockHandlerAdaptor.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.api.mockito.invocation; import org.mockito.MockingDetails; import org.mockito.Mockito; import org.mockito.exceptions.base.MockitoAssertionError; import org.mockito.exceptions.misusing.NotAMockException; import org.mockito.invocation.Invocation; import org.mockito.invocation.MockHandler; import org.mockito.mock.MockCreationSettings; import org.powermock.api.mockito.internal.invocation.InvocationControlAssertionError; import org.powermock.core.MockRepository; import java.lang.reflect.Method; /** * The class provides a access to method and data of {@link org.mockito.invocation.MockHandler} from the given mock instance. */ public class MockHandlerAdaptor { private final T mock; private final InvocationFactory invocationFactory; private final MockingDetails mockingDetails; MockHandlerAdaptor(final T mock) { this.mock = mock; this.invocationFactory = new InvocationFactory(); this.mockingDetails = Mockito.mockingDetails(mock); } public Object getMock() { return mock; } public MockCreationSettings getMockSettings() { return mockingDetails.getMockCreationSettings(); } private MockHandler getMockHandler() { return mockingDetails.getMockHandler(); } Object performIntercept(final Object mock, final Method method, Object[] arguments) throws Throwable { Invocation invocation = createInvocation(mock, method, arguments); try { return getMockHandler().handle(invocation); } catch (NotAMockException e) { if (invocation.getMock() .getClass() .getName() .startsWith("java.") && MockRepository.getInstanceMethodInvocationControl(invocation.getMock()) != null) { return invocation.callRealMethod(); } else { throw e; } } catch (MockitoAssertionError e) { InvocationControlAssertionError.updateErrorMessageForMethodInvocation(e); throw e; } } private Invocation createInvocation(final Object mock, final Method method, final Object[] arguments) { return invocationFactory.createInvocation(mock, method, getMockHandler().getMockSettings(), arguments); } } ================================================ FILE: powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/invocation/MockitoMethodInvocationControl.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.api.mockito.invocation; import org.mockito.Mockito; import org.mockito.exceptions.base.MockitoAssertionError; import org.powermock.api.mockito.internal.invocation.InvocationControlAssertionError; import org.powermock.api.mockito.internal.stubbing.MockitoRealMethodInvocation; import org.powermock.core.MockGateway; import org.powermock.core.spi.MethodInvocationControl; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.HashSet; import java.util.Set; /** * A Mockito implementation of the {@link MethodInvocationControl} interface. */ public class MockitoMethodInvocationControl implements MethodInvocationControl { private final Set mockedMethods; private final Object delegator; private final MockHandlerAdaptor mockHandlerAdaptor; /** * Creates a new instance with a delegator. This delegator may be * {@code null} (if it is then no calls will be forwarded to this * instance). If a delegator exists (i.e. not null) all non-mocked calls * will be delegated to that instance. * * @param delegator If the user spies on an instance the original instance must be * injected here. * @param mockInstance The actual mock instance. May be {@code null}. Even * though the mock instance may not be used it's needed to keep a * reference to this object otherwise it may be garbage collected * in some situations. For example when mocking static methods we * don't return the mock object and thus it will be garbage * collected (and thus the finalize method will be invoked which * will be caught by the proxy and the test will fail because we * haven't setup expectations for this method) because then that * object has no reference. In order to avoid this we keep a * reference to this instance here. * @param methodsToMock The methods that are mocked for this instance. If * {@code methodsToMock} is null or empty, all methods for * the {@code invocationHandler} are considered to be */ public MockitoMethodInvocationControl(Object delegator, T mockInstance, Method... methodsToMock) { this.mockHandlerAdaptor = new MockHandlerAdaptor(mockInstance); this.mockedMethods = toSet(methodsToMock); this.delegator = delegator; } @Override public boolean isMocked(Method method) { return mockedMethods == null || (mockedMethods.contains(method)); } @Override public Object invoke(final Object mock, final Method method, final Object[] arguments) throws Throwable { /* * If we come here and it means that the class has been modified by * PowerMock. If this handler has a delegator (i.e. is in spy mode in * the current implementation) and it has been caught by the Mockito * proxy before our MockGateway we need to know if the method is private * or not. Because if the previously described preconditions are met and * the method is not private it means that Mockito has already processed * the method invocation and we should NOT delegate the call to Mockito * again (thus we return proceed). If we would do that Mockito will * receive multiple method invocations to proxy for each method * invocation. For privately spied methods Mockito haven't received the * invocation and thus we should delegate the call to the Mockito proxy. */ final Object returnValue; if (isCanBeHandledByMockito(method) && hasBeenCaughtByMockitoProxy()) { returnValue = MockGateway.PROCEED; } else { if (mock instanceof Class) { returnValue = mockHandlerAdaptor.performIntercept(mockHandlerAdaptor.getMockSettings().getTypeToMock(), method, arguments); } else { returnValue = mockHandlerAdaptor.performIntercept(mock, method, arguments); } if (returnValue == null) { return MockGateway.SUPPRESS; } } return returnValue; } private boolean isCanBeHandledByMockito(final Method method) { final int modifiers = method.getModifiers(); return hasDelegator() && !Modifier.isPrivate(modifiers) && !Modifier.isFinal(modifiers) && !Modifier.isStatic(modifiers); } private boolean hasBeenCaughtByMockitoProxy() { return MockitoRealMethodInvocation.isHandledByMockito(); } @Override public Object replay(Object... mocks) { throw new IllegalStateException("Internal error: No such thing as replay exists in Mockito."); } @Override public Object reset(Object... mocks) { throw new IllegalStateException("Internal error: No such thing as reset exists in Mockito."); } public void verifyNoMoreInteractions() { try { Mockito.verifyNoMoreInteractions(getMockHandlerAdaptor().getMock()); } catch (MockitoAssertionError e) { //TODO replace this dirty hack InvocationControlAssertionError.updateErrorMessageForVerifyNoMoreInteractions(e); throw e; } catch (Exception e) { throw new RuntimeException("PowerMock internal error", e); } } private Set toSet(Method... methods) { return methods == null ? null : new HashSet(Arrays.asList(methods)); } private boolean hasDelegator() { return delegator != null; } public MockHandlerAdaptor getMockHandlerAdaptor() { return mockHandlerAdaptor; } } ================================================ FILE: powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/mockmaker/MockMakerLoader.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.api.mockito.mockmaker; import org.mockito.Mockito; import org.mockito.plugins.MockMaker; import org.powermock.configuration.MockitoConfiguration; class MockMakerLoader { MockMaker load(final MockitoConfiguration mockitoConfiguration) { ClassLoader loader = Thread.currentThread().getContextClassLoader(); if (loader == null) { loader = ClassLoader.getSystemClassLoader(); } String mockMakerClassName = mockitoConfiguration.getMockMakerClass(); try { return doLoad(loader, mockMakerClassName); } catch (Exception e) { throw new IllegalStateException("Failed to load MockMaker implementation: " + mockMakerClassName, e); } } private MockMaker doLoad(final ClassLoader loader, final String mockMakerClassName) throws ClassNotFoundException, InstantiationException, IllegalAccessException { if (mockMakerClassName == null) { return Mockito.framework().getPlugins().getDefaultPlugin(MockMaker.class); } else if ("mock-maker-inline".equals(mockMakerClassName)) { return Mockito.framework().getPlugins().getInlineMockMaker(); } else { Class mockMakerClass = loader.loadClass(mockMakerClassName); Object mockMaker = mockMakerClass.newInstance(); return MockMaker.class.cast(mockMaker); } } } ================================================ FILE: powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/mockmaker/PowerMockMaker.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.api.mockito.mockmaker; import org.mockito.Mockito; import org.mockito.invocation.Invocation; import org.mockito.invocation.InvocationContainer; import org.mockito.invocation.MockHandler; import org.mockito.mock.MockCreationSettings; import org.mockito.plugins.MockMaker; import org.powermock.api.mockito.invocation.MockitoMethodInvocationControl; import org.powermock.configuration.GlobalConfiguration; import org.powermock.core.MockRepository; /** * A PowerMock implementation of the MockMaker. */ public class PowerMockMaker implements MockMaker { private final MockMaker mockMaker; public PowerMockMaker() { mockMaker = new MockMakerLoader().load(GlobalConfiguration.mockitoConfiguration()); } @Override public T createMock(MockCreationSettings settings, MockHandler handler){ return mockMaker.createMock(settings, handler); } @Override public MockHandler getHandler(Object mock) { if (mock instanceof Class) { return staticMockHandler((Class) mock); } else { return instanceMockHandler(mock); } } private MockHandler instanceMockHandler(final Object mock) { return mockMaker.getHandler(getRealMock(mock)); } private Object getRealMock(final Object mock) { final MockitoMethodInvocationControl invocationControl = (MockitoMethodInvocationControl) MockRepository.getInstanceMethodInvocationControl(mock); final Object realMock; if (invocationControl == null){ realMock = mock; }else{ realMock = invocationControl.getMockHandlerAdaptor().getMock(); } return realMock; } private MockHandler staticMockHandler(final Class mock) { return new StaticMockHandler(createStaticMockSettings(mock)); } @Override public void resetMock(Object mock, MockHandler newHandler, MockCreationSettings settings) { mockMaker.resetMock(mock, newHandler, settings); } @Override public TypeMockability isTypeMockable(Class type) { return mockMaker.isTypeMockable(type); } MockMaker getMockMaker() { return mockMaker; } @SuppressWarnings("unchecked") private MockCreationSettings createStaticMockSettings(final Class mock) { return Mockito.withSettings() .name(mock.getName()) .build((Class) mock); } private static class StaticMockHandler implements MockHandler { private final MockCreationSettings mockSettings; private StaticMockHandler(final MockCreationSettings mockSettings) { this.mockSettings = mockSettings; } @Override public MockCreationSettings getMockSettings() { return mockSettings; } @Override public InvocationContainer getInvocationContainer() { return null; } @Override public Object handle(Invocation invocation) throws Throwable { return null; } } } ================================================ FILE: powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/mockpolicies/Slf4jMockPolicy.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.api.mockito.mockpolicies; import org.mockito.Mockito; import org.powermock.core.spi.PowerMockPolicy; import org.powermock.mockpolicies.MockPolicyClassLoadingSettings; import org.powermock.mockpolicies.MockPolicyInterceptionSettings; import org.powermock.mockpolicies.support.LogPolicySupport; import java.lang.reflect.Method; /** * Sfl4j mock policy that injects a Mockito-created mock to be returned on calls to getLogger factory methods. * The implementation returns a single mock instance per thread but it doesn't return a different mock instance based * on the actual value passed to getLogger. This limitation is acceptable in most real uses cases. *

* Tests that want to do verifications on the mocked logger can do so by getting the mocked instance as production code * does: {@code org.slf4j.LoggerFactory.getLogger(Class)}. However, it is critical that the mocked logger is * reset after each test in order to avoid crosstalk between test cases. *

* * @author Alexandre Normand */ public class Slf4jMockPolicy implements PowerMockPolicy { private static final String LOGGER_FACTORY_CLASS_NAME = "org.slf4j.LoggerFactory"; private static final String LOGGER_FACTORY_METHOD_NAME = "getLogger"; private static final String FRAMEWORK_NAME = "sfl4j"; private static final String LOGGER_CLASS_NAME = "org.slf4j.Logger"; private static ThreadLocal threadLogger = new ThreadLocal(); @Override public void applyClassLoadingPolicy(MockPolicyClassLoadingSettings mockPolicyClassLoadingSettings) { mockPolicyClassLoadingSettings.addFullyQualifiedNamesOfClassesToLoadByMockClassloader( LOGGER_FACTORY_CLASS_NAME, "org.apache.log4j.Appender", "org.apache.log4j.xml.DOMConfigurator"); } @Override public void applyInterceptionPolicy(MockPolicyInterceptionSettings mockPolicyInterceptionSettings) { LogPolicySupport logPolicySupport = new LogPolicySupport(); Method[] loggerFactoryMethods = logPolicySupport.getLoggerMethods(LOGGER_FACTORY_CLASS_NAME, LOGGER_FACTORY_METHOD_NAME, FRAMEWORK_NAME); initializeMockForThread(logPolicySupport); for (Method loggerFactoryMethod : loggerFactoryMethods) { mockPolicyInterceptionSettings.stubMethod(loggerFactoryMethod, threadLogger.get()); } } private void initializeMockForThread(LogPolicySupport logPolicySupport) { Class loggerClass = getLoggerClass(logPolicySupport); if (threadLogger.get() == null) { /* * When mocking with Mockito we need to change the context CL to the same CL that is loading Mockito * otherwise the Mockito plugin mechanism will load the PowerMockMaker from the wrong classloader. */ final ClassLoader originalCl = Thread.currentThread().getContextClassLoader(); final ClassLoader classLoader = Mockito.class.getClassLoader(); Thread.currentThread().setContextClassLoader(classLoader); final Object mock; try { mock = Mockito.mock(loggerClass); } finally { Thread.currentThread().setContextClassLoader(originalCl); } threadLogger.set(mock); } } private Class getLoggerClass(LogPolicySupport logPolicySupport) { Class loggerType; try { loggerType = logPolicySupport.getType(LOGGER_CLASS_NAME, FRAMEWORK_NAME); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } return loggerType; } } ================================================ FILE: powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/powermocklistener/AnnotationEnabler.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.api.mockito.powermocklistener; /** * Before each test method all fields annotated with {@link org.mockito.Mock} have mock objects created for them * and injected to the fields. * * @deprecated Test Runners uses an annotation enabling listener per default * since version 1.3. You should just remove this listener. */ @Deprecated public class AnnotationEnabler extends org.powermock.api.extension.listener.AnnotationEnabler { } ================================================ FILE: powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/verification/ConstructorArgumentsVerification.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.api.mockito.verification; public interface ConstructorArgumentsVerification { void withArguments(Object argument, Object... additionalArguments) throws Exception; void withNoArguments() throws Exception; } ================================================ FILE: powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/verification/PrivateMethodVerification.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.api.mockito.verification; import java.lang.reflect.Method; public interface PrivateMethodVerification { /** * Verify calls to private methods without having to specify the method * name. The method will be looked up using the parameter types (if * possible). * * @throws Exception If something unexpected goes wrong. * @deprecated Use {@link #invoke(String, Object...)} instead. Will be remove in PowerMock 3.0 */ @Deprecated void invoke(Object... arguments) throws Exception; /** * Verify calls to the specific method. * * @throws Exception If something unexpected goes wrong. */ WithOrWithoutVerifiedArguments invoke(Method method) throws Exception; /** * Verify a private method call by specifying the method name of the method * to verify. * * @throws Exception If something unexpected goes wrong. */ void invoke(String methodToVerify, Object... arguments) throws Exception; } ================================================ FILE: powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/verification/WithOrWithoutVerifiedArguments.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.api.mockito.verification; public interface WithOrWithoutVerifiedArguments extends WithVerifiedArguments, WithoutVerifiedArguments { } ================================================ FILE: powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/verification/WithVerifiedArguments.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.api.mockito.verification; public interface WithVerifiedArguments { void withArguments(Object firstArgument, Object... additionalArguments) throws Exception; } ================================================ FILE: powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/verification/WithoutVerifiedArguments.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.api.mockito.verification; public interface WithoutVerifiedArguments { void withNoArguments() throws Exception; } ================================================ FILE: powermock-api/powermock-api-mockito2/src/main/resources/mockito-extensions/org.mockito.plugins.MockMaker ================================================ org.powermock.api.mockito.mockmaker.PowerMockMaker ================================================ FILE: powermock-api/powermock-api-mockito2/src/main/resources/mockito-extensions/org.mockito.plugins.StackTraceCleanerProvider ================================================ org.powermock.api.mockito.internal.exceptions.StackTraceCleanerProvider ================================================ FILE: powermock-api/powermock-api-mockito2/src/test/java/org/powermock/api/mockito/PowerMockMockito2ApiTestSuite.java ================================================ package org.powermock.api.mockito; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.powermock.api.mockito.internal.expectation.DefaultMethodExpectationSetupTestCase; import org.powermock.api.mockito.internal.mockcreation.MockCreatorTestCase; import org.powermock.api.mockito.mockmaker.PowerMockMakerTestCase; /* * We have to use suite in this case to define order of test and prevent fluky test which * are depends on ordering. */ @RunWith(Suite.class) @Suite.SuiteClasses({ PowerMockMakerTestCase.class, MockCreatorTestCase.class, DefaultMethodExpectationSetupTestCase.class }) public class PowerMockMockito2ApiTestSuite { } ================================================ FILE: powermock-api/powermock-api-mockito2/src/test/java/org/powermock/api/mockito/internal/expectation/DefaultMethodExpectationSetupTestCase.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.api.mockito.internal.expectation; import org.junit.Assert; import org.junit.Test; import org.mockito.exceptions.misusing.MissingMethodInvocationException; import org.powermock.reflect.Whitebox; /** * @author Stanislav Chizhov */ public class DefaultMethodExpectationSetupTestCase { private final CUT object = new CUT(); @Test(expected = MissingMethodInvocationException.class) public void testWithArguments_Multiple() throws Exception { DefaultMethodExpectationSetup s = new DefaultMethodExpectationSetup(object, object.getClass().getMethod("multiple", Object.class, Object.class, Object.class)); Object a1 = new Object(); Object a2 = new Object(); Object a3 = new Object(); s.withArguments(a1, a2, a3); } @Test(expected = MissingMethodInvocationException.class) public void testWithArguments_Single() throws Exception { DefaultMethodExpectationSetup s = new DefaultMethodExpectationSetup(object, object.getClass().getMethod("single", Object.class)); Object a1 = new Object(); s.withArguments(a1); } @Test public void testJoin() throws Exception { Object a1 = new Object(); Object a2 = new Object(); Object a3 = new Object(); Object[] res = Whitebox.invokeMethod(DefaultMethodExpectationSetup.class, "join", a1, new Object[]{a2, a3}); Assert.assertArrayEquals(new Object[]{a1, a2, a3}, res); } public static class CUT { public void multiple(Object a1, Object a2, Object a3) { //Nada } public void single(Object a1) { //Nada } } } ================================================ FILE: powermock-api/powermock-api-mockito2/src/test/java/org/powermock/api/mockito/internal/mockcreation/MockCreatorTestCase.java ================================================ package org.powermock.api.mockito.internal.mockcreation; import org.junit.Test; import org.mockito.MockSettings; import org.mockito.Mockito; import org.mockito.mock.MockName; import org.powermock.api.mockito.invocation.MockitoMethodInvocationControl; import org.powermock.core.MockRepository; import java.util.List; import static org.assertj.core.api.Java6Assertions.assertThat; public class MockCreatorTestCase { @Test public void should_return_mock_name_when_settings_have_name() throws NoSuchMethodException, SecurityException { final String definedMockName = "my-list"; final MockSettings settings = Mockito.withSettings().name(definedMockName); final List result = createMock(settings); final MockName mockName = getMockName(result); assertThat(mockName.toString()) .as("Mock name is configured") .isEqualTo(definedMockName); } @Test public void should_return_class_name_when_settings_have_no_name() throws NoSuchMethodException, SecurityException { final MockSettings settings = Mockito.withSettings(); final List result = createMock(settings); final MockName mockName = getMockName(result); assertThat(mockName.toString()) .as("Mock name is configured") .isEqualTo("list"); } private List createMock(final MockSettings settings) throws NoSuchMethodException { return DefaultMockCreator.mock(List.class, false, false, null, settings, List.class.getMethod("add", Object.class)); } private MockName getMockName(final List result) { final MockitoMethodInvocationControl invocationControl = (MockitoMethodInvocationControl) MockRepository.getInstanceMethodInvocationControl(result); return invocationControl.getMockHandlerAdaptor().getMockSettings().getMockName(); } } ================================================ FILE: powermock-api/powermock-api-mockito2/src/test/java/org/powermock/api/mockito/mockmaker/PowerMockMakerTestCase.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.api.mockito.mockmaker; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.JUnitCore; import org.mockito.Mockito; import org.mockito.invocation.Invocation; import org.mockito.invocation.InvocationContainer; import org.mockito.invocation.MockHandler; import org.mockito.mock.MockCreationSettings; import org.mockito.plugins.MockMaker; import org.powermock.api.mockito.ConfigurationTestUtils; import org.powermock.configuration.GlobalConfiguration; import org.powermock.reflect.Whitebox; import java.lang.reflect.Method; import java.net.URLClassLoader; import java.util.List; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.assertj.core.api.Java6Assertions.fail; import static org.junit.Assume.assumeFalse; public class PowerMockMakerTestCase { @Test public void should_delegate_calls_to_mock_maker_from_configuration() { final String javaVersion = System.getProperty("java.version"); assumeFalse("Test failed on JDK9. System class loader does not extends URLClassloader any more.", javaVersion.startsWith("9")); ClassLoader currentCL = Thread.currentThread().getContextClassLoader(); try { ClassLoader classLoader = new URLClassLoader(((URLClassLoader) currentCL).getURLs(), null); Thread.currentThread().setContextClassLoader(classLoader); final Class jUnitCoreClass = classLoader.loadClass(JUnitCore.class.getName()); final Class targetTestClass = classLoader.loadClass(TargetTest.class.getName()); final Method method = Whitebox.getMethod(jUnitCoreClass, "runClasses", Class[].class); Object result = method.invoke(null, new Object[]{new Class[]{targetTestClass}}); final List failures = Whitebox.invokeMethod(result, "getFailures"); assertThat(failures) .withFailMessage("Failures description %s", failures) .isEmpty(); } catch (Exception e) { fail("Test failed", e); } finally { Thread.currentThread().setContextClassLoader(currentCL); } } public static class DelegateMockMakerStub implements MockMaker { private final Object mock; public DelegateMockMakerStub() { this.mock = new Object(); } @Override public T createMock(final MockCreationSettings settings, final MockHandler handler) { return (T) mock; } @Override public MockHandler getHandler(final Object mock) { return null; } @Override public void resetMock(final Object mock, final MockHandler newHandler, final MockCreationSettings settings) { } @Override public TypeMockability isTypeMockable(final Class type) { return new TypeMockability() { @Override public boolean mockable() { return true; } @Override public String nonMockableReason() { return null; } }; } private Object getMock() { return mock; } } public static class TargetTest { private ConfigurationTestUtils util; @Before public void setUp() throws Exception { util = new ConfigurationTestUtils(); util.copyTemplateToPropertiesFile(); GlobalConfiguration.clear(); } @After public void tearDown() throws Exception { util.clear(); GlobalConfiguration.clear(); } @Test public void runTest() { PowerMockMaker powerMockMaker = new PowerMockMaker(); Object mock = powerMockMaker.createMock(Mockito.withSettings().build(Object.class), new MockHandler() { @Override public Object handle(final Invocation invocation) throws Throwable { return null; } @Override public MockCreationSettings getMockSettings() { return null; } @Override public InvocationContainer getInvocationContainer() { return null; } }); MockMaker mockMaker = powerMockMaker.getMockMaker(); assertThat(mockMaker) .as("Mock maker instance of configuration") .isInstanceOf(DelegateMockMakerStub.class); assertThat(((DelegateMockMakerStub) mockMaker).getMock()) .as("Mock is created by delegated mock maker") .isSameAs(mock); } } } ================================================ FILE: powermock-api/powermock-api-mockito2/src/test/resources/org/powermock/extensions/configuration.template ================================================ mockito.mock-maker-class=org.powermock.api.mockito.mockmaker.PowerMockMakerTestCase$DelegateMockMakerStub ================================================ FILE: powermock-api/powermock-api-support/src/main/java/org/powermock/api/support/ClassLoaderUtil.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.api.support; public class ClassLoaderUtil { /** * Loads a class with a specific classloader, wraps the * {@link ClassNotFoundException} in a runtime exeception. */ @SuppressWarnings("unchecked") public static Class loadClass(Class type, ClassLoader classloader) { return loadClass(type.getName(), classloader); } /** * Loads a class from the current classloader */ @SuppressWarnings("unchecked") public static Class loadClass(String className) { return loadClass(className, ClassLoaderUtil.class.getClassLoader()); } /** * Check whether a classloader can load the given class. */ @SuppressWarnings("unchecked") public static boolean hasClass(Class type, ClassLoader classloader) { try { loadClass(type.getName(), classloader); return true; } catch (RuntimeException e) { if(e.getCause() instanceof ClassNotFoundException) { return false; } throw e; } } /** * Load a class from a specific classloader */ public static Class loadClass(String className, ClassLoader classloader) { if(className == null) { throw new IllegalArgumentException("className cannot be null"); } if(classloader == null) { throw new IllegalArgumentException("classloader cannot be null"); } try { return (Class) Class.forName(className, false, classloader); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } } ================================================ FILE: powermock-api/powermock-api-support/src/main/java/org/powermock/api/support/MethodProxy.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.api.support; import org.powermock.core.MockRepository; import org.powermock.reflect.Whitebox; import org.powermock.reflect.exceptions.MethodNotFoundException; import org.powermock.reflect.exceptions.TooManyMethodsFoundException; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class MethodProxy { /** * Add a proxy for this method. Each call to the method will be routed to * the invocationHandler instead. */ public static void proxy(Method method, InvocationHandler invocationHandler) { assertInvocationHandlerNotNull(invocationHandler); MockRepository.putMethodProxy(method, invocationHandler); } /** * Add a proxy for a method declared in class {@code declaringClass}. * Each call to the method will be routed to the invocationHandler instead. */ public static void proxy(Class declaringClass, String methodName, InvocationHandler invocationHandler) { assertInvocationHandlerNotNull(invocationHandler); if (declaringClass == null) { throw new IllegalArgumentException("declaringClass cannot be null"); } if (methodName == null || methodName.length() == 0) { throw new IllegalArgumentException("methodName cannot be empty"); } Method[] methods = Whitebox.getMethods(declaringClass, methodName); if (methods.length == 0) { throw new MethodNotFoundException(String.format("Couldn't find a method with name %s in the class hierarchy of %s", methodName, declaringClass.getName())); } else if (methods.length > 1) { throw new TooManyMethodsFoundException(String.format("Found %d methods with name %s in the class hierarchy of %s.", methods.length, methodName, declaringClass.getName())); } MockRepository.putMethodProxy(methods[0], invocationHandler); } private static void assertInvocationHandlerNotNull(InvocationHandler invocationHandler) { if (invocationHandler == null) { throw new IllegalArgumentException("invocationHandler cannot be null"); } } } ================================================ FILE: powermock-api/powermock-api-support/src/main/java/org/powermock/api/support/SafeExceptionRethrower.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.api.support; public class SafeExceptionRethrower { public static void safeRethrow(Throwable t) { SafeExceptionRethrower. safeRethrow0(t); } @SuppressWarnings("unchecked") private static void safeRethrow0(Throwable t) throws T { throw (T) t; } } ================================================ FILE: powermock-api/powermock-api-support/src/main/java/org/powermock/api/support/Stubber.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.api.support; import org.powermock.core.MockRepository; import org.powermock.reflect.Whitebox; import org.powermock.reflect.exceptions.MethodNotFoundException; import org.powermock.reflect.exceptions.TooManyMethodsFoundException; import java.lang.reflect.Method; public class Stubber { /** * Add a method that should be intercepted and return another value ( * {@code returnObject}) (i.e. the method is stubbed). */ public static void stubMethod(Method method, Object returnObject) { MockRepository.putMethodToStub(method, returnObject); } /** * Add a method that should be intercepted and return another value ( * {@code returnObject}) (i.e. the method is stubbed). */ public static void stubMethod(Class declaringClass, String methodName, Object returnObject) { if (declaringClass == null) { throw new IllegalArgumentException("declaringClass cannot be null"); } if (methodName == null || methodName.length() == 0) { throw new IllegalArgumentException("methodName cannot be empty"); } Method[] methods = Whitebox.getMethods(declaringClass, methodName); if (methods.length == 0) { throw new MethodNotFoundException(String.format("Couldn't find a method with name %s in the class hierarchy of %s", methodName, declaringClass.getName())); } else if (methods.length > 1) { throw new TooManyMethodsFoundException(String.format("Found %d methods with name %s in the class hierarchy of %s.", methods.length, methodName, declaringClass.getName())); } MockRepository.putMethodToStub(methods[0], returnObject); } } ================================================ FILE: powermock-api/powermock-api-support/src/main/java/org/powermock/api/support/SuppressCode.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.api.support; import org.powermock.core.MockRepository; import org.powermock.reflect.Whitebox; import org.powermock.reflect.internal.WhiteboxImpl; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; public class SuppressCode { /** * Suppress constructor calls on specific constructors only. */ public static synchronized void suppressConstructor(Constructor... constructors) { if (constructors == null) { throw new IllegalArgumentException("constructors cannot be null."); } for (Constructor constructor : constructors) { MockRepository.addConstructorToSuppress(constructor); // Also suppress all parent constructors Class declaringClass = constructor.getDeclaringClass(); if (declaringClass != null) { suppressConstructor((Class) declaringClass.getSuperclass()); } } } /** * This method can be used to suppress the code in a specific constructor. * * @param clazz * The class where the constructor is located. * @param parameterTypes * The parameter types of the constructor to suppress. */ public static synchronized void suppressSpecificConstructor(Class clazz, Class... parameterTypes) { MockRepository.addConstructorToSuppress(Whitebox.getConstructor(clazz, parameterTypes)); } /** * Suppress all constructors in the given class and it's super classes. * * @param classes * The classes whose constructors will be suppressed. */ public static synchronized void suppressConstructor(Class... classes) { for (Class clazz : classes) { Class tempClass = clazz; while (tempClass != Object.class) { suppressConstructor(tempClass, false); tempClass = tempClass.getSuperclass(); } } } /** * Suppress all constructors in the given class. * * @param clazz * The classes whose constructors will be suppressed. * @param excludePrivateConstructors * optionally keep code in private constructors */ public static synchronized void suppressConstructor(Class clazz, boolean excludePrivateConstructors) { Constructor[] ctors = null; if (excludePrivateConstructors) { ctors = clazz.getConstructors(); } else { ctors = clazz.getDeclaredConstructors(); } for (Constructor ctor : ctors) { MockRepository.addConstructorToSuppress(ctor); } } /** * Suppress specific fields. This works on both instance methods and static * methods. Note that replay and verify are not needed as this is not part * of a mock behavior. */ public static synchronized void suppressField(Field... fields) { for (Field field : fields) { MockRepository.addFieldToSuppress(field); } } /** * Suppress all fields for these classes. */ public static synchronized void suppressField(Class[] classes) { if (classes == null || classes.length == 0) { throw new IllegalArgumentException("You must supply at least one class."); } for (Class clazz : classes) { suppressField(clazz.getDeclaredFields()); } } /** * Suppress multiple methods for a class. * * @param clazz * The class whose methods will be suppressed. * @param fieldNames * The names of the methods that'll be suppressed. If field names * are empty, all fields in the supplied class will be * suppressed. */ public static synchronized void suppressField(Class clazz, String... fieldNames) { if (fieldNames == null || fieldNames.length == 0) { suppressField(new Class[] { clazz }); } else { for (Field field : Whitebox.getFields(clazz, fieldNames)) { MockRepository.addFieldToSuppress(field); } } } /** * Suppress specific method calls on all types containing this method. This * works on both instance methods and static methods. Note that replay and * verify are not needed as this is not part of a mock behavior. */ public static synchronized void suppressMethod(Method... methods) { for (Method method : methods) { MockRepository.addMethodToSuppress(method); } } /** * Suppress all methods for these classes. * * @param cls * The first class whose methods will be suppressed. * @param additionalClasses * Additional classes whose methods will be suppressed. */ public static synchronized void suppressMethod(Class cls, Class... additionalClasses) { suppressMethod(cls, false); for (Class clazz : additionalClasses) { suppressMethod(clazz, false); } } /** * Suppress all methods for these classes. * * @param classes * Classes whose methods will be suppressed. */ public static synchronized void suppressMethod(Class[] classes) { for (Class clazz : classes) { suppressMethod(clazz, false); } } /** * Suppress multiple methods for a class. * * @param clazz * The class whose methods will be suppressed. * @param methodName * The first method to be suppress in class {@code clazz}. * @param additionalMethodNames * Additional methods to suppress in class {@code clazz}. */ public static synchronized void suppressMethod(Class clazz, String methodName, String... additionalMethodNames) { for (Method method : Whitebox.getMethods(clazz, methodName)) { MockRepository.addMethodToSuppress(method); } if (additionalMethodNames != null && additionalMethodNames.length > 0) { for (Method method : Whitebox.getMethods(clazz, additionalMethodNames)) { MockRepository.addMethodToSuppress(method); } } } /** * Suppress multiple methods for a class. * * @param clazz * The class whose methods will be suppressed. * @param methodNames * Methods to suppress in class {@code clazz}. */ public static synchronized void suppressMethod(Class clazz, String[] methodNames) { for (Method method : Whitebox.getMethods(clazz, methodNames)) { MockRepository.addMethodToSuppress(method); } } /** * suSuppress all methods for this class. * * @param clazz * The class which methods will be suppressed. * @param excludePrivateMethods * optionally not suppress private methods */ public static synchronized void suppressMethod(Class clazz, boolean excludePrivateMethods) { Method[] methods = null; if (excludePrivateMethods) { methods = clazz.getMethods(); } else { methods = clazz.getDeclaredMethods(); } for (Method method : methods) { MockRepository.addMethodToSuppress(method); } } /** * Suppress a specific method call. Use this for overloaded methods. */ public static synchronized void suppressMethod(Class clazz, String methodName, Class[] parameterTypes) { Method method = null; if (parameterTypes.length > 0) { method = Whitebox.getMethod(clazz, methodName, parameterTypes); } else { method = WhiteboxImpl.findMethodOrThrowException(clazz, methodName, parameterTypes); } MockRepository.addMethodToSuppress(method); } } ================================================ FILE: powermock-api/powermock-api-support/src/main/java/org/powermock/api/support/membermodification/MemberMatcher.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.api.support.membermodification; import org.powermock.reflect.Whitebox; import org.powermock.reflect.exceptions.ConstructorNotFoundException; import org.powermock.reflect.exceptions.FieldNotFoundException; import org.powermock.reflect.exceptions.MethodNotFoundException; import org.powermock.reflect.exceptions.TooManyConstructorsFoundException; import org.powermock.reflect.exceptions.TooManyMethodsFoundException; import org.powermock.reflect.internal.WhiteboxImpl; import org.powermock.tests.utils.impl.ArrayMergerImpl; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Collections; import java.util.HashSet; import java.util.Set; import static java.util.Arrays.asList; /** * Finds members in classes. */ public class MemberMatcher { /** * Get all methods in a class hierarchy of the supplied classes. Both * declared an non-declared (no duplicates). * * @param cls * The class whose methods to get. * @param additionalClasses * Additional classes whose methods to get. * @return All methods declared in this class hierarchy. */ public static Method[] methodsDeclaredIn(final Class cls, final Class... additionalClasses) { if (cls == null) { throw new IllegalArgumentException("You need to supply at least one class."); } Set methods = new HashSet(); methods.addAll(asList(WhiteboxImpl.getAllMethods(cls))); for (Class klass : additionalClasses) { methods.addAll(asList(WhiteboxImpl.getAllMethods(klass))); } return methods.toArray(new Method[methods.size()]); } /** * Get a method when it cannot be determined by methodName or parameter * types only. *

* The method will first try to look for a declared method in the same * class. If the method is not declared in this class it will look for the * method in the super class. This will continue throughout the whole class * hierarchy. If the method is not found an {@link IllegalArgumentException} * is thrown. * * @param declaringClass * The declaringClass of the class where the method is located. * @param methodName * The method names. * @param parameterTypes * All parameter types of the method (may be {@code null}). * @return A {@code java.lang.reflect.Method}. * @throws MethodNotFoundException * If a method cannot be found in the hierarchy. */ public static Method method(Class declaringClass, String methodName, Class... parameterTypes) { final Method method = WhiteboxImpl.findMethod(declaringClass, methodName, parameterTypes); WhiteboxImpl.throwExceptionIfMethodWasNotFound(declaringClass, methodName, method, (Object[]) parameterTypes); return method; } /** * Get a method without having to specify the method name. *

* The method will first try to look for a declared method in the same * class. If the method is not declared in this class it will look for the * method in the super class. This will continue throughout the whole class * hierarchy. If the method is not found an {@link IllegalArgumentException} * is thrown. Since the method name is not specified an * {@link IllegalArgumentException} is thrown if two or more methods matches * the same parameter types in the same class. * * @param declaringClass * The declaringClass of the class where the method is located. * @param parameterTypes * All parameter types of the method (may be {@code null}). * @return A {@code java.lang.reflect.Method}. * @throws MethodNotFoundException * If a method cannot be found in the hierarchy. * @throws TooManyMethodsFoundException * If several methods were found. */ public static Method method(Class declaringClass, Class... parameterTypes) { return Whitebox.getMethod(declaringClass, parameterTypes); } /** * Get an array of {@link Method}'s that matches the supplied list of method * names. Both instance and static methods are taken into account. * * @param clazz * The class that should contain the methods. * @param methodName * The name of the first method. * @param additionalMethodNames * Additional names of the methods that will be returned. * @return An array of Method's. May be of length 0 but not * {@code null}. * @throws MethodNotFoundException * If no method was found. */ public static Method[] methods(Class clazz, String methodName, String... additionalMethodNames) { return Whitebox.getMethods(clazz, merge(methodName, additionalMethodNames)); } /** * Get an array of {@link Field}'s. * * @param method * The first field. * @param additionalMethods * Additional fields * @return An array of {@link Field}. */ public static Method[] methods(Method method, Method... additionalMethods) { return merge(method, additionalMethods); } /** * Get an array of {@link Method}'s that matches the supplied list of method * names. Both instance and static methods are taken into account. * * @param clazz * The class that should contain the methods. * @param methodNames * The names of the methods. * @return An array of Method's. May be of length 0 but not * {@code null}. * @throws MethodNotFoundException * If no method was found. */ public static Method[] methods(Class clazz, String[] methodNames) { return Whitebox.getMethods(clazz, methodNames); } /** * Get a field from a class. *

* The method will first try to look for a declared field in the same class. * If the method is not declared in this class it will look for the field in * the super class. This will continue throughout the whole class hierarchy. * If the field is not found an {@link IllegalArgumentException} is thrown. * * @param declaringClass * The declaringClass of the class where the method is located. * @param fieldName * The method names. * @return A {@code java.lang.reflect.Field}. * @throws FieldNotFoundException * If a field cannot be found in the hierarchy. */ public static Field field(Class declaringClass, String fieldName) { return Whitebox.getField(declaringClass, fieldName); } /** * Get an array of {@link Field}'s that matches the supplied list of field * names. * * @param clazz * The class that should contain the fields. * @param firstFieldName * The name of the first field. * @param additionalfieldNames * The additional names of the fields that will be returned. * @return An array of Field's. May be of length 0 but not {@code null} * */ public static Field[] fields(Class clazz, String firstFieldName, String... additionalfieldNames) { return Whitebox.getFields(clazz, merge(firstFieldName, additionalfieldNames)); } /** * Get all fields in a class hierarchy. * * @param clazz * The class that should contain the fields. * @return An array of Field's. May be of length 0 but not {@code null} * */ public static Field[] fields(Class clazz) { return WhiteboxImpl.getAllFields(clazz); } /** * Get an array of {@link Field}'s. * * @param field * The first field. * @param additionalFields * Additional fields * @return An array of {@link Field}. */ public static Field[] fields(Field field, Field... additionalFields) { return merge(field, additionalFields); } /** * Get an array of {@link Field}'s that matches the supplied list of field * names. * * @param clazz * The class that should contain the fields. * @param fieldNames * The names of the fields that will be returned. * @return An array of Field's. May be of length 0 but not {@code null} * */ public static Field[] fields(Class clazz, String[] fieldNames) { return Whitebox.getFields(clazz, fieldNames); } /** * Returns a constructor specified in declaringClass. * * @param declaringClass * The declaringClass of the class where the constructor is * located. * @param parameterTypes * All parameter types of the constructor (may be * {@code null}). * @return A {@code java.lang.reflect.Constructor}. * @throws ConstructorNotFoundException * if the constructor cannot be found. */ @SuppressWarnings("unchecked") public static Constructor constructor(Class declaringClass, Class... parameterTypes) { return (Constructor) WhiteboxImpl.findUniqueConstructorOrThrowException(declaringClass, (Object[]) parameterTypes); } /** * Returns any one constructor specified in declaringClass. Is is useful when you only have ONE constructor * declared in {@code declaringClass} but you don't care which parameters it take. * * @param declaringClass * The declaringClass of the class where the constructor is * located. * @return A {@code java.lang.reflect.Constructor}. * @throws TooManyConstructorsFoundException * If more than one constructor was present in * {@code declaringClass} */ @SuppressWarnings("unchecked") public static Constructor constructor(Class declaringClass) { return (Constructor) WhiteboxImpl.findConstructorOrThrowException(declaringClass); } /** * Returns the default constructor in {@code declaringClass} * * @param declaringClass * The declaringClass of the class where the constructor is * located. * @return A {@code java.lang.reflect.Constructor}. * @throws ConstructorNotFoundException * If no default constructor was found in {@code declaringClass} */ @SuppressWarnings("unchecked") public static Constructor defaultConstructorIn(Class declaringClass) { return (Constructor) WhiteboxImpl.findDefaultConstructorOrThrowException(declaringClass); } /** * Get all constructors in the supplied class(es). * * @param cls * The class whose constructors to get. * @param additionalClasses * Additional classes whose constructors to get. * @return All constructors declared in this class. */ public static Constructor[] constructorsDeclaredIn(final Class cls, final Class... additionalClasses) { if (cls == null) { throw new IllegalArgumentException("You need to supply at least one class."); } Set> constructors = new HashSet>(); constructors.addAll(asList(WhiteboxImpl.getAllConstructors(cls))); for (Class klass : additionalClasses) { constructors.addAll(asList(WhiteboxImpl.getAllConstructors(klass))); } return constructors.toArray(new Constructor[constructors.size()]); } /** * Convenience method to get a constructor from a class. * * @param constructor * The first constructor. * @param additionalConstructors * Additional constructors * @return An array of {@code java.lang.reflect.Constructor}. */ public static Constructor[] constructors(Constructor constructor, Constructor... additionalConstructors) { return merge(constructor, additionalConstructors); } /** * Get all constructors and methods in the supplied class(es). * * @param cls * The class whose constructors and methods to get. * @param additionalClasses * Additional classes whose constructors and methods to get. * @return All constructors and methods declared in this class. */ public static AccessibleObject[] everythingDeclaredIn(final Class cls, final Class... additionalClasses) { if (cls == null) { throw new IllegalArgumentException("You need to supply at least one class."); } Set accessibleObjects = new HashSet(); accessibleObjects.addAll(Collections.unmodifiableCollection(asList(methodsDeclaredIn(cls, additionalClasses)))); accessibleObjects.addAll(Collections.unmodifiableCollection(asList(constructorsDeclaredIn(cls, additionalClasses)))); return accessibleObjects.toArray(new AccessibleObject[accessibleObjects.size()]); } private static String[] merge(String first, String... additional) { return new ArrayMergerImpl().mergeArrays(String.class, new String[] { first }, additional); } private static Method[] merge(Method first, Method... additional) { return new ArrayMergerImpl().mergeArrays(Method.class, new Method[] { first }, additional); } private static Field[] merge(Field first, Field... additional) { return new ArrayMergerImpl().mergeArrays(Field.class, new Field[] { first }, additional); } private static Constructor[] merge(Constructor first, Constructor... additional) { return new ArrayMergerImpl().mergeArrays(Constructor.class, new Constructor[] { first }, additional); } } ================================================ FILE: powermock-api/powermock-api-support/src/main/java/org/powermock/api/support/membermodification/MemberModifier.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.api.support.membermodification; import org.powermock.api.support.SuppressCode; import org.powermock.api.support.membermodification.strategy.MethodReplaceStrategy; import org.powermock.api.support.membermodification.strategy.MethodStubStrategy; import org.powermock.api.support.membermodification.strategy.impl.MethodReplaceStrategyImpl; import org.powermock.api.support.membermodification.strategy.impl.MethodStubStrategyImpl; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; /** * Contains various utilities for modifying members of classes such as * constructors, fields and methods. Modifying means e.g. changing return value * of method invocations or suppressing a constructor. */ public class MemberModifier extends MemberMatcher { /** * Suppress a specific method. This works on both instance methods and * static methods. */ public static void suppress(Method method) { SuppressCode.suppressMethod(method); } /** * Suppress multiple methods. This works on both instance methods and static * methods. */ public static void suppress(Method[] methods) { SuppressCode.suppressMethod(methods); } /** * Suppress a constructor. */ public static void suppress(Constructor constructor) { SuppressCode.suppressConstructor(constructor); } /** * Suppress multiple constructors. */ public static void suppress(Constructor[] constructors) { SuppressCode.suppressConstructor(constructors); } /** * Suppress a field. */ public static void suppress(Field field) { SuppressCode.suppressField(field); } /** * Suppress multiple fields. */ public static void suppress(Field[] fields) { SuppressCode.suppressField(fields); } /** * Suppress an array of accessible objects. */ public static void suppress(AccessibleObject[] accessibleObjects) { if (accessibleObjects == null) { throw new IllegalArgumentException("accessibleObjects cannot be null"); } for (AccessibleObject accessibleObject : accessibleObjects) { if (accessibleObject instanceof Constructor) { SuppressCode.suppressConstructor((Constructor) accessibleObject); } else if (accessibleObject instanceof Field) { SuppressCode.suppressField((Field) accessibleObject); } else if (accessibleObject instanceof Method) { SuppressCode.suppressMethod((Method) accessibleObject); } } } /** * Add a method that should be intercepted and return another value (i.e. * the method is stubbed). */ public static MethodStubStrategy stub(Method method) { return new MethodStubStrategyImpl(method); } /** * Replace a method invocation. */ public static MethodReplaceStrategy replace(Method method) { return new MethodReplaceStrategyImpl(method); } } ================================================ FILE: powermock-api/powermock-api-support/src/main/java/org/powermock/api/support/membermodification/strategy/ClassReplaceStrategy.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.api.support.membermodification.strategy; /** * Specifies the replace strategy for a class. */ public interface ClassReplaceStrategy { /** * Replaces all method invocations on class specified class with method * invocation to {@code cls}. Also replaces all constructor * invocations. You can see this as duck typing. * * @param cls * The class that will replace the other class. */ void with(Class cls); } ================================================ FILE: powermock-api/powermock-api-support/src/main/java/org/powermock/api/support/membermodification/strategy/MethodReplaceStrategy.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.api.support.membermodification.strategy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; /** * Specifies the replace strategy for a method. */ public interface MethodReplaceStrategy { /** * Replaces the method invocation with this method. *

* Note that both methods needs to be static. * * @param method * The method call will be replaced by this method instead. Needs * to be static. */ void with(Method method); /** * Replaces the method invocation with an invocation handler * * @param invocationHandler * The invocation handler to replace the method call with. */ void with(InvocationHandler invocationHandler); } ================================================ FILE: powermock-api/powermock-api-support/src/main/java/org/powermock/api/support/membermodification/strategy/MethodStubStrategy.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.api.support.membermodification.strategy; /** * Specifies the return value when stubbing a method. */ public interface MethodStubStrategy { /** * Stubs the method to return the specified returnValue. * * @param returnValue * The value that will be returned. * @deprecated Since version 1.4.1, use {@link #toReturn(Object)} instead. */ @Deprecated void andReturn(T returnValue); /** * Stubs the method to return the specified returnValue. * * @param returnValue * The value that will be returned. */ void toReturn(T returnValue); /** * Stubs the method to throw the specified throwable. * * @param throwable * the throwable */ void toThrow(Throwable throwable); } ================================================ FILE: powermock-api/powermock-api-support/src/main/java/org/powermock/api/support/membermodification/strategy/impl/MethodReplaceStrategyImpl.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.api.support.membermodification.strategy.impl; import org.powermock.api.support.MethodProxy; import org.powermock.api.support.membermodification.strategy.MethodReplaceStrategy; import org.powermock.reflect.internal.WhiteboxImpl; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Modifier; public class MethodReplaceStrategyImpl implements MethodReplaceStrategy { private final Method method; public MethodReplaceStrategyImpl(Method method) { if (method == null) { throw new IllegalArgumentException("Cannot replace a null method."); } this.method = method; } @Override public void with(Method method) { if (method == null) { throw new IllegalArgumentException("A metod cannot be replaced with null."); } if (!Modifier.isStatic(this.method.getModifiers())) { throw new IllegalArgumentException(String.format("Replace requires static methods, '%s' is not static", this.method)); } else if (!Modifier.isStatic(method.getModifiers())) { throw new IllegalArgumentException(String.format("Replace requires static methods, '%s' is not static", method)); } else if(!this.method.getReturnType().isAssignableFrom(method.getReturnType())) { 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())); } else if(!WhiteboxImpl.checkIfParameterTypesAreSame(this.method.isVarArgs(),this.method.getParameterTypes(), method.getParameterTypes())) { 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())); } else { MethodProxy.proxy(this.method, new MethodInvocationHandler(method)); } } @Override public void with(InvocationHandler invocationHandler) { if (invocationHandler == null) { throw new IllegalArgumentException("Invocation handler cannot be null"); } MethodProxy.proxy(method, invocationHandler); } private final class MethodInvocationHandler implements InvocationHandler { private final Method methodDelegator; public MethodInvocationHandler(Method methodDelegator) { this.methodDelegator = methodDelegator; } @Override public Object invoke(Object object, Method invokingMethod, Object[] arguments) throws Throwable { return methodDelegator.invoke(object, arguments); } } } ================================================ FILE: powermock-api/powermock-api-support/src/main/java/org/powermock/api/support/membermodification/strategy/impl/MethodStubStrategyImpl.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.api.support.membermodification.strategy.impl; import org.powermock.api.support.MethodProxy; import org.powermock.api.support.Stubber; import org.powermock.api.support.membermodification.strategy.MethodStubStrategy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class MethodStubStrategyImpl implements MethodStubStrategy { private final Method method; public MethodStubStrategyImpl(Method method) { if (method == null) { throw new IllegalArgumentException("Method to stub cannot be null."); } this.method = method; } @Deprecated @Override public void andReturn(T returnValue) { toReturn(returnValue); } @Override public void toThrow(final Throwable throwable) { InvocationHandler throwingInvocationHandler = new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { throw throwable; } }; MethodProxy.proxy(method, throwingInvocationHandler); } @Override public void toReturn(T returnValue) { Stubber.stubMethod(method, returnValue); } } ================================================ FILE: powermock-classloading/powermock-classloading-base/src/main/java/org/powermock/classloading/AbstractClassloaderExecutor.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.classloading; import org.powermock.api.support.ClassLoaderUtil; import org.powermock.api.support.SafeExceptionRethrower; import org.powermock.classloading.spi.DeepClonerSPI; import org.powermock.reflect.Whitebox; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.concurrent.Callable; public abstract class AbstractClassloaderExecutor implements ClassloaderExecutor { @Override @SuppressWarnings("unchecked") public T execute(Callable callable) { assertArgumentNotNull(callable, "callable"); return (T) execute(callable, Whitebox.getMethod(callable.getClass(), "call")); } @Override public void execute(Runnable runnable) { assertArgumentNotNull(runnable, "runnable"); execute(runnable, Whitebox.getMethod(runnable.getClass(), "run")); } private void assertArgumentNotNull(Object object, String argumentName) { if (object == null) { throw new IllegalArgumentException(argumentName + " cannot be null."); } } protected abstract Object execute(Object instance, Method method, Object... arguments); Object executeWithClassLoader(Object instance, Method method, ClassLoader classloader, Object[] arguments) { final DeepClonerSPI deepCloner = createDeepCloner(classloader); final Object objectLoadedWithClassloader = deepCloner.clone(instance); final Object[] argumentsLoadedByClassLoader = cloneArguments(arguments, deepCloner); return invokeWithClassLoader(classloader, method, objectLoadedWithClassloader, argumentsLoadedByClassLoader); } private Object invokeWithClassLoader(final ClassLoader classloader, final Method method, final Object objectLoadedWithClassloader, final Object[] argumentsLoadedByClassLoader) { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(classloader); Object result = getResult(method, objectLoadedWithClassloader, argumentsLoadedByClassLoader); return cloneResult(result); } finally { Thread.currentThread().setContextClassLoader(classLoader); } } private Object cloneResult(Object result) {return result == null ? null : createDeepCloner(getClass().getClassLoader()).clone(result);} private Object getResult(Method method, Object objectLoadedWithClassloader, Object[] argumentsLoadedByClassLoader) { Object result = null; try { result = Whitebox.invokeMethod(objectLoadedWithClassloader, method.getName(), argumentsLoadedByClassLoader); } catch (Exception e) { SafeExceptionRethrower.safeRethrow(e); } return result; } private Object[] cloneArguments(Object[] arguments, DeepClonerSPI deepCloner) { final Object[] argumentsLoadedByClassLoader = new Object[arguments.length]; for (int i = 0; i < arguments.length; i++) { final Object argument = arguments[i]; argumentsLoadedByClassLoader[i] = deepCloner.clone(argument); } return argumentsLoadedByClassLoader; } private DeepClonerSPI createDeepCloner(ClassLoader classLoader) { final Class deepClonerClass = ClassLoaderUtil.loadClass("org.powermock.classloading.DeepCloner"); ClassLoader currentCL = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(deepClonerClass.getClass().getClassLoader()); return doCreateDeepCloner(classLoader, deepClonerClass); } finally { Thread.currentThread().setContextClassLoader(currentCL); } } private DeepClonerSPI doCreateDeepCloner(final ClassLoader classLoader, final Class deepClonerClass) { final Constructor constructor = Whitebox.getConstructor(deepClonerClass, ClassLoader.class); try { return constructor.newInstance(classLoader); } catch (Exception e) { throw new RuntimeException("Failed to instantiate DeepCloner. The DeepCloner implementation must have a one-arg constructor taking a Classloader as parameter.", e); } } } ================================================ FILE: powermock-classloading/powermock-classloading-base/src/main/java/org/powermock/classloading/ClassloaderExecutor.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.classloading; import org.powermock.classloading.spi.DeepClonerSPI; import java.util.concurrent.Callable; /** * A ClassLoaderExecutor can run any code in any classloader. E.g. assume you have a classloader * called myClassloader and you want to execute a (void) method called myMethod in myObject using this CL: *

 *     SingleClassloaderExecutor cle = new SingleClassloaderExecutor(myClassloader);
 *     cle.execute(new Runnable() {
 *          public void run() {
 *             myObject.myMethod();
 *          }
 *     });
 * 
* * What happens is that the entire object graph of myObject is deep-cloned into the {@code myClassloader} classloader * and then the {@code myObject.myMethod()} is executed. *

* You can also execute methods that return something: *

 *     SingleClassloaderExecutor cle = new SingleClassloaderExecutor(myClassloader);
 *     MyResult result = cle.execute(new Callable() {
 *          public MyResult call() throws Exception {
 *             return myObject.myMethod();
 *          }
 *     });
 * 
* Here we imagine that {@code myObject.myMethod()} returns an object of type {@code MyResult}. Again the entire * state will be deep-cloned to {@code myClassloader} and then the {@code myObject.myMethod()} is executed. * The result of the method call is deep-cloned back into the original classloader (the one that made the call to * {@code cle.execute(..)}) and is ready for use. *

*

* Note that the SingleClassloaderExecutor requires a deep cloner implementing the {@link DeepClonerSPI} present in the class-path. *

*/ public interface ClassloaderExecutor { T execute(Callable callable); void execute(Runnable runnable); } ================================================ FILE: powermock-classloading/powermock-classloading-base/src/main/java/org/powermock/classloading/SingleClassloaderExecutor.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.classloading; import org.powermock.classloading.spi.DoNotClone; import java.lang.reflect.Method; public class SingleClassloaderExecutor extends AbstractClassloaderExecutor { @DoNotClone private final ClassLoader classloader; public SingleClassloaderExecutor(ClassLoader classloader) { this.classloader = classloader; } @Override protected Object execute(Object instance, Method method, Object... arguments) { return executeWithClassLoader(instance, method, classloader, arguments); } } ================================================ FILE: powermock-classloading/powermock-classloading-base/src/main/java/org/powermock/classloading/spi/DeepClonerSPI.java ================================================ package org.powermock.classloading.spi; /** * A deep-cloner must implement this interface. */ public interface DeepClonerSPI { T clone(T objectToClone); } ================================================ FILE: powermock-classloading/powermock-classloading-base/src/main/java/org/powermock/classloading/spi/DoNotClone.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.classloading.spi; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Fields annotated with this annotation are not allowed to be cloned by a Deep Cloner implementation. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) @Inherited public @interface DoNotClone { } ================================================ FILE: powermock-classloading/powermock-classloading-objenesis/src/main/java/org/powermock/classloading/DeepCloner.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.classloading; import org.powermock.api.support.ClassLoaderUtil; import org.powermock.api.support.SafeExceptionRethrower; import org.powermock.classloading.spi.DeepClonerSPI; import org.powermock.classloading.spi.DoNotClone; import org.powermock.core.ListMap; import org.powermock.reflect.Whitebox; import sun.misc.Unsafe; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Map; /** *

* The purpose of the deep cloner is to create a deep clone of an object. An * object can also be cloned to a different class-loader. *

*/ public class DeepCloner implements DeepClonerSPI { private final ClassLoader targetCL; private final Map referenceMap = new ListMap(); private final Class doNotClone; /** * Clone using the supplied ClassLoader. * @param classLoader - the classloader to loaded cloned classes. */ public DeepCloner(ClassLoader classLoader) { this.targetCL = classLoader; doNotClone = getDoNotClone(targetCL); } /** * Clone using the current ContextClassLoader. */ public DeepCloner() { this(Thread.currentThread().getContextClassLoader()); } private Class getDoNotClone(ClassLoader targetCL) { return ClassLoaderUtil.loadClass(DoNotClone.class, targetCL); } /** * Clones an object. * * @param objectToClone the object to clone. * @return A deep clone of the object to clone. */ @Override public T clone(T objectToClone) { return clone(objectToClone, true); } /** * * @param objectToClone the object to clone * @param includeStandardJavaType * {@code true} also clones standard java types (using * simple serialization), {@code false} simply reference to * these objects (will be same instance). * @return A deep clone of the object to clone. */ public T clone(T objectToClone, boolean includeStandardJavaType) { assertObjectNotNull(objectToClone); return performClone(ClassLoaderUtil.loadClass(getType(objectToClone), targetCL), objectToClone, includeStandardJavaType); } @SuppressWarnings("unchecked") private static Class getType(T object) { if (object == null) { return null; } return (Class) (object instanceof Class ? object : object.getClass()); } private static boolean isClass(Object object) { if (object == null) { return false; } return object instanceof Class; } private static void assertObjectNotNull(Object object) { if (object == null) { throw new IllegalArgumentException("Object to clone cannot be null"); } } @SuppressWarnings("unchecked") private T performClone(Class targetClass, Object source, boolean shouldCloneStandardJavaTypes) { Object target = null; if (targetClass.isArray() && !isClass(source)) { return (T) instantiateArray(targetCL, targetClass, source, shouldCloneStandardJavaTypes); } else if (isJavaReflectMethod(targetClass)) { return (T) cloneJavaReflectMethod(source); } else if (targetClass.isPrimitive() || isSunClass(targetClass) || isJavaReflectClass(targetClass)) { return (T) source; } else if (isSerializableCandidate(targetClass, source)) { return (T) serializationClone(source); } else if (targetClass.isEnum()) { return (T) cloneEnum(targetCL, source); } else if (isClass(source)) { return (T) ClassLoaderUtil.loadClass(getType(source), targetCL); } else { target = isClass(source) ? source : Whitebox.newInstance(targetClass); } if (target != null) { referenceMap.put(source, target); cloneFields(targetCL, targetClass, source, target, referenceMap, shouldCloneStandardJavaTypes); } return (T) target; } private Object cloneJavaReflectMethod(Object source) { Method sourceMethod = (Method) source; Class declaringClass = sourceMethod.getDeclaringClass(); Class targetClassLoadedWithTargetCL = ClassLoaderUtil.loadClass(declaringClass, targetCL); Method targetMethod = null; try { targetMethod = targetClassLoadedWithTargetCL.getDeclaredMethod(sourceMethod.getName(), sourceMethod.getParameterTypes()); } catch (Exception e) { SafeExceptionRethrower.safeRethrow(e); } if (sourceMethod.isAccessible()) { targetMethod.setAccessible(true); } return targetMethod; } private boolean isJavaReflectMethod(Class cls) { return cls.getName().equals(Method.class.getName()); } private boolean isSunClass(Class cls) { return cls.getName().startsWith("sun."); } private boolean isJavaReflectClass(Class cls) { return cls.getName().startsWith("java.lang.reflect"); } private boolean isSerializableCandidate(Class targetClass, Object source) { return isStandardJavaType(targetClass) && (isSerializable(targetClass) || isImpliticlySerializable(targetClass)) && !Map.class.isAssignableFrom(source.getClass()) && !Iterable.class.isAssignableFrom(source.getClass()); } private static boolean isImpliticlySerializable(Class cls) { return cls.isPrimitive(); } private static boolean isSerializable(Class cls) { return Serializable.class.isAssignableFrom(cls); } /* * Perform simple serialization */ private Object serializationClone(Object source) { ObjectOutputStream oos = null; ObjectInputStream ois = null; try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(bos); oos.writeObject(source); oos.flush(); ByteArrayInputStream bin = new ByteArrayInputStream(bos.toByteArray()); ois = new ObjectInputStream(bin); return ois.readObject(); } catch (Exception e) { throw new RuntimeException(e); } finally { close(oos); close(ois); } } private void close(Closeable closeable) { try { if (closeable != null) { closeable.close(); } } catch (IOException e) { } } @SuppressWarnings({ "unchecked", "rawtypes" }) private Object cloneEnum(ClassLoader targetCL, Object source) { Object target; final Class enumClassLoadedByTargetCL = ClassLoaderUtil.loadClass(getType(source), targetCL); target = getEnumValue(source, enumClassLoadedByTargetCL); return target; } @SuppressWarnings("unchecked") private void cloneFields(ClassLoader targetCL, Class targetClass, Object source, Object target, Map referenceMap, boolean cloneStandardJavaTypes) { Class currentTargetClass = targetClass; while (currentTargetClass != null) { for (Field field : currentTargetClass.getDeclaredFields()) { if (field.getAnnotation(doNotClone) != null) { continue; } field.setAccessible(true); try { final Field declaredField = Whitebox.getField(getType(source), field.getName()); declaredField.setAccessible(true); final Object object = declaredField.get(source); final Object instantiatedValue; if (object == source) { instantiatedValue = target; } else if (referenceMap.containsKey(object)) { instantiatedValue = referenceMap.get(object); } else { if (object == null && !isIterable(object)) { instantiatedValue = object; } else { Class type = getType(object); if (type.getName().equals("void")) { type = Class.class.cast(Class.class); } final Class typeLoadedByCL = ClassLoaderUtil.loadClass(type, targetCL ); if (type.isEnum()) { instantiatedValue = getEnumValue(object, typeLoadedByCL); } else { instantiatedValue = performClone(typeLoadedByCL, object, cloneStandardJavaTypes); } } } final boolean needsUnsafeWrite = field.isEnumConstant() || isStaticFinalModifier(field); if (needsUnsafeWrite) { UnsafeFieldWriter.write(field, target, instantiatedValue); } else { field.set(target, instantiatedValue); } } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } } currentTargetClass = currentTargetClass.getSuperclass(); } } private static boolean isStandardJavaType(Class targetClass) { return targetClass.getName().startsWith("java."); } private static boolean isStaticFinalModifier(final Field field) { final int modifiers = field.getModifiers(); return Modifier.isFinal(modifiers) && Modifier.isStatic(modifiers) || field.getDeclaringClass().equals(Character.class) && field.getName().equals("MIN_RADIX"); } private static boolean isIterable(final Object object) { return object != null && isIterable(object.getClass()); } private static boolean isIterable(final Class cls) { return Iterable.class.isAssignableFrom(cls); } @SuppressWarnings({ "unchecked", "rawtypes" }) private static Enum getEnumValue(final Object enumValueOfSourceClassloader, final Class enumTypeLoadedByTargetCL) { return Enum.valueOf((Class) enumTypeLoadedByTargetCL, enumValueOfSourceClassloader.toString()); } private Object instantiateArray(ClassLoader targetCL, Class arrayClass, Object objectToClone, boolean cloneStandardJavaTypes) { final int arrayLength = Array.getLength(objectToClone); final Object array = Array.newInstance(arrayClass.getComponentType(), arrayLength); for (int i = 0; i < arrayLength; i++) { final Object object = Array.get(objectToClone, i); final Object performClone; if (object == null) { performClone = null; } else { performClone = performClone(ClassLoaderUtil.loadClass(getType(object), targetCL), object, cloneStandardJavaTypes); } Array.set(array, i, performClone); } return array; } /** * Most of this code has been copied from the Sun14ReflectionProvider in the * XStream project. Some changes has been made, namely if the field is * static final then the {@link Unsafe#staticFieldOffset(Field)} method is * used instead of {@link Unsafe#objectFieldOffset(Field)}. * * @author Joe Walnes * @author Brian Slesinsky * @author Johan Haleby */ private static class UnsafeFieldWriter { private final static Unsafe unsafe; private final static Exception exception; static { Unsafe u = null; Exception ex = null; try { Class objectStreamClass = Class.forName("sun.misc.Unsafe"); Field unsafeField = objectStreamClass.getDeclaredField("theUnsafe"); unsafeField.setAccessible(true); u = (Unsafe) unsafeField.get(null); } catch (Exception e) { ex = e; } exception = ex; unsafe = u; } public static void write(Field field, Object object, Object value) { if (exception != null) { throw new RuntimeException("Could not set field " + object.getClass() + "." + field.getName(), exception); } try { final long offset; if (DeepCloner.isStaticFinalModifier(field)) { offset = unsafe.staticFieldOffset(field); } else { offset = unsafe.objectFieldOffset(field); } Class type = field.getType(); if (type.isPrimitive()) { if (type.equals(Integer.TYPE)) { unsafe.putInt(object, offset, ((Integer) value).intValue()); } else if (type.equals(Long.TYPE)) { unsafe.putLong(object, offset, ((Long) value).longValue()); } else if (type.equals(Short.TYPE)) { unsafe.putShort(object, offset, ((Short) value).shortValue()); } else if (type.equals(Character.TYPE)) { unsafe.putChar(object, offset, ((Character) value).charValue()); } else if (type.equals(Byte.TYPE)) { unsafe.putByte(object, offset, ((Byte) value).byteValue()); } else if (type.equals(Float.TYPE)) { unsafe.putFloat(object, offset, ((Float) value).floatValue()); } else if (type.equals(Double.TYPE)) { unsafe.putDouble(object, offset, ((Double) value).doubleValue()); } else if (type.equals(Boolean.TYPE)) { unsafe.putBoolean(object, offset, ((Boolean) value).booleanValue()); } else { throw new RuntimeException("Could not set field " + object.getClass() + "." + field.getName() + ": Unknown type " + type); } } else { unsafe.putObject(object, offset, value); } } catch (IllegalArgumentException e) { throw new RuntimeException("Could not set field " + object.getClass() + "." + field.getName(), e); } } } } ================================================ FILE: powermock-classloading/powermock-classloading-objenesis/src/test/java/powermock/classloading/ObjenesisClassloaderExecutorTest.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package powermock.classloading; import org.junit.Ignore; import org.junit.Test; import org.powermock.classloading.SingleClassloaderExecutor; import org.powermock.core.classloader.MockClassLoader; import org.powermock.core.classloader.javassist.JavassistMockClassLoader; import org.powermock.core.transformers.ClassWrapper; import org.powermock.core.transformers.MockTransformer; import org.powermock.core.transformers.support.DefaultMockTransformerChain; import powermock.classloading.classes.MyArgument; import powermock.classloading.classes.MyClass; import powermock.classloading.classes.MyEnum; import powermock.classloading.classes.MyEnumHolder; import powermock.classloading.classes.MyHierarchicalFieldHolder; import powermock.classloading.classes.MyIntegerHolder; import powermock.classloading.classes.MyPrimitiveArrayHolder; import powermock.classloading.classes.MyReferenceFieldHolder; import powermock.classloading.classes.MyReturnValue; import powermock.classloading.classes.ReflectionMethodInvoker; import java.lang.reflect.Method; import java.util.concurrent.Callable; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; @Ignore("Test are failed on JDK more that 1.6. On Travis we can run only on JDK8 and JDK9") public class ObjenesisClassloaderExecutorTest { @Test public void loadsObjectGraphInSpecifiedClassloaderAndReturnsResultInOriginalClassloader() throws Exception { MockClassLoader classloader = createClassloader(); final MyReturnValue expectedConstructorValue = new MyReturnValue(new MyArgument("first value")); final MyClass myClass = new MyClass(expectedConstructorValue); final MyArgument expected = new MyArgument("A value"); MyReturnValue[] actual = new SingleClassloaderExecutor(classloader).execute(new Callable() { public MyReturnValue[] call() throws Exception { assertEquals(JavassistMockClassLoader.class.getName(), this.getClass() .getClassLoader() .getClass() .getName()); return myClass.myMethod(expected); } }); assertFalse(MockClassLoader.class.getName().equals(this.getClass().getClassLoader().getClass().getName())); final MyReturnValue myReturnValue = actual[0]; assertEquals(expectedConstructorValue.getMyArgument().getValue(), myReturnValue.getMyArgument().getValue()); assertEquals(expected.getValue(), actual[1].getMyArgument().getValue()); } @Test public void loadsObjectGraphThatIncludesPrimitiveValuesInSpecifiedClassloaderAndReturnsResultInOriginalClassloader() throws Exception { MockClassLoader classloader = createClassloader(); final Integer expected = 42; final MyIntegerHolder myClass = new MyIntegerHolder(expected); Integer actual = new SingleClassloaderExecutor(classloader).execute(new Callable() { public Integer call() throws Exception { assertEquals(JavassistMockClassLoader.class.getName(), this.getClass() .getClassLoader() .getClass() .getName()); final int myInteger = myClass.getMyInteger(); assertEquals((int) expected, myInteger); return myInteger; } }); assertFalse(MockClassLoader.class.getName().equals(this.getClass().getClassLoader().getClass().getName())); assertEquals(expected, actual); } @Test public void loadsObjectGraphThatIncludesEnumsInSpecifiedClassloaderAndReturnsResultInOriginalClassloader() throws Exception { MockClassLoader classloader = createClassloader(); final MyEnum expected = MyEnum.MyEnum1; final MyEnumHolder myClass = new MyEnumHolder(expected); MyEnum actual = new SingleClassloaderExecutor(classloader).execute(new Callable() { public MyEnum call() throws Exception { assertEquals(JavassistMockClassLoader.class.getName(), this.getClass() .getClassLoader() .getClass() .getName()); MyEnum myEnum = myClass.getMyEnum(); assertEquals(expected, myEnum); return myEnum; } }); assertFalse(MockClassLoader.class.getName().equals(this.getClass().getClassLoader().getClass().getName())); assertEquals(expected, actual); } @Test public void loadsObjectGraphThatIncludesPrimitiveArraysInSpecifiedClassloaderAndReturnsResultInOriginalClassloader() throws Exception { MockClassLoader classloader = createClassloader(); final int[] expected = new int[]{1, 2}; final MyPrimitiveArrayHolder myClass = new MyPrimitiveArrayHolder(expected); int[] actual = new SingleClassloaderExecutor(classloader).execute(new Callable() { public int[] call() throws Exception { assertEquals(JavassistMockClassLoader.class.getName(), this.getClass() .getClassLoader() .getClass() .getName()); int[] myArray = myClass.getMyArray(); assertArrayEquals(expected, myArray); return myArray; } }); assertFalse(MockClassLoader.class.getName().equals(this.getClass().getClassLoader().getClass().getName())); assertArrayEquals(expected, actual); } @Test public void usesReferenceCloningWhenTwoFieldsPointToSameInstance() throws Exception { final MockClassLoader classloader = createClassloader(); final MyReferenceFieldHolder tested = new MyReferenceFieldHolder(); assertSame(tested.getMyArgument1(), tested.getMyArgument2()); assertSame(tested.getMyArgument1(), MyReferenceFieldHolder.MY_ARGUMENT); new SingleClassloaderExecutor(classloader).execute(new Runnable() { public void run() { assertEquals(JavassistMockClassLoader.class.getName(), this.getClass() .getClassLoader() .getClass() .getName()); assertEquals(tested.getMyArgument1(), tested.getMyArgument2()); assertEquals(tested.getMyArgument1(), MyReferenceFieldHolder.MY_ARGUMENT); assertSame(tested.getMyArgument1(), tested.getMyArgument2()); // FIXME: This assertion should work: // assertSame(tested.getMyArgument1(), MyReferenceFieldHolder.MY_ARGUMENT); } }); } @Test public void worksWithObjectHierarchy() throws Exception { final MockClassLoader classloader = createClassloader(); final MyHierarchicalFieldHolder tested = new MyHierarchicalFieldHolder(); assertSame(tested.getMyArgument1(), tested.getMyArgument2()); assertEquals(tested.getMyArgument3(), tested.getMyArgument2()); new SingleClassloaderExecutor(classloader).execute(new Runnable() { public void run() { assertEquals(JavassistMockClassLoader.class.getName(), this.getClass() .getClassLoader() .getClass() .getName()); assertSame(tested.getMyArgument1(), tested.getMyArgument2()); assertEquals(tested.getMyArgument3(), tested.getMyArgument2()); } }); } @Test public void worksWithReflection() throws Exception { final MockClassLoader classloader = createClassloader(); final MyArgument myArgument = new MyArgument("test"); final MyReturnValue instance = new MyReturnValue(myArgument); Method method = instance.getClass().getMethod("getMyArgument"); final ReflectionMethodInvoker tested = new ReflectionMethodInvoker(method, instance); new SingleClassloaderExecutor(classloader).execute(new Runnable() { public void run() { Object invoke = tested.invoke(); assertSame(invoke, myArgument); } }); } private MockClassLoader createClassloader() { MockClassLoader classloader = new JavassistMockClassLoader(new String[]{MyClass.class.getName(), MyArgument.class.getName(), MyReturnValue.class.getName()}); MockTransformer mainMockTransformer = new MockTransformer() { @Override public ClassWrapper transform(ClassWrapper clazz) throws Exception { return clazz; } }; classloader.setMockTransformerChain(DefaultMockTransformerChain.newBuilder() .append(mainMockTransformer) .build()); return classloader; } } ================================================ FILE: powermock-classloading/powermock-classloading-objenesis/src/test/java/powermock/classloading/ObjenesisDeepClonerTest.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package powermock.classloading; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.powermock.classloading.DeepCloner; import java.net.URL; import java.util.Collections; import java.util.List; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotSame; import static org.junit.Assume.assumeTrue; @Ignore("Test are failed on JDK more that 1.6. On Travis we can run only on JDK8 and JDK9") public class ObjenesisDeepClonerTest { /** * These tests crashes the JVM on version 1.8 */ @Before public void onlyRunTestsOnNonJava8Environment() throws Exception { final String property = System.getProperty("java.specification.version"); final float maximumVersion = 1.6f; assumeTrue("Current JDK version " + property + " expected is more than than " + maximumVersion, Float.valueOf(property) <= maximumVersion); } @Test public void clonesJavaInstances() throws Exception { final URL original = new URL("http://www.powermock.org"); URL clone = new DeepCloner().clone(original); assertEquals(clone, original); assertNotSame(clone, original); } @Test public void clonesUnmodifiableLists() throws Exception { final UnmodifiableListExample original = new UnmodifiableListExample(); UnmodifiableListExample clone = new DeepCloner().clone(original); assertEquals(clone, original); assertNotSame(clone, original); } @Test public void clonesArraysWithNullValues() throws Exception { Object[] original = new Object[]{"Test", null}; Object[] clone = new DeepCloner().clone(original); assertArrayEquals(clone, original); assertNotSame(clone, original); } } class UnmodifiableListExample { private List cl = Collections.singletonList(new NotSerializable()); @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((cl == null) ? 0 : cl.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } powermock.classloading.UnmodifiableListExample other = (powermock.classloading.UnmodifiableListExample) obj; if (cl == null) { if (other.cl != null) { return false; } } else if (!cl.equals(other.cl)) { return false; } return true; } } class NotSerializable { private final String state = "Nothing"; @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((state == null) ? 0 : state.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } powermock.classloading.NotSerializable other = (powermock.classloading.NotSerializable) obj; if (state == null) { if (other.state != null) { return false; } } else if (!state.equals(other.state)) { return false; } return true; } } ================================================ FILE: powermock-classloading/powermock-classloading-xstream/src/main/java/org/powermock/classloading/DeepCloner.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.classloading; import com.thoughtworks.xstream.XStream; import org.powermock.classloading.spi.DeepClonerSPI; /** *

* The purpose of the deep cloner is to create a deep clone of an object. An * object can also be cloned to a different class-loader. *

*/ public class DeepCloner implements DeepClonerSPI { private final XStream xStream; /** * Clone using the supplied ClassLoader. * @param classLoader - the classloader to loaded cloned classes. */ public DeepCloner(ClassLoader classLoader) { xStream = new XStream(); disableSecurity(); xStream.omitField(SingleClassloaderExecutor.class, "classloader"); xStream.setClassLoader(classLoader); } private void disableSecurity() { XStream.setupDefaultSecurity(xStream); xStream.allowTypesByRegExp(new String[]{".*"}); } /** * Clone using the current ContextClassLoader. */ public DeepCloner() { this(Thread.currentThread().getContextClassLoader()); } /** * Clones an object. * * @param objectToClone the object to clone. * @return A deep clone of the object to clone. */ @SuppressWarnings("unchecked") public T clone(T objectToClone) { final String serialized = xStream.toXML(objectToClone); return (T) xStream.fromXML(serialized); } } ================================================ FILE: powermock-classloading/powermock-classloading-xstream/src/test/java/powermock/classloading/XStreamClassloaderExecutorTest.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package powermock.classloading; import org.junit.Test; import org.powermock.classloading.SingleClassloaderExecutor; import org.powermock.core.classloader.MockClassLoader; import org.powermock.core.classloader.javassist.JavassistMockClassLoader; import org.powermock.core.transformers.ClassWrapper; import org.powermock.core.transformers.MockTransformer; import org.powermock.core.transformers.support.DefaultMockTransformerChain; import powermock.classloading.classes.MyArgument; import powermock.classloading.classes.MyClass; import powermock.classloading.classes.MyCollectionHolder; import powermock.classloading.classes.MyEnum; import powermock.classloading.classes.MyEnumHolder; import powermock.classloading.classes.MyHierarchicalFieldHolder; import powermock.classloading.classes.MyHierarchicalOverloadedFieldHolder; import powermock.classloading.classes.MyIntegerHolder; import powermock.classloading.classes.MyPrimitiveArrayHolder; import powermock.classloading.classes.MyReferenceFieldHolder; import powermock.classloading.classes.MyReturnValue; import powermock.classloading.classes.MyStaticFinalArgumentHolder; import powermock.classloading.classes.MyStaticFinalNumberHolder; import powermock.classloading.classes.MyStaticFinalPrimitiveHolder; import powermock.classloading.classes.ReflectionMethodInvoker; import java.lang.reflect.Method; import java.util.Collection; import java.util.LinkedList; import java.util.concurrent.Callable; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; public class XStreamClassloaderExecutorTest { @Test public void loadsObjectGraphInSpecifiedClassloaderAndReturnsResultInOriginalClassloader() throws Exception { MockClassLoader classloader = createClassloader(); final MyReturnValue expectedConstructorValue = new MyReturnValue(new MyArgument("first value")); final MyClass myClass = new MyClass(expectedConstructorValue); final MyArgument expected = new MyArgument("A value"); MyReturnValue[] actual = new SingleClassloaderExecutor(classloader).execute(new Callable() { public MyReturnValue[] call() throws Exception { assertEquals(JavassistMockClassLoader.class.getName(), this.getClass().getClassLoader().getClass().getName()); return myClass.myMethod(expected); } }); assertFalse(JavassistMockClassLoader.class.getName().equals(this.getClass().getClassLoader().getClass().getName())); final MyReturnValue myReturnValue = actual[0]; assertEquals(expectedConstructorValue.getMyArgument().getValue(), myReturnValue.getMyArgument().getValue()); assertEquals(expected.getValue(), actual[1].getMyArgument().getValue()); } @Test public void loadsObjectGraphThatIncludesPrimitiveValuesInSpecifiedClassloaderAndReturnsResultInOriginalClassloader() throws Exception { MockClassLoader classloader = createClassloader(); final Integer expected = 42; final MyIntegerHolder myClass = new MyIntegerHolder(expected); Integer actual = new SingleClassloaderExecutor(classloader).execute(new Callable() { public Integer call() throws Exception { assertEquals(JavassistMockClassLoader.class.getName(), this.getClass().getClassLoader().getClass().getName()); final int myInteger = myClass.getMyInteger(); assertEquals((int) expected, myInteger); return myInteger; } }); assertFalse(JavassistMockClassLoader.class.getName().equals(this.getClass().getClassLoader().getClass().getName())); assertEquals(expected, actual); } @Test public void loadsObjectGraphThatIncludesEnumsInSpecifiedClassloaderAndReturnsResultInOriginalClassloader() throws Exception { MockClassLoader classloader = createClassloader(); final MyEnum expected = MyEnum.MyEnum1; final MyEnumHolder myClass = new MyEnumHolder(expected); MyEnum actual = new SingleClassloaderExecutor(classloader).execute(new Callable() { public MyEnum call() throws Exception { assertEquals(JavassistMockClassLoader.class.getName(), this.getClass().getClassLoader().getClass().getName()); MyEnum myEnum = myClass.getMyEnum(); assertEquals(expected, myEnum); return myEnum; } }); assertFalse(JavassistMockClassLoader.class.getName().equals(this.getClass().getClassLoader().getClass().getName())); assertEquals(expected, actual); } @Test public void clonesStaticFinalObjectFields() throws Exception { MockClassLoader classloader = createClassloader(); final MyStaticFinalArgumentHolder expected = new MyStaticFinalArgumentHolder(); MyStaticFinalArgumentHolder actual = new SingleClassloaderExecutor(classloader) .execute(new Callable() { public MyStaticFinalArgumentHolder call() throws Exception { assertEquals(JavassistMockClassLoader.class.getName(), this.getClass().getClassLoader().getClass() .getName()); MyStaticFinalArgumentHolder actual = new MyStaticFinalArgumentHolder(); assertEquals(expected.getMyObject(), actual.getMyObject()); return actual; } }); assertFalse(JavassistMockClassLoader.class.getName().equals(this.getClass().getClassLoader().getClass().getName())); assertEquals(expected.getMyObject(), actual.getMyObject()); } @Test public void clonesStaticFinalPrimitiveFields() throws Exception { MockClassLoader classloader = createClassloader(); final MyStaticFinalPrimitiveHolder expected = new MyStaticFinalPrimitiveHolder(); MyStaticFinalPrimitiveHolder actual = new SingleClassloaderExecutor(classloader) .execute(new Callable() { public MyStaticFinalPrimitiveHolder call() throws Exception { assertEquals(JavassistMockClassLoader.class.getName(), this.getClass().getClassLoader().getClass() .getName()); MyStaticFinalPrimitiveHolder actual = new MyStaticFinalPrimitiveHolder(); assertEquals(expected.getMyInt(), actual.getMyInt()); return actual; } }); assertFalse(JavassistMockClassLoader.class.getName().equals(this.getClass().getClassLoader().getClass().getName())); assertEquals(expected.getMyInt(), actual.getMyInt()); } @Test public void clonesStaticFinalNumberFields() throws Exception { MockClassLoader classloader = createClassloader(); final MyStaticFinalNumberHolder expected = new MyStaticFinalNumberHolder(); MyStaticFinalNumberHolder actual = new SingleClassloaderExecutor(classloader) .execute(new Callable() { public MyStaticFinalNumberHolder call() throws Exception { assertEquals(JavassistMockClassLoader.class.getName(), this.getClass().getClassLoader().getClass() .getName()); MyStaticFinalNumberHolder actual = new MyStaticFinalNumberHolder(); assertEquals(expected.getMyLong(), actual.getMyLong()); return actual; } }); assertFalse(JavassistMockClassLoader.class.getName().equals(this.getClass().getClassLoader().getClass().getName())); assertEquals(expected.getMyLong(), actual.getMyLong()); } @Test public void loadsObjectGraphThatIncludesPrimitiveArraysInSpecifiedClassloaderAndReturnsResultInOriginalClassloader() throws Exception { MockClassLoader classloader = createClassloader(); final int[] expected = new int[] { 1, 2 }; final MyPrimitiveArrayHolder myClass = new MyPrimitiveArrayHolder(expected); int[] actual = new SingleClassloaderExecutor(classloader).execute(new Callable() { public int[] call() throws Exception { assertEquals(JavassistMockClassLoader.class.getName(), this.getClass().getClassLoader().getClass().getName()); int[] myArray = myClass.getMyArray(); assertArrayEquals(expected, myArray); return myArray; } }); assertFalse(JavassistMockClassLoader.class.getName().equals(this.getClass().getClassLoader().getClass().getName())); assertArrayEquals(expected, actual); } @Test public void loadsObjectGraphThatIncludesCollectionInSpecifiedClassloaderAndReturnsResultInOriginalClassloader() throws Exception { final MockClassLoader classloader = createClassloader(); final Collection expected = new LinkedList(); expected.add(new MyReturnValue(new MyArgument("one"))); expected.add(new MyReturnValue(new MyArgument("two"))); final MyCollectionHolder myClass = new MyCollectionHolder(expected); Collection actual = new SingleClassloaderExecutor(classloader).execute(new Callable>() { public Collection call() throws Exception { assertEquals(JavassistMockClassLoader.class.getName(), this.getClass().getClassLoader().getClass().getName()); Collection myCollection = myClass.getMyCollection(); for (Object object : myCollection) { assertEquals(JavassistMockClassLoader.class.getName(), object.getClass().getClassLoader().getClass() .getName()); } return myCollection; } }); assertFalse(JavassistMockClassLoader.class.getName().equals(this.getClass().getClassLoader().getClass().getName())); assertEquals(2, actual.size()); for (Object object : actual) { final String value = ((MyReturnValue) object).getMyArgument().getValue(); assertTrue(value.equals("one") || value.equals("two")); } } @Test public void usesReferenceCloningWhenTwoFieldsPointToSameInstance() throws Exception { final MockClassLoader classloader = createClassloader(); final MyReferenceFieldHolder tested = new MyReferenceFieldHolder(); assertSame(tested.getMyArgument1(), tested.getMyArgument2()); assertSame(tested.getMyArgument1(), MyReferenceFieldHolder.MY_ARGUMENT); new SingleClassloaderExecutor(classloader).execute(new Runnable() { public void run() { assertEquals(JavassistMockClassLoader.class.getName(), this.getClass().getClassLoader().getClass().getName()); assertEquals(tested.getMyArgument1(), tested.getMyArgument2()); assertEquals(tested.getMyArgument1(), MyReferenceFieldHolder.MY_ARGUMENT); assertSame(tested.getMyArgument1(), tested.getMyArgument2()); // FIXME: This assertion should work: // assertSame(tested.getMyArgument1(), MyReferenceFieldHolder.MY_ARGUMENT); } }); } @Test public void worksWithObjectHierarchy() throws Exception { final MockClassLoader classloader = createClassloader(); final MyHierarchicalFieldHolder tested = new MyHierarchicalFieldHolder(); assertSame(tested.getMyArgument1(), tested.getMyArgument2()); assertEquals(tested.getMyArgument3(), tested.getMyArgument2()); new SingleClassloaderExecutor(classloader).execute(new Runnable() { public void run() { assertEquals(JavassistMockClassLoader.class.getName(), this.getClass().getClassLoader().getClass().getName()); assertSame(tested.getMyArgument1(), tested.getMyArgument2()); assertEquals(tested.getMyArgument3(), tested.getMyArgument2()); } }); } @Test public void worksWithObjectHierarchyAndOverloadedFields() throws Exception { final MockClassLoader classloader = createClassloader(); final MyHierarchicalOverloadedFieldHolder tested = new MyHierarchicalOverloadedFieldHolder(); assertSame(tested.getMyArgument1(), tested.getMyArgument2()); assertEquals(tested.getMyArgument1(), tested.getMyArgument3()); assertSame(tested.getMyArgument3(), MyHierarchicalOverloadedFieldHolder.MY_ARGUMENT); assertNotSame(MyReferenceFieldHolder.MY_ARGUMENT, MyHierarchicalOverloadedFieldHolder.MY_ARGUMENT); assertEquals(MyReferenceFieldHolder.MY_ARGUMENT, MyHierarchicalOverloadedFieldHolder.MY_ARGUMENT); new SingleClassloaderExecutor(classloader).execute(new Runnable() { public void run() { assertEquals(JavassistMockClassLoader.class.getName(), this.getClass().getClassLoader().getClass().getName()); assertSame(tested.getMyArgument1(), tested.getMyArgument2()); assertEquals(tested.getMyArgument1(), tested.getMyArgument3()); // Note: Cannot be same using X-Stream assertEquals(tested.getMyArgument3(), MyHierarchicalOverloadedFieldHolder.MY_ARGUMENT); assertNotSame(MyReferenceFieldHolder.MY_ARGUMENT, MyHierarchicalOverloadedFieldHolder.MY_ARGUMENT); assertEquals(MyReferenceFieldHolder.MY_ARGUMENT, MyHierarchicalOverloadedFieldHolder.MY_ARGUMENT); } }); } @Test public void worksWithReflection() throws Exception { final MockClassLoader classloader = createClassloader(); final MyArgument myArgument = new MyArgument("test"); final MyReturnValue instance = new MyReturnValue(myArgument); Method method = instance.getClass().getMethod("getMyArgument"); final ReflectionMethodInvoker tested = new ReflectionMethodInvoker(method, instance); new SingleClassloaderExecutor(classloader).execute(new Runnable() { public void run() { Object invoke = tested.invoke(); assertSame(invoke, myArgument); } }); } private MockClassLoader createClassloader() { MockClassLoader classloader = new JavassistMockClassLoader(new String[] { MyClass.class.getName(), MyArgument.class.getName(), MyReturnValue.class.getName() }); MockTransformer mainMockTransformer = new MockTransformer() { @Override public ClassWrapper transform(ClassWrapper clazz) throws Exception { return clazz; } }; classloader.setMockTransformerChain(DefaultMockTransformerChain.newBuilder().append(mainMockTransformer).build()); return classloader; } } ================================================ FILE: powermock-classloading/powermock-classloading-xstream/src/test/java/powermock/classloading/XStreamDeepClonerTest.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package powermock.classloading; import org.junit.Test; import org.powermock.classloading.DeepCloner; import java.net.URL; import java.util.Collections; import java.util.List; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotSame; public class XStreamDeepClonerTest { @Test public void clonesJavaInstances() throws Exception { final URL original = new URL("http://www.powermock.org"); URL clone = new DeepCloner().clone(original); assertEquals(clone, original); assertNotSame(clone, original); } @Test public void clonesUnmodifiableLists() throws Exception { final UnmodifiableListExample original = new UnmodifiableListExample(); UnmodifiableListExample clone = new DeepCloner().clone(original); assertEquals(clone, original); assertNotSame(clone, original); } @Test public void clonesArraysWithNullValues() throws Exception { Object[] original = new Object[] { "Test", null }; Object[] clone = new DeepCloner().clone(original); assertArrayEquals(clone, original); assertNotSame(clone, original); } } class UnmodifiableListExample { private List cl = Collections.singletonList(new NotSerializable()); @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((cl == null) ? 0 : cl.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; powermock.classloading.UnmodifiableListExample other = (powermock.classloading.UnmodifiableListExample) obj; if (cl == null) { if (other.cl != null) return false; } else if (!cl.equals(other.cl)) return false; return true; } } class NotSerializable { private final String state = "Nothing"; @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((state == null) ? 0 : state.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; powermock.classloading.NotSerializable other = (powermock.classloading.NotSerializable) obj; if (state == null) { if (other.state != null) return false; } else if (!state.equals(other.state)) return false; return true; } } ================================================ FILE: powermock-core/build.gradle ================================================ ================================================ FILE: powermock-core/src/main/java/org/powermock/PowerMockInternalException.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock; public class PowerMockInternalException extends RuntimeException{ 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. "; public PowerMockInternalException(final Throwable cause) { super(MESSAGE, cause); } public PowerMockInternalException(final String message) { super(MESSAGE + message); } public PowerMockInternalException(final String message, final Throwable cause) { super(MESSAGE + message, cause); } } ================================================ FILE: powermock-core/src/main/java/org/powermock/configuration/Configuration.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.configuration; /** * The general interface for all types configurations that could be obtained via {@link GlobalConfiguration}. *

* All user defined configurations are read from the properties file: *

org/powermock/extensions/configuration.properties
*

* By default the file is not exist and default values are used. *

* * @param configuration implementer class. * @since 1.7.0 */ public interface Configuration { /** * Merge values of the configuration with values of configuration. * Values with the same keys from the configuration * overwrite value in the current configuration. * * @param configuration source configurations. * @return a new instance of {@link Configuration} with merged values. */ T merge(T configuration); } ================================================ FILE: powermock-core/src/main/java/org/powermock/configuration/ConfigurationFactory.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.configuration; public interface ConfigurationFactory { > T create(Class configurationType); } ================================================ FILE: powermock-core/src/main/java/org/powermock/configuration/ConfigurationType.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.configuration; public enum ConfigurationType { Mockito("mockito", MockitoConfiguration.class), PowerMock("powermock", PowerMockConfiguration.class); private final String prefix; private final Class configurationClass; ConfigurationType(final String prefix, final Class configurationClass) { this.prefix = prefix; this.configurationClass = configurationClass; } public String getPrefix() { return prefix; } public static ConfigurationType forClass(final Class configurationClass) { for (ConfigurationType configurationType : ConfigurationType.values()) { if (configurationType.configurationClass.isAssignableFrom(configurationClass)){ return configurationType; } } return null; } } ================================================ FILE: powermock-core/src/main/java/org/powermock/configuration/GlobalConfiguration.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.configuration; import org.powermock.configuration.support.ConfigurationFactoryImpl; /** *

* The class provides static access to {@link Configuration}. * The class uses {@link ThreadLocal} for storing of each type of configuration. * In result a one instance of each configuration type is created per thread. *

* * @since 1.7.0 */ public final class GlobalConfiguration { private static ConfigurationFactory configurationFactory = new ConfigurationFactoryImpl(); private static final ThreadLocal MOCKITO_CONFIGURATION = new ThreadLocal(); private static final ThreadLocal POWER_MOCK_CONFIGURATION = new ThreadLocal(); public static MockitoConfiguration mockitoConfiguration() { return new GlobalConfiguration().getMockitoConfiguration(); } public static PowerMockConfiguration powerMockConfiguration() { return new GlobalConfiguration().getPowerMockConfiguration(); } public static void clear() { configurationFactory = new ConfigurationFactoryImpl(); MOCKITO_CONFIGURATION.remove(); POWER_MOCK_CONFIGURATION.remove(); } public static void setConfigurationFactory(final ConfigurationFactory configurationFactory) { GlobalConfiguration.configurationFactory = configurationFactory; } private GlobalConfiguration() { if (MOCKITO_CONFIGURATION.get() == null) { MOCKITO_CONFIGURATION.set(createConfig(MockitoConfiguration.class)); } if (POWER_MOCK_CONFIGURATION.get() == null) { POWER_MOCK_CONFIGURATION.set(createConfig(PowerMockConfiguration.class)); } } private PowerMockConfiguration getPowerMockConfiguration() { return POWER_MOCK_CONFIGURATION.get(); } private MockitoConfiguration getMockitoConfiguration() { return MOCKITO_CONFIGURATION.get(); } private > T createConfig(Class configurationClass) { return configurationFactory.create(configurationClass); } } ================================================ FILE: powermock-core/src/main/java/org/powermock/configuration/MockitoConfiguration.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.configuration; public class MockitoConfiguration implements Configuration { private String mockMakerClass; public MockitoConfiguration() { // Used by configuration reader to create an instance } private MockitoConfiguration(final String mockMakerClass) { this.mockMakerClass = mockMakerClass; } public String getMockMakerClass() { return mockMakerClass; } public void setMockMakerClass(final String mockMakerClass) { this.mockMakerClass = mockMakerClass; } @Override public MockitoConfiguration merge(final MockitoConfiguration configuration) { if (configuration != null && configuration.getMockMakerClass() != null) { return new MockitoConfiguration(configuration.getMockMakerClass()); } else { return this; } } } ================================================ FILE: powermock-core/src/main/java/org/powermock/configuration/PowerMockConfiguration.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.configuration; import org.powermock.core.classloader.ByteCodeFramework; import org.powermock.utils.ArrayUtil; /** * The class provides list of setting for PowerMock. * The properties with `powermock` prefix are mapped to the class. * * @since 1.7.0 * @see Configuration */ public class PowerMockConfiguration implements Configuration { private String[] globalIgnore; private ByteCodeFramework byteCodeFramework; public String[] getGlobalIgnore() { return globalIgnore; } public void setGlobalIgnore(final String[] globalIgnore) { this.globalIgnore = globalIgnore; } public ByteCodeFramework getByteCodeFramework() { return byteCodeFramework; } public void setByteCodeFramework(final ByteCodeFramework byteCodeFramework) { this.byteCodeFramework = byteCodeFramework; } @Override public PowerMockConfiguration merge(final PowerMockConfiguration configuration) { if (configuration == null) { return this; } else { PowerMockConfiguration powerMockConfiguration = new PowerMockConfiguration(); String[] globalIgnore = ArrayUtil.mergeArrays(this.globalIgnore, configuration.globalIgnore); powerMockConfiguration.setGlobalIgnore(globalIgnore); if (configuration.byteCodeFramework == null) { powerMockConfiguration.setByteCodeFramework(byteCodeFramework); }else { powerMockConfiguration.setByteCodeFramework(configuration.byteCodeFramework); } return powerMockConfiguration; } } } ================================================ FILE: powermock-core/src/main/java/org/powermock/configuration/support/ConfigurationBuilder.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.configuration.support; import org.powermock.PowerMockInternalException; import org.powermock.configuration.Configuration; import java.util.HashMap; import java.util.Map; import java.util.Properties; class ConfigurationBuilder> { static > ConfigurationBuilder createConfigurationFor(final Class configurationType) { return new ConfigurationBuilder(configurationType); } private final Map alias; private final Class configurationType; private ConfigurationBuilder(final Class configurationType) { this.configurationType = configurationType; alias = new HashMap(); } ConfigurationBuilder withValueAlias(final String alias, final String value) { this.alias.put(alias, value); return this; } T fromFile(final String configurationLocation) { final Properties properties = new PropertiesLoader().load(configurationLocation); return fromProperties(properties); } T fromProperties(final Properties properties) { final ConfigurationCreator configurationCreator = new ConfigurationCreator(alias); return configurationCreator.create(configurationType, properties); } private static class ConfigurationCreator { private final ValueAliases alias; private ConfigurationCreator(final Map alias) { this.alias = new ValueAliases(alias); } public T create(Class configurationClass, final Properties properties) { try { T configuration = configurationClass.newInstance(); if (properties != null) { mapConfiguration(configurationClass, configuration, properties); } return configuration; } catch (Exception e) { throw new PowerMockInternalException(e); } } private void mapConfiguration(final Class configurationClass, final T configuration, final Properties properties) { new ConfigurationMapper(configurationClass, configuration, alias).map(properties); } } } ================================================ FILE: powermock-core/src/main/java/org/powermock/configuration/support/ConfigurationFactoryImpl.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.configuration.support; import org.powermock.configuration.Configuration; import org.powermock.configuration.ConfigurationFactory; import org.powermock.utils.Asserts; import java.util.Properties; import static org.powermock.configuration.support.ConfigurationBuilder.createConfigurationFor; public class ConfigurationFactoryImpl implements ConfigurationFactory { private static final String USER_CONFIGURATION = "org/powermock/extensions/configuration.properties"; private static final String DEFAULT_CONFIGURATION = "org/powermock/default.properties"; private final String userConfigurationLocation; private final String defaultConfigurationLocation; public ConfigurationFactoryImpl() { this(USER_CONFIGURATION, DEFAULT_CONFIGURATION); } ConfigurationFactoryImpl(final String userConfigurationLocation, final String defaultConfigurationLocation) { this.userConfigurationLocation = userConfigurationLocation; this.defaultConfigurationLocation = defaultConfigurationLocation; } ConfigurationFactoryImpl(final String defaultConfigurationLocation) { this(USER_CONFIGURATION, defaultConfigurationLocation); } @Override public > T create(final Class configurationType) { T environmentConfiguration = readEnvironmentConfiguration(configurationType); T configuration = readUserConfiguration(configurationType); T defaultConfiguration = readDefault(configurationType); return defaultConfiguration.merge(configuration.merge(environmentConfiguration)); } private > T readEnvironmentConfiguration(final Class configurationType) { final Properties properties = new Properties(); properties.putAll(System.getenv()); return createConfigurationFor(configurationType) .fromProperties(properties); } private T readDefault(final Class configurationType) { final T configuration = createConfigurationFor(configurationType) .fromFile(getDefaultConfigurationLocation()); Asserts.internalAssertNotNull(configuration, "Default configuration is null."); return configuration; } private T readUserConfiguration(final Class configurationType) { return createConfigurationFor(configurationType) .fromFile(getUserConfigurationLocation()); } private String getDefaultConfigurationLocation() { return defaultConfigurationLocation; } private String getUserConfigurationLocation() { return userConfigurationLocation; } } ================================================ FILE: powermock-core/src/main/java/org/powermock/configuration/support/ConfigurationMapper.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.configuration.support; import org.powermock.configuration.Configuration; import org.powermock.configuration.ConfigurationType; import org.powermock.PowerMockInternalException; import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.util.Properties; class ConfigurationMapper { private final Class configurationClass; private final T configuration; private final ValueAliases aliases; ConfigurationMapper(final Class configurationClass, final T configuration, final ValueAliases aliases) { this.configurationClass = configurationClass; this.configuration = configuration; this.aliases = aliases; } public void map(final Properties properties) { try { BeanInfo info = Introspector.getBeanInfo(configurationClass, Object.class); PropertyDescriptor[] propertyDescriptors = info.getPropertyDescriptors(); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { if (propertyDescriptor.getWriteMethod() != null) { mapProperty(propertyDescriptor, properties); } } } catch (Exception e) { throw new PowerMockInternalException(e); } } private void mapProperty(final PropertyDescriptor propertyDescriptor, final Properties properties) { final ConfigurationKey key = new ConfigurationKey(ConfigurationType.forClass(configurationClass), propertyDescriptor.getName()); final String value = aliases.findValue((String) properties.get(key.toString())); PropertyWriter.forProperty(propertyDescriptor) .writeProperty(propertyDescriptor, this.configuration, value); } private static class ConfigurationKey { private final ConfigurationType configurationType; private final String name; private ConfigurationKey(final ConfigurationType configurationType, final String name) { this.configurationType = configurationType; this.name = name; } @Override public String toString() { StringBuilder key = new StringBuilder(); if (configurationType.getPrefix() != null) { key.append(configurationType.getPrefix()); key.append("."); } for (int i = 0; i < name.length(); i++) { char c = name.charAt(i); if (Character.isUpperCase(c)) { key.append('-'); key.append(Character.toLowerCase(c)); } else { key.append(c); } } return key.toString(); } } @SuppressWarnings("unchecked") private enum PropertyWriter { ArrayWriter { @Override public void writeProperty(final PropertyDescriptor pd, final Object target, final String value) { try { if (value != null) { String[] array = value.split(","); pd.getWriteMethod().invoke(target, (Object) array); } } catch (Exception e) { throw new PowerMockInternalException(e); } } }, StringWriter { @Override public void writeProperty(final PropertyDescriptor pd, final Object target, final String value) { try { if (value != null) { pd.getWriteMethod().invoke(target, value); } } catch (Exception e) { throw new PowerMockInternalException(e); } } }, EnumWriter { @Override public void writeProperty(final PropertyDescriptor pd, final Object target, final String value) { try { if (value != null) { final Class> enumClass = (Class>) pd.getPropertyType(); final Enum[] constants = enumClass.getEnumConstants(); for (Enum constant : constants) { if(value.equals(constant.name())){ pd.getWriteMethod().invoke(target, constant); return; } } throw new PowerMockInternalException(String.format( "Find unknown enum constant `%s` for type `%s` during reading configuration.", value, enumClass )); } } catch (Exception e) { throw new PowerMockInternalException(e); } } }; private static PropertyWriter forProperty(final PropertyDescriptor pd) { if (String[].class.isAssignableFrom(pd.getPropertyType())) { return ArrayWriter; } else if (Enum.class.isAssignableFrom(pd.getPropertyType())) { return EnumWriter; } else { return StringWriter; } } abstract void writeProperty(final PropertyDescriptor propertyDescriptor, final Object target, final String value); } } ================================================ FILE: powermock-core/src/main/java/org/powermock/configuration/support/PropertiesFinder.java ================================================ package org.powermock.configuration.support; import java.io.IOException; import java.io.InputStream; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; class PropertiesFinder { private final ClassLoader classLoader; PropertiesFinder(final ClassLoader classLoader) { this.classLoader = classLoader; } List find(final String configurationFile) throws IOException, URISyntaxException { final List configurations = new ArrayList(); Enumeration resources = classLoader.getResources(configurationFile); while (resources.hasMoreElements()) { URL candidate = resources.nextElement(); configurations.add(new ConfigurationSource(candidate.getFile(), candidate.openStream())); } return configurations; } static class ConfigurationSource { private final String location; private final InputStream inputStream; ConfigurationSource(final String location, final InputStream inputStream) { this.location = location; this.inputStream = inputStream; } InputStream inputStream() { return inputStream; } String getLocation() { return location; } @Override public String toString() { return "ConfigurationSource{" + "location='" + location + '}'; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final ConfigurationSource that = (ConfigurationSource) o; return getLocation() != null ? getLocation().equals(that.getLocation()) : that.getLocation() == null; } @Override public int hashCode() { return getLocation() != null ? getLocation().hashCode() : 0; } } } ================================================ FILE: powermock-core/src/main/java/org/powermock/configuration/support/PropertiesLoader.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.configuration.support; import org.powermock.configuration.support.PropertiesFinder.ConfigurationSource; import org.powermock.utils.StringJoiner; import java.io.IOException; import java.util.List; import java.util.Properties; class PropertiesLoader { Properties load(final String propertiesFile) { if (propertiesFile == null) { return null; } final ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); try { final List configurations = new PropertiesFinder(classLoader).find(propertiesFile); return loadProperties(configurations, propertiesFile); } catch (Exception e) { return null; } } private Properties loadProperties(final List configurations, final String propertiesFile) throws IOException { if (configurations.size() == 0) { return null; } else { if (configurations.size() > 1) { printWarning(configurations, propertiesFile); } return loadPropertiesFromFile(configurations.get(0)); } } private void printWarning(final List configurations, final String propertiesFile) { System.err.printf( "Properties file %s is found in %s places: %s. Which one will be used is undefined. " + "Please, remove duplicated configuration file (or second PowerMock jar file)" + " from class path to have stable tests.", propertiesFile, configurations.size(), StringJoiner.join(configurations) ); } private Properties loadPropertiesFromFile(final ConfigurationSource configurationSource) throws IOException { final Properties properties = new Properties(); properties.load(configurationSource.inputStream()); return properties; } } ================================================ FILE: powermock-core/src/main/java/org/powermock/configuration/support/ValueAliases.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.configuration.support; import java.util.Map; class ValueAliases { private final Map alias; ValueAliases(final Map alias) {this.alias = alias;} String findValue(final String value) { if (alias.containsKey(value)) { return alias.get(value); } return value; } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/ClassLocator.java ================================================ /* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.core; public class ClassLocator extends SecurityManager { public static Class getCallerClass() { return new ClassLocator().getClassContext()[5]; } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/ClassReplicaCreator.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.core; import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; import javassist.CtConstructor; import javassist.CtField; import javassist.CtMethod; import javassist.CtNewConstructor; import javassist.CtNewMethod; import javassist.Modifier; import javassist.NotFoundException; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; /** * This class takes care of creating a replica of a class. The class structure * is copied to the new class. This is useful in situations where you want to * create a mock for a class but it's not possible because of some restrictions * (such as the class being loaded by the bootstrap class-loader). */ public class ClassReplicaCreator { private static final String POWERMOCK_INSTANCE_DELEGATOR_FIELD_NAME = "powerMockInstanceDelegatorField"; // Used to make each new replica class of a specific type unique. private static AtomicInteger counter = new AtomicInteger(0); public Class createClassReplica(Class clazz) { if (clazz == null) { throw new IllegalArgumentException("clazz cannot be null"); } ClassPool classpool = ClassPool.getDefault(); final String originalClassName = clazz.getName(); CtClass originalClassAsCtClass; final CtClass newClass = classpool.makeClass(generateReplicaClassName(clazz)); try { originalClassAsCtClass = classpool.get(originalClassName); CtMethod[] declaredMethods = originalClassAsCtClass.getDeclaredMethods(); for (CtMethod ctMethod : declaredMethods) { final String code = getReplicaMethodDelegationCode(clazz, ctMethod, null); CtNewMethod.make(ctMethod.getReturnType(), ctMethod.getName(), ctMethod.getParameterTypes(), ctMethod.getExceptionTypes(), code, newClass); } return (Class) newClass.toClass(this.getClass().getClassLoader(), this.getClass().getProtectionDomain()); } catch (Exception e) { throw new RuntimeException(e); } } /** * Create a class that is a replica of type {@code T}. To allow for * partial mocking all calls to non-mocked methods will be delegated to the * {@code delegator}. * * @param The type of the replica class to be created. * @param delegator The delegator object that will be invoked to allow for partial * mocking. * @return A replica class that can be used to duck-type an instance. */ @SuppressWarnings("unchecked") public Class createInstanceReplica(T delegator) { if (delegator == null) { throw new IllegalArgumentException("delegator cannot be null"); } final Class clazz = (Class) delegator.getClass(); ClassPool classpool = ClassPool.getDefault(); final String originalClassName = clazz.getName(); CtClass originalClassAsCtClass; final CtClass newClass = classpool.makeClass(generateReplicaClassName(clazz)); try { originalClassAsCtClass = classpool.get(originalClassName); copyFields(originalClassAsCtClass, newClass); addDelegatorField(delegator, newClass); CtMethod[] declaredMethods = originalClassAsCtClass.getDeclaredMethods(); for (CtMethod ctMethod : declaredMethods) { @SuppressWarnings("unused") final String code = getReplicaMethodDelegationCode(delegator.getClass(), ctMethod, POWERMOCK_INSTANCE_DELEGATOR_FIELD_NAME); CtMethod make2 = CtNewMethod.copy(ctMethod, newClass, null); newClass.addMethod(make2); } CtConstructor[] declaredConstructors = originalClassAsCtClass.getDeclaredConstructors(); for (CtConstructor ctConstructor : declaredConstructors) { CtConstructor copy = CtNewConstructor.copy(ctConstructor, newClass, null); newClass.addConstructor(copy); } return (Class) newClass.toClass(this.getClass().getClassLoader(), this.getClass().getProtectionDomain()); } catch (Exception e) { throw new RuntimeException(e); } } /** * Add a field to the replica class that holds the instance delegator. I.e. * if we're creating a instance replica of {@code java.lang.Long} this * methods adds a new field of type {@code delegator.getClass()} to the * replica class. */ private void addDelegatorField(T delegator, final CtClass replicaClass) throws CannotCompileException { CtField f = CtField.make(String.format("private %s %s = null;", delegator.getClass().getName(), POWERMOCK_INSTANCE_DELEGATOR_FIELD_NAME), replicaClass); replicaClass.addField(f); } private String generateReplicaClassName(final Class clazz) { return "replica." + clazz.getName() + "$$PowerMock" + counter.getAndIncrement(); } private void copyFields(CtClass originalClassAsCtClass, final CtClass newClass) throws CannotCompileException, NotFoundException { CtField[] declaredFields = originalClassAsCtClass.getDeclaredFields(); CtField[] undeclaredFields = originalClassAsCtClass.getFields(); Set allFields = new HashSet(); Collections.addAll(allFields, declaredFields); Collections.addAll(allFields, undeclaredFields); for (CtField ctField : allFields) { CtField f = new CtField(ctField.getType(), ctField.getName(), newClass); newClass.addField(f); } } /* * Invokes a instance method of the original instance. This enables partial * mocking of system classes. */ private String getReplicaMethodDelegationCode(Class clazz, CtMethod ctMethod, String classOrInstanceToDelegateTo) throws NotFoundException { StringBuilder builder = new StringBuilder(); builder.append("{java.lang.reflect.Method originalMethod = "); builder.append(clazz.getName()); builder.append(".class.getDeclaredMethod(\""); builder.append(ctMethod.getName()); builder.append("\", "); final String parametersAsString = getParametersAsString(getParameterTypes(ctMethod)); if ("".equals(parametersAsString)) { builder.append("null"); } else { builder.append(parametersAsString); } builder.append(");\n"); builder.append("originalMethod.setAccessible(true);\n"); final CtClass returnType = ctMethod.getReturnType(); final boolean isVoid = returnType.equals(CtClass.voidType); if (!isVoid) { builder.append("return ("); builder.append(returnType.getName()); builder.append(") "); } builder.append("originalMethod.invoke("); if (Modifier.isStatic(ctMethod.getModifiers()) || classOrInstanceToDelegateTo == null) { builder.append(clazz.getName()); builder.append(".class"); } else { builder.append(classOrInstanceToDelegateTo); } builder.append(", $args);}"); return builder.toString(); } private String[] getParameterTypes(CtMethod ctMethod) throws NotFoundException { final CtClass[] parameterTypesAsCtClass = ctMethod.getParameterTypes(); final String[] parameterTypes = new String[parameterTypesAsCtClass.length]; for (int i = 0; i < parameterTypes.length; i++) { parameterTypes[i] = parameterTypesAsCtClass[i].getName() + ".class"; } return parameterTypes; } private static String getParametersAsString(String[] types) { StringBuilder parametersAsString = new StringBuilder(); if (types != null && types.length == 0) { parametersAsString.append("new Class[0]"); } else { parametersAsString.append("new Class[] {"); if (types != null) { for (int i = 0; i < types.length; i++) { parametersAsString.append(types[i]); if (i != types.length - 1) { parametersAsString.append(", "); } } } parametersAsString.append("}"); } return parametersAsString.toString(); } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/ConcreteClassGenerator.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.core; import javassist.ClassPool; import javassist.CtClass; import javassist.CtConstructor; import javassist.CtMethod; import javassist.CtNewMethod; import javassist.Modifier; import javassist.NotFoundException; import org.powermock.reflect.internal.TypeUtils; import java.util.concurrent.atomic.AtomicInteger; /** * This class takes care of creating a concrete sub-class implementing all * abstract methods in the parent. */ public class ConcreteClassGenerator { // Used to make each new subclass of a specific type unique. private static AtomicInteger counter = new AtomicInteger(0); public Class createConcreteSubClass(Class clazz) { if (clazz == null) { throw new IllegalArgumentException("clazz cannot be null"); } if (!java.lang.reflect.Modifier.isAbstract(clazz.getModifiers())) { throw new IllegalArgumentException("clazz must be abstract"); } ClassPool classpool = ClassPool.getDefault(); final String originalClassName = clazz.getName(); final CtClass originalClassAsCtClass; final CtClass newClass = classpool.makeClass(generateClassName(clazz)); try { newClass.setSuperclass(classpool.get(clazz.getName())); } catch (Exception e1) { throw new RuntimeException(e1); } try { originalClassAsCtClass = classpool.get(originalClassName); CtMethod[] declaredMethods = originalClassAsCtClass.getDeclaredMethods(); for (CtMethod ctMethod : declaredMethods) { if (Modifier.isAbstract(ctMethod.getModifiers())) { final String code = getReturnCode(ctMethod.getReturnType()); CtNewMethod.make(ctMethod.getReturnType(), ctMethod.getName(), ctMethod.getParameterTypes(), ctMethod.getExceptionTypes(), code, newClass); } } if (!hasInheritableConstructor(originalClassAsCtClass)) { return null; } return newClass.toClass(this.getClass().getClassLoader(), this.getClass().getProtectionDomain()); } catch (Exception e) { throw new RuntimeException(e); } } private boolean hasInheritableConstructor(CtClass cls) throws NotFoundException { CtConstructor[] constructors = cls.getDeclaredConstructors(); if (constructors.length == 0) { return true; } for (CtConstructor ctConstructor : constructors) { int modifiers = ctConstructor.getModifiers(); if (!Modifier.isPackage(modifiers) && !Modifier.isPrivate(modifiers)) { return true; } } return false; } private String getReturnCode(CtClass returnType) { if (returnType.equals(CtClass.voidType)) { return "{}"; } return "{return " + TypeUtils.getDefaultValueAsString(returnType.getName()) + ";}"; } private String generateClassName(final Class clazz) { return "subclass." + clazz.getName() + "$$PowerMock" + counter.getAndIncrement(); } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/DefaultFieldValueGenerator.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.core; import org.powermock.reflect.Whitebox; import org.powermock.reflect.internal.TypeUtils; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.net.Inet4Address; import java.net.InetAddress; import java.util.Set; /** * Fills the fields with default not-null values. If a field type is an * interface a proxy returning default values for each method will be created. * If it's an abstract class a new concrete implementation of that type will * created and instantiated at run-time. *

* There are two scenarios where a field-type cannot possibly be assigned. *

    *
  1. * When a class contains a field of it's own type, which would lead to infinite * recursion, {@code null} is assigned.
  2. *
  3. When the field type is an abstract Java system class with no visible * constructor (package-private) {@code null} is assigned.
  4. *
*/ public class DefaultFieldValueGenerator { public static T fillWithDefaultValues(T object) { if (object == null) { throw new IllegalArgumentException("object to fill cannot be null"); } Set allInstanceFields = Whitebox.getAllInstanceFields(object); for (Field field : allInstanceFields) { final Class fieldType = field.getType(); Object defaultValue = TypeUtils.getDefaultValue(fieldType); if (defaultValue == null && fieldType != object.getClass() && !field.isSynthetic()) { defaultValue = instantiateFieldType(field); if (defaultValue != null) { fillWithDefaultValues(defaultValue); } } try { field.set(object, defaultValue); } catch (Exception e) { throw new RuntimeException("Internal error: Failed to set field.", e); } } return object; } private static Object instantiateFieldType(Field field) { Class fieldType = field.getType(); Object defaultValue; int modifiers = fieldType.getModifiers(); if(fieldType.isAssignableFrom(ClassLoader.class) || isClass(fieldType)) { defaultValue = null; } else if (Modifier.isAbstract(modifiers) && !Modifier.isInterface(modifiers) && !fieldType.isArray()) { Class createConcreteSubClass = new ConcreteClassGenerator().createConcreteSubClass(fieldType); defaultValue = createConcreteSubClass == null ? null : Whitebox.newInstance(createConcreteSubClass); } else { fieldType = substituteKnownProblemTypes(fieldType); defaultValue = Whitebox.newInstance(fieldType); } return defaultValue; } private static boolean isClass(Class fieldType) { return fieldType == Class.class; } /** * Substitute class types that are known to cause problems when generating * them. * * @param fieldType the field type. * @return A field-type substitute or the original class. */ private static Class substituteKnownProblemTypes(Class fieldType) { /* * InetAddress has a private constructor and is normally not * constructable without reflection. It's no problem instantiating this * class using reflection or with Whitebox#newInstance but the problem * lies in the equals method since it _always_ returns false even though * it's the same instance! So in cases where classes containing an * InetAddress field and uses it in the equals method (such as * java.net.URL) then may return false since InetAddress#equals() * returns false all the time. As a work-around we return an * Inet4Address instead which has a proper equals method. */ if (fieldType == InetAddress.class) { return Inet4Address.class; } return fieldType; } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/IdentityHashSet.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.core; import java.util.AbstractSet; import java.util.Iterator; import java.util.Map; public class IdentityHashSet extends AbstractSet { protected final Map backedMap; public IdentityHashSet() { this.backedMap = new ListMap(); } @Override public int size() { return backedMap.size(); } @Override public boolean contains(Object o) { return backedMap.containsKey(o); } @Override public boolean add(E o) { return backedMap.put(o, Boolean.TRUE) == null; } @Override public Iterator iterator() { return backedMap.keySet().iterator(); } @Override public boolean remove(Object o) { return backedMap.remove(o) != null; } @Override public void clear() { backedMap.clear(); } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/IndicateReloadClass.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.core; public class IndicateReloadClass { } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/InvocationException.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core; public class InvocationException extends RuntimeException { public InvocationException(final Throwable cause) { super(cause); } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/ListMap.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.core; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; public class ListMap implements Map { private List> entries = new LinkedList>(); private static class SimpleEntry implements Entry { private K key; private V value; public SimpleEntry(K key, V value) { this.key = key; this.value = value; } @Override public K getKey() { return key; } @Override public V getValue() { return value; } @Override public V setValue(V value) { V old = this.value; this.value = value; return old; } } @Override public V remove(Object key) { for (Iterator> i = entries.iterator(); i.hasNext();) { Map.Entry entry = i.next(); if (entry.getKey() == key) { i.remove(); return entry.getValue(); } } return null; } @Override public void clear() { entries.clear(); } @Override public V get(Object key) { for (Entry entry : entries) { if (entry.getKey() == key) { return entry.getValue(); } } return null; } @Override public V put(K key, V value) { for (Entry entry : entries) { if (entry.getKey() == key) { return entry.setValue(value); } } Map.Entry entry = new SimpleEntry(key, value); entries.add(entry); return null; } @Override public boolean containsKey(Object key) { return get(key) != null; } @Override public boolean containsValue(Object value) { for (Entry entry : entries) { if (entry.getValue() == value) { return true; } } return false; } @Override public Set> entrySet() { throw new UnsupportedOperationException(); } @Override public boolean isEmpty() { return entries.isEmpty(); } @Override public Set keySet() { Set identityHashSet = new HashSet(); for (Map.Entry entry : entries) { identityHashSet.add(entry.getKey()); } return identityHashSet; } @Override @SuppressWarnings("unchecked") public void putAll(Map t) { Set entrySet = t.entrySet(); for (Object object : entrySet) { entries.add((java.util.Map.Entry) object); } } @Override public int size() { return entries.size(); } @Override public Collection values() { Set hashSet = new HashSet(); for (Map.Entry entry : entries) { hashSet.add(entry.getValue()); } return hashSet; } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/MockGateway.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.core; import org.powermock.core.spi.MethodInvocationControl; import org.powermock.core.spi.NewInvocationControl; import org.powermock.reflect.internal.TypeUtils; import org.powermock.reflect.internal.WhiteboxImpl; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Modifier; /** * All mock invocations are routed through this gateway. This includes method * calls, construction of new instances and more. Do not use this class * directly, but always go through the PowerMock facade. */ public class MockGateway { /** * {@link #noMockito} is wrapped into it's own static class to make sure it is initialized not earlier than * {@link #calledFromMockito()} is called for the first time. */ private static final class NoMockito { static final boolean noMockito = Package.getPackage("org.mockito") == null; private NoMockito() {} } public static final Object PROCEED = new Object(); public static final Object SUPPRESS = new Object(); /** * Used to tell the MockGateway that the next call should not be mocked * regardless if a {@link MethodInvocationControl} is found in the * {@link MockRepository}. Used to allow for e.g. recursive partial mocking. */ public static final String DONT_MOCK_NEXT_CALL = "DontMockNextCall"; /** * Tells PowerMock to mock standard methods. These are * {@link Object#toString()}, {@link Object#hashCode()} and * {@link Object#equals(Object)}. By default this is {@code true}. */ public static boolean MOCK_STANDARD_METHODS = true; @SuppressWarnings("UnusedDeclaration") public static Object newInstanceCall(Class type, Object[] args, Class[] sig) throws Throwable { final NewInvocationControl newInvocationControl = MockRepository.getNewInstanceControl(type); if (newInvocationControl != null) { /* * We need to deal with inner, local and anonymous inner classes * specifically. For example when new is invoked on an inner class * it seems like null is passed as an argument even though it * shouldn't. We correct this here. * * Seems with Javassist 3.17.1-GA & Java 7, the 'null' is passed as the last argument. */ if (type.isMemberClass() && Modifier.isStatic(type.getModifiers())) { if (args.length > 0 && ((args[0] == null && sig[0].getCanonicalName() == null) || (args[args.length - 1] == null && sig[args.length - 1].getCanonicalName() == null)) && sig.length > 0) { args = copyArgumentsForInnerOrLocalOrAnonymousClass(args, sig[0], false); } } else if (type.isLocalClass() || type.isAnonymousClass() || type.isMemberClass()) { if (args.length > 0 && sig.length > 0 && sig[0].equals(type.getEnclosingClass())) { args = copyArgumentsForInnerOrLocalOrAnonymousClass(args, sig[0], true); } } return newInvocationControl.invoke(type, args, sig); } // Check if we should suppress the constructor code if (MockRepository.shouldSuppressConstructor(WhiteboxImpl.getConstructor(type, sig))) { return WhiteboxImpl.getFirstParentConstructor(type); } return PROCEED; } @SuppressWarnings("UnusedDeclaration") public static Object fieldCall(Object instanceOrClassContainingTheField, Class classDefiningField, String fieldName, Class fieldType) { if (MockRepository.shouldSuppressField(WhiteboxImpl.getField(classDefiningField, fieldName))) { return TypeUtils.getDefaultValue(fieldType); } return PROCEED; } public static Object staticConstructorCall(String className) { if (MockRepository.shouldSuppressStaticInitializerFor(className)) { return "suppress"; } return PROCEED; } @SuppressWarnings("UnusedDeclaration") public static Object constructorCall(Class type, Object[] args, Class[] sig) throws Throwable { final Constructor constructor = WhiteboxImpl.getConstructor(type, sig); if (MockRepository.shouldSuppressConstructor(constructor)) { return null; } return PROCEED; } public static boolean suppressConstructorCall(Class type, Object[] args, Class[] sig) throws Throwable { return constructorCall(type, args, sig) != PROCEED; } /** * Tells PowerMock whether or not to mock * {@link java.lang.Object#getClass()}. */ public static boolean MOCK_GET_CLASS_METHOD = false; /** * Tells PowerMock whether or not to mock * {@link java.lang.Class#isAnnotationPresent(Class)} and * {@link java.lang.Class#getAnnotation(Class)}. */ public static boolean MOCK_ANNOTATION_METHODS = false; // used for instance methods @SuppressWarnings("UnusedDeclaration") public static Object methodCall(Object instance, String methodName, Object[] args, Class[] sig, String returnTypeAsString) throws Throwable { return doMethodCall(instance, methodName, args, sig, returnTypeAsString); } // used for static methods @SuppressWarnings("UnusedDeclaration") public static Object methodCall(Class type, String methodName, Object[] args, Class[] sig, String returnTypeAsString) throws Throwable { return doMethodCall(type, methodName, args, sig, returnTypeAsString); } private static Object doMethodCall(Object object, String methodName, Object[] args, Class[] sig, String returnTypeAsString) throws Throwable { if (!shouldMockMethod(methodName, sig)) { return PROCEED; } MockInvocation mockInvocation = new MockInvocation(object, methodName, sig); MethodInvocationControl methodInvocationControl = mockInvocation.getMethodInvocationControl(); Object returnValue = null; // The following describes the equals non-static method. if (isEqualsMethod(mockInvocation) && !isStaticMethod(mockInvocation)) { returnValue = tryHandleEqualsMethod(mockInvocation); } if (returnValue != null) { return returnValue; } return doMethodCall(object, args, returnTypeAsString, mockInvocation, methodInvocationControl); } private static Object doMethodCall(Object object, Object[] args, String returnTypeAsString, MockInvocation mockInvocation, MethodInvocationControl methodInvocationControl) throws Throwable { Object returnValue; // At first should be checked that method not suppressed/stubbed, because otherwise for spies real // method is involved. // https://github.com/jayway/powermock/issues/327 if (MockRepository.shouldSuppressMethod(mockInvocation.getMethod(), mockInvocation.getObjectType())) { returnValue = TypeUtils.getDefaultValue(returnTypeAsString); } else if (MockRepository.shouldStubMethod(mockInvocation.getMethod())) { returnValue = MockRepository.getMethodToStub(mockInvocation.getMethod()); } else if (methodInvocationControl != null && methodInvocationControl.isMocked(mockInvocation.getMethod()) && shouldMockThisCall()) { returnValue = methodInvocationControl.invoke(object, mockInvocation.getMethod(), args); if (returnValue == SUPPRESS) { returnValue = TypeUtils.getDefaultValue(returnTypeAsString); } } else if (MockRepository.hasMethodProxy(mockInvocation.getMethod())) { /* * We must temporary remove the method proxy when invoking the * invocation handler because if the invocation handler delegates * the call we will end up here again and we'll get a * StackOverflowError. */ final InvocationHandler invocationHandler = MockRepository.removeMethodProxy(mockInvocation.getMethod()); try { returnValue = invocationHandler.invoke(object, mockInvocation.getMethod(), args); } finally { // Set the method proxy again after the invocation MockRepository.putMethodProxy(mockInvocation.getMethod(), invocationHandler); } } else { returnValue = PROCEED; } return returnValue; } /* * Method handles exception cases with equals method. */ private static Object tryHandleEqualsMethod(MockInvocation mockInvocation) { // Fix for Issue http://code.google.com/p/powermock/issues/detail?id=88 // For some reason the method call to equals() on final methods is // intercepted and during the further processing in Mockito the same // equals() method is called on the same instance. A StackOverflowError // is the result. The following fix changes this by checking if the // method to be called is a final equals() method. In that case the // original method is called by returning PROCEED. if (mockInvocation.getMethod().getParameterTypes().length == 1 && mockInvocation.getMethod().getParameterTypes()[0] == Object.class && Modifier.isFinal(mockInvocation.getMethod().getModifiers())) { return PROCEED; } if (calledFromMockito()){ return PROCEED; } return null; } private static boolean isEqualsMethod(MockInvocation mockInvocation) { return "equals".equals(mockInvocation.getMethod().getName()); } private static boolean isStaticMethod(MockInvocation mockInvocation) { return Modifier.isStatic(mockInvocation.getMethod().getModifiers()); } private static boolean calledFromMockito() { if (NoMockito.noMockito) { return false; } StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); for (StackTraceElement stackTraceElement : stackTrace) { if (stackTraceElement.getClassName().startsWith("org.mockito.")){ return true; } } return false; } private static boolean shouldMockMethod(String methodName, Class[] sig) { if (isJavaStandardMethod(methodName, sig) && !MOCK_STANDARD_METHODS) { return false; } else if (isGetClassMethod(methodName, sig) && !MOCK_GET_CLASS_METHOD) { return false; } else { return !(isAnnotationMethod(methodName, sig) && !MOCK_ANNOTATION_METHODS); } } private static boolean isJavaStandardMethod(String methodName, Class[] sig) { return (methodName.equals("equals") && sig.length == 1) || (methodName.equals("hashCode") && sig.length == 0) || (methodName.equals("toString") && sig.length == 0); } private static boolean isGetClassMethod(String methodName, Class[] sig) { return methodName.equals("getClass") && sig.length == 0; } private static boolean isAnnotationMethod(String methodName, Class[] sig) { return (methodName.equals("isAnnotationPresent") && sig.length == 1) || (methodName.equals("getAnnotation") && sig.length == 1); } private static boolean shouldMockThisCall() { Object shouldSkipMockingOfNextCall = MockRepository.getAdditionalState(DONT_MOCK_NEXT_CALL); final boolean shouldMockThisCall = shouldSkipMockingOfNextCall == null; MockRepository.removeAdditionalState(DONT_MOCK_NEXT_CALL); return shouldMockThisCall; } /** * The first parameter of an inner, local or anonymous inner class is * {@code null} or the enclosing instance. This should not be included * in the substitute invocation since it is never expected by the user. *

* Seems with Javassist 3.17.1-GA & Java 7, the '{@code null}' is passed as the last argument. */ private static Object[] copyArgumentsForInnerOrLocalOrAnonymousClass(Object[] args, Class sig, boolean excludeEnclosingInstance) { Object[] newArgs = new Object[args.length - 1]; final int start; final int end; int j = 0; if ((args[0] == null && sig == null)|| excludeEnclosingInstance) { start = 1; end = args.length; } else { start = 0; end = args.length - 1; } for (int i = start; i < end; i++) { newArgs[j++] = args[i]; } args = newArgs; return args; } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/MockInvocation.java ================================================ package org.powermock.core; import org.powermock.core.spi.MethodInvocationControl; import org.powermock.reflect.exceptions.MethodNotFoundException; import org.powermock.reflect.internal.WhiteboxImpl; import org.powermock.reflect.internal.proxy.UnproxiedType; import java.lang.reflect.Method; class MockInvocation { private Object object; private String methodName; private Class[] sig; private Class objectType; private MethodInvocationControl methodInvocationControl; private Method method; MockInvocation(Object object, String methodName, Class... sig) { this.object = object; this.methodName = methodName; this.sig = sig; init(); } private void init() { if (object instanceof Class) { objectType = (Class) object; methodInvocationControl = MockRepository.getStaticMethodInvocationControl(objectType); } else { final Class type = object.getClass(); UnproxiedType unproxiedType = WhiteboxImpl.getUnproxiedType(type); objectType = unproxiedType.getOriginalType(); methodInvocationControl = MockRepository.getInstanceMethodInvocationControl(object); } method = findMethodToInvoke(methodName, sig, objectType); } Class getObjectType() { return objectType; } MethodInvocationControl getMethodInvocationControl() { return methodInvocationControl; } Method getMethod() { return method; } private static Method findMethodToInvoke(String methodName, Class[] sig, Class objectType) { /* * if invocationControl is null or the method is not mocked, invoke * original method or suppress the method code otherwise invoke the * invocation handler. */ Method method; try { method = WhiteboxImpl.getBestMethodCandidate(objectType, methodName, sig, true); } catch (MethodNotFoundException e) { /* * Dirty hack to get around issue 110 * (http://code.google.com/p/powermock/issues/detail?id=110). Review * this! What we do here is to try to find a reflective method on * class. This has begun to fail since version 1.2 when we supported * mocking static methods in system classes. */ try { method = WhiteboxImpl.getMethod(Class.class, methodName, sig); } catch (MethodNotFoundException e2) { throw e; } } return method; } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/MockRepository.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.core; import org.powermock.core.spi.MethodInvocationControl; import org.powermock.core.spi.NewInvocationControl; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * Hold mock objects that should be used instead of the concrete implementation. * Mock transformers may use this class to gather information on which classes * and methods that are mocked. */ public class MockRepository { private static Set objectsToAutomaticallyReplayAndVerify = new IdentityHashSet(); private static Map, NewInvocationControl> newSubstitutions = new HashMap, NewInvocationControl>(); /** * Holds info about general method invocation mocks for classes. */ private static Map, MethodInvocationControl> classMocks = new HashMap, MethodInvocationControl>(); /** * Holds info about general method invocation mocks for instances. */ private static Map instanceMocks = new ListMap(); /** * Holds info about which methods that should return a substitute/another * instance instead of the default instance. */ private static Map substituteReturnValues = new HashMap(); /** * Holds info about which methods that are proxied. */ private static Map methodProxies = new HashMap(); /** * Holds info about which class that should have their static initializers * suppressed. */ private static Set suppressStaticInitializers = new HashSet(); /** * Sometimes mock frameworks needs to store additional state. They can do * this using this key/value based approach. */ private static Map additionalState = new HashMap(); /** * Set of constructors that should be suppressed. */ private static final Set> suppressConstructor = new HashSet>(); /** * Set of methods that should be suppressed. */ private static final Set suppressMethod = new HashSet(); /** * Set of methods that should be suppressed. */ private static final Set suppressField = new HashSet(); /** * Set of field types that should always be suppressed regardless of * instance. */ private static final Set suppressFieldTypes = new HashSet(); /** * Set of runnables that will be executed after the test (method) is completed. */ private static final Set afterMethodRunners = new HashSet(); /** * Clear all state of the mock repository except for static initializers. * The reason for not clearing static initializers is that when running in a * suite with many tests the clear method is invoked after each test. This * means that before the test that needs to suppress the static initializer * has been reach the state of the MockRepository would have been wiped out. * This is generally not a problem because most state will be added again * but suppression of static initializers are different because this state * can only be set once per class per CL. That's why we cannot remove this * state. */ public synchronized static void clear() { newSubstitutions.clear(); classMocks.clear(); instanceMocks.clear(); objectsToAutomaticallyReplayAndVerify.clear(); additionalState.clear(); suppressConstructor.clear(); suppressMethod.clear(); substituteReturnValues.clear(); suppressField.clear(); suppressFieldTypes.clear(); methodProxies.clear(); for (Runnable runnable : afterMethodRunners) { runnable.run(); } afterMethodRunners.clear(); } /** * Removes an object from the MockRepository if it exists. */ public static void remove(Object mock) { if (mock instanceof Class) { if (newSubstitutions.containsKey(mock)) { newSubstitutions.remove(mock); } if (classMocks.containsKey(mock)) { classMocks.remove(mock); } } else if (instanceMocks.containsKey(mock)) { instanceMocks.remove(mock); } } public static synchronized MethodInvocationControl getStaticMethodInvocationControl(Class type) { return classMocks.get(type); } public static synchronized MethodInvocationControl putStaticMethodInvocationControl(Class type, MethodInvocationControl invocationControl) { return classMocks.put(type, invocationControl); } public static synchronized MethodInvocationControl removeClassMethodInvocationControl(Class type) { return classMocks.remove(type); } public static synchronized MethodInvocationControl getInstanceMethodInvocationControl(Object instance) { return instanceMocks.get(instance); } public static synchronized MethodInvocationControl putInstanceMethodInvocationControl(Object instance, MethodInvocationControl invocationControl) { return instanceMocks.put(instance, invocationControl); } public static synchronized MethodInvocationControl removeInstanceMethodInvocationControl(Class type) { return classMocks.remove(type); } public static synchronized NewInvocationControl getNewInstanceControl(Class type) { return newSubstitutions.get(type); } public static synchronized NewInvocationControl putNewInstanceControl(Class type, NewInvocationControl control) { return newSubstitutions.put(type, control); } /** * Add a fully qualified class name for a class that should have its static * initializers suppressed. * * @param className * The fully qualified class name for a class that should have * its static initializers suppressed. */ public static synchronized void addSuppressStaticInitializer(String className) { suppressStaticInitializers.add(className); } /** * Remove a fully qualified class name for a class that should no longer * have its static initializers suppressed. * * @param className * The fully qualified class name for a class that should no * longer have its static initializers suppressed. */ public static synchronized void removeSuppressStaticInitializer(String className) { suppressStaticInitializers.remove(className); } /** * Check whether or not a class with the fully qualified name should have * its static initializers suppressed. * * @param className * {@code true} if class with the fully qualified name * {@code className} should have its static initializers * suppressed, {@code false} otherwise. */ public static synchronized boolean shouldSuppressStaticInitializerFor(String className) { return suppressStaticInitializers.contains(className); } /** * @return All classes that should be automatically replayed or verified. */ public static synchronized Set getObjectsToAutomaticallyReplayAndVerify() { return Collections.unmodifiableSet(objectsToAutomaticallyReplayAndVerify); } /** * Add classes that should be automatically replayed or verified. */ public static synchronized void addObjectsToAutomaticallyReplayAndVerify(Object... objects) { Collections.addAll(objectsToAutomaticallyReplayAndVerify, objects); } /** * When a mock framework API needs to store additional state not applicable * for the other methods, it may use this method to do so. * * @param key * The key under which the value is stored. * @param value * The value to store under the specified key. * @return The previous object under the specified key or * {@code null}. */ public static synchronized Object putAdditionalState(String key, Object value) { return additionalState.put(key, value); } public static synchronized Object removeAdditionalState(String key) { return additionalState.remove(key); } public static synchronized InvocationHandler removeMethodProxy(Method method) { return methodProxies.remove(method); } /** * Retrieve state based on the supplied key. */ @SuppressWarnings("unchecked") public static synchronized T getAdditionalState(String key) { return (T) additionalState.get(key); } /** * Add a method to suppress. * * @param method * The method to suppress. */ public static synchronized void addMethodToSuppress(Method method) { suppressMethod.add(method); } /** * Add a field to suppress. * * @param field * The field to suppress. */ public static synchronized void addFieldToSuppress(Field field) { suppressField.add(field); } /** * Add a field type to suppress. All fields of this type will be suppressed. * * @param fieldType * The fully-qualified name to a type. All fields of this type * will be suppressed. */ public static synchronized void addFieldTypeToSuppress(String fieldType) { suppressFieldTypes.add(fieldType); } /** * Add a constructor to suppress. * * @param constructor * The constructor to suppress. */ public static synchronized void addConstructorToSuppress(Constructor constructor) { suppressConstructor.add(constructor); } /** * @return {@code true} if the method should be proxied. */ public static synchronized boolean hasMethodProxy(Method method) { return methodProxies.containsKey(method); } /** * @return {@code true} if the method should be suppressed. */ public static synchronized boolean shouldSuppressMethod(Method method, Class objectType) throws ClassNotFoundException { for (Method suppressedMethod : suppressMethod) { Class suppressedMethodClass = suppressedMethod .getDeclaringClass(); if (suppressedMethodClass.getClass().isAssignableFrom( objectType.getClass()) && suppressedMethod.getName().equals(method.getName()) && ClassLocator.getCallerClass().getName() .equals(suppressedMethodClass.getName())) { return true; } } return false; } /** * @return {@code true} if the field should be suppressed. */ public static synchronized boolean shouldSuppressField(Field field) { return suppressField.contains(field) || suppressFieldTypes.contains(field.getType().getName()); } /** * @return {@code true} if the constructor should be * suppressed. */ public static synchronized boolean shouldSuppressConstructor(Constructor constructor) { return suppressConstructor.contains(constructor); } /** * @return {@code true} if the method has a substitute return * value. */ public static synchronized boolean shouldStubMethod(Method method) { return substituteReturnValues.containsKey(method); } /** * @return The substitute return value for a particular method, may be * {@code null}. */ public static synchronized Object getMethodToStub(Method method) { return substituteReturnValues.get(method); } /** * Set a substitute return value for a method. Whenever this method will be * called the {@code value} will be returned instead. * * @return The previous substitute value if any. */ public static synchronized Object putMethodToStub(Method method, Object value) { return substituteReturnValues.put(method, value); } /** * @return The proxy for a particular method, may be {@code null}. */ public static synchronized InvocationHandler getMethodProxy(Method method) { return methodProxies.get(method); } /** * Set a proxy for a method. Whenever this method is called the invocation * handler will be invoked instead. * * @return The method proxy if any. */ public static synchronized InvocationHandler putMethodProxy(Method method, InvocationHandler invocationHandler) { return methodProxies.put(method, invocationHandler); } /** * Add a {@link Runnable} that will be executed after each test * @param runnable - an instance of {@link Runnable} that will be executed. */ public static synchronized void addAfterMethodRunner(Runnable runnable) { afterMethodRunners.add(runnable); } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/PowerMockUtils.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.core; import java.lang.reflect.Field; import java.util.Iterator; import java.util.Vector; public class PowerMockUtils { /** * Get an iterator of all classes loaded by the specific classloader. * * @param classLoader the class loader for that iterator with all loaded classes should be created. * @return the iterator with all classes loaded by the given {@code classLoader} * @throws NoSuchFieldException * @throws IllegalAccessException */ @SuppressWarnings("unchecked") public static Iterator> getClassIterator(ClassLoader classLoader) throws NoSuchFieldException, IllegalAccessException { Class classLoaderClass = classLoader.getClass(); while (classLoaderClass != ClassLoader.class) { classLoaderClass = classLoaderClass.getSuperclass(); } Field classesField = classLoaderClass.getDeclaredField("classes"); classesField.setAccessible(true); Vector> classes = (Vector>) classesField.get(classLoader); return classes.iterator(); } /** * * @param classLoader the class loader for that classes is printed. * @throws NoSuchFieldException * @throws IllegalAccessException */ public static void printClassesLoadedByClassloader(ClassLoader classLoader, boolean includeParent) throws NoSuchFieldException, IllegalAccessException { while (classLoader != null) { System.out.println("ClassLoader: " + classLoader); for (Iterator iter = PowerMockUtils.getClassIterator(classLoader); iter.hasNext();) { System.out.println("\t" + iter.next()); } if (includeParent) { classLoader = classLoader.getParent(); } else { classLoader = null; } } } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/WildcardMatcher.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.core; import java.util.Collection; /** * Wildcard matcher. */ public class WildcardMatcher { private static final char WILDCARD = '*'; /** * Performs a wildcard matching for the text and pattern provided. * * @param text * the text to be tested for matches. * * @param pattern * the pattern to be matched for. This can contain the wildcard * character '*' (asterisk). * * @return true if a match is found, false otherwise. */ public static boolean matches(String text, String pattern) { if (text == null) { throw new IllegalArgumentException("text cannot be null"); } text += '\0'; pattern += '\0'; int N = pattern.length(); boolean[] states = new boolean[N + 1]; boolean[] old = new boolean[N + 1]; old[0] = true; for (int i = 0; i < text.length(); i++) { char c = text.charAt(i); states = new boolean[N + 1]; // initialized to false for (int j = 0; j < N; j++) { char p = pattern.charAt(j); // hack to handle *'s that match 0 characters if (old[j] && (p == WILDCARD)) old[j + 1] = true; if (old[j] && (p == c)) states[j + 1] = true; if (old[j] && (p == WILDCARD)) states[j] = true; if (old[j] && (p == WILDCARD)) states[j + 1] = true; } old = states; } return states[N]; } public static boolean matchesAny(Collection patterns, String text) { for (String pattern : patterns) { if (matches(text, pattern)) { return true; } } return false; } public static boolean matchesAny(Iterable patterns, String text) { for (String string : patterns) { if (matches(text, string)) { return true; } } return false; } public static boolean matchesAny(String[] patterns, String text) { for (String string : patterns) { if (matches(text, string)) { return true; } } return false; } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/agent/JavaAgentClassRegister.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.agent; /** * This register contains information about which class has been modified by PowerMock Java Agent. */ public interface JavaAgentClassRegister { /** * Check if class with {@code className} has been modified for the given class loader * @param classLoader - {@link ClassLoader} for that class should be checked * @param className - name of class * @return {@code true} if the given class has been modified, otherwise {@code false} */ boolean isModifiedByAgent(ClassLoader classLoader, String className); /** * Register that the class with name {@code className} has been modified for the given class loader. * @param loader - {@link ClassLoader} for that class has been modified. * @param className - name of the class which has been modified. */ void registerClass(ClassLoader loader, String className); /** * Remove all registered classes for all class loaders. */ void clear(); } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/agent/JavaAgentFrameworkRegister.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.agent; /** * Instance of class should set/clear an instance of the JavaAgentClassRegister * in Mockito Frameworks classes */ public interface JavaAgentFrameworkRegister { /** * Set the {@code javaAgentClassRegister} to current loaded mocking framework. * @param javaAgentClassRegister - an instance of {@link JavaAgentClassRegister} which should be set to * frameworks classes. */ void set(JavaAgentClassRegister javaAgentClassRegister); /** * Remove all links to JavaAgentClassRegister */ void clear(); } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/agent/JavaAgentFrameworkRegisterFactory.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.agent; import org.powermock.reflect.Whitebox; /** * Factory to create an instance of JavaAgentFrameworkRegister, * depends on which mocking framework is loaded in runtime. */ public class JavaAgentFrameworkRegisterFactory { public static JavaAgentFrameworkRegister create() { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); return getInstanceForClassLoader(classLoader); } private static JavaAgentFrameworkRegister getInstanceForClassLoader(ClassLoader classLoader) { Class frameworkReporterClass = getJavaAgentFrameworkRegisterClass(classLoader); return Whitebox.newInstance(frameworkReporterClass); } @SuppressWarnings("unchecked") private static Class getJavaAgentFrameworkRegisterClass(ClassLoader classLoader) { Class agentFrameworkRegisterClass; try { agentFrameworkRegisterClass = (Class) classLoader.loadClass(getImplementerClassName()); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } return agentFrameworkRegisterClass; } @SuppressWarnings("SameReturnValue") private static String getImplementerClassName() { return "org.powermock.api.extension.agent.JavaAgentFrameworkRegisterImpl"; } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/bytebuddy/ConditionalStateStackManipulation.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.bytebuddy; import net.bytebuddy.implementation.Implementation.Context; import net.bytebuddy.implementation.bytecode.StackManipulation; import net.bytebuddy.jar.asm.Label; import net.bytebuddy.jar.asm.MethodVisitor; import net.bytebuddy.jar.asm.Opcodes; public class ConditionalStateStackManipulation implements StackManipulation { private final StackManipulation condition; private final StackManipulation action; private final StackManipulation otherwise; private final Frame frame; public ConditionalStateStackManipulation(final StackManipulation condition, final StackManipulation action, final StackManipulation otherwise, final Frame frame) { this.condition = condition; this.action = action; this.otherwise = otherwise; this.frame = frame; } @Override public boolean isValid() { return true; } @Override public Size apply(final MethodVisitor mv, final Context implementationContext) { Size size = new Size(0, 0); Label proceed = new Label(); Label exit = new Label(); size = size.aggregate(condition.apply(mv, implementationContext)); mv.visitJumpInsn(Opcodes.IFEQ, proceed); size = size.aggregate(action.apply(mv, implementationContext)); mv.visitJumpInsn(Opcodes.GOTO, exit); mv.visitLabel(proceed); mv.visitFrame(Opcodes.F_FULL, frame.localSize(), frame.locals(), 0, null); size = size.aggregate(otherwise.apply(mv, implementationContext)); mv.visitLabel(exit); mv.visitFrame(Opcodes.F_FULL, 0, null, 0, null); return size; } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/bytebuddy/Frame.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.bytebuddy; import net.bytebuddy.description.method.ParameterDescription; import net.bytebuddy.description.method.ParameterDescription.InDefinedShape; import net.bytebuddy.description.method.ParameterList; import net.bytebuddy.description.type.TypeDescription.Generic; import net.bytebuddy.implementation.bytecode.StackSize; import net.bytebuddy.jar.asm.Opcodes; import net.bytebuddy.utility.CompoundList; import java.util.ArrayList; import java.util.Collections; import java.util.Deque; import java.util.LinkedList; import java.util.List; public class Frame { public static Frame beforeConstructorCall(final Iterable constructorParameters) { List locals = new ArrayList(); locals.add(LocalVariable.UNINITIALIZED_THIS); int maxLocals = 1; for (ParameterDescription sourceParameter : constructorParameters) { Generic type = sourceParameter.getType(); locals.add(LocalVariable.from(type)); maxLocals += type.getStackSize().getSize(); } return new Frame(locals); } private Deque stack; private List locals; public Frame(final List locals) { this.locals = Collections.unmodifiableList(locals); this.stack = new LinkedList(); } public Frame addTopToLocals(final int count) { List locals = new ArrayList(); for (int i = 0; i < count; i++) { locals.add(LocalVariable.TOP); } return new Frame( CompoundList.of(this.locals, locals) ); } public Frame addLocalVariable(final LocalVariable localVariable) { return new Frame( CompoundList.of(this.locals, localVariable) ); } public Frame addLocalVariables(final ParameterList types) { List frameLocals = new ArrayList(); for (ParameterDescription parameter : types) { Generic type = parameter.getType(); frameLocals.add(LocalVariable.from(type)); } return new Frame(CompoundList.of(this.locals, frameLocals)); } public Object[] locals() { Object[] frameLocals = new Object[this.locals.size()]; for (int i = 0; i < this.locals.size(); i++) { frameLocals[i] = this.locals.get(i).getType(); } return frameLocals; } public int localSize() { return locals.size(); } public int maxLocalVariableIndex() { int localStackSize = 0; for (LocalVariable localVariable : locals) { localStackSize += localVariable.getStackSize().getSize(); } return localStackSize; } public static class LocalVariable { public static LocalVariable from(final Generic type) { if (type.represents(double.class)) { return DOUBLE; } else { return new LocalVariable( type.getTypeName().replace('.', '/'), type.getStackSize() ); } } public static final LocalVariable UNINITIALIZED_THIS = new LocalVariable(Opcodes.UNINITIALIZED_THIS, StackSize.SINGLE); public static final LocalVariable TOP = new LocalVariable(Opcodes.TOP, StackSize.SINGLE); public static final LocalVariable DOUBLE = new LocalVariable(Opcodes.DOUBLE, StackSize.DOUBLE); private final Object type; private final StackSize stackSize; private LocalVariable(final Object type, StackSize size) { this.type = type; this.stackSize = size; } public Object getType() { return type; } public StackSize getStackSize() { return stackSize; } } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/bytebuddy/MaxLocalsExtractor.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.bytebuddy; import net.bytebuddy.description.method.MethodDescription; import net.bytebuddy.jar.asm.ClassVisitor; import net.bytebuddy.jar.asm.MethodVisitor; import net.bytebuddy.jar.asm.Opcodes; public class MaxLocalsExtractor extends ClassVisitor { private MethodMaxLocals methodMaxLocals; public MaxLocalsExtractor() { super(Opcodes.ASM5); } @Override public MethodVisitor visitMethod(final int access, final String name, final String desc, final String signature, final String[] exceptions) { if (MethodDescription.CONSTRUCTOR_INTERNAL_NAME.equals(name)) { methodMaxLocals = new MethodMaxLocals(); return new MaxLocalsMethodVisitor(name, desc, methodMaxLocals); } return super.visitMethod(access, name, desc, signature, exceptions); } public MethodMaxLocals getMethods() { return methodMaxLocals; } private static class MaxLocalsMethodVisitor extends MethodVisitor { private final String name; private final String signature; private final MethodMaxLocals methodMaxLocals; private int maxLocals; private MaxLocalsMethodVisitor(final String name, final String signature, final MethodMaxLocals methodMaxLocals) { super(Opcodes.ASM5); this.name = name; this.signature = signature; this.methodMaxLocals = methodMaxLocals; } @Override public void visitMaxs(final int maxStack, final int maxLocals) { this.maxLocals = maxLocals; super.visitMaxs(maxStack, maxLocals); } @Override public void visitEnd() { methodMaxLocals.add(name, signature, maxLocals); super.visitEnd(); } } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/bytebuddy/MethodMaxLocals.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.bytebuddy; import net.bytebuddy.description.method.MethodDescription; import java.util.HashMap; import java.util.Map; public class MethodMaxLocals { private final Map methodMaxLocals; MethodMaxLocals() { methodMaxLocals = new HashMap(); } public void add(String name, String signature, int maxLocals) { methodMaxLocals.put(name + signature, maxLocals); } public int getMethodMaxLocal(final MethodDescription instrumentedMethod) { final String key = instrumentedMethod.getInternalName() + instrumentedMethod.getDescriptor(); final Integer maxLocals = methodMaxLocals.get(key); return maxLocals == null ? 0 : maxLocals; } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/bytebuddy/MockGetawayCall.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.bytebuddy; import net.bytebuddy.description.method.MethodDescription.ForLoadedMethod; import net.bytebuddy.description.method.ParameterDescription.InDefinedShape; import net.bytebuddy.description.method.ParameterList; import net.bytebuddy.description.type.TypeDescription; import net.bytebuddy.implementation.Implementation.Context; import net.bytebuddy.implementation.bytecode.StackManipulation; import net.bytebuddy.implementation.bytecode.collection.ArrayFactory; import net.bytebuddy.implementation.bytecode.constant.ClassConstant; import net.bytebuddy.implementation.bytecode.member.MethodInvocation; import net.bytebuddy.jar.asm.MethodVisitor; import org.powermock.core.bytebuddy.Variable.VariableAccess; import org.powermock.reflect.internal.WhiteboxImpl; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; public class MockGetawayCall { private final Method getawayMethod; public MockGetawayCall(final Class mockGetawayClass) { getawayMethod = WhiteboxImpl.getMethod( mockGetawayClass, "suppressConstructorCall", Class.class, Object[].class, Class[].class ); } public ForType forType(final TypeDescription targetType) { return new ForType(this, targetType); } public static class ForType { private final TypeDescription targetType; private final MockGetawayCall mockGetawayCall; private ForType(final MockGetawayCall mockGetawayCall, final TypeDescription targetType) { this.mockGetawayCall = mockGetawayCall; this.targetType = targetType; } public WithArguments withArguments(final List parameters) { return new WithArguments(this, parameters); } } public static class WithArguments { private final ForType forType; private final List arguments; private WithArguments(final ForType forType, final List arguments) { this.forType = forType; this.arguments = arguments; } public ConstructorMockGetawayCall withParameterTypes(final ParameterList targetParameters) { return new ConstructorMockGetawayCall( forType.mockGetawayCall.getawayMethod, forType.targetType, arguments, targetParameters ); } } private static class ConstructorMockGetawayCall implements StackManipulation { private final Method getawayMethod; private final TypeDescription targetType; private final List arguments; private final ParameterList targetParameters; private ConstructorMockGetawayCall(final Method getawayMethod, final TypeDescription targetType, final List arguments, final ParameterList targetParameters ) { this.getawayMethod = getawayMethod; this.targetType = targetType; this.arguments = arguments; this.targetParameters = targetParameters; } private List loadSignatureParametersClasess() { List constructorSignature = new ArrayList(); for (InDefinedShape targetParameter : targetParameters) { constructorSignature.add( ClassConstant.of(targetParameter.getType().asErasure()) ); } return constructorSignature; } private List loadArgumentsFromVariable() { List loadTargetParameters = new ArrayList(); for (Variable argument : arguments) { loadTargetParameters.add( VariableAccess.load(argument, true) ); } return loadTargetParameters; } @Override public boolean isValid() { return true; } @Override public Size apply(final MethodVisitor mv, final Context implementationContext) { List loadTargetParameters = loadArgumentsFromVariable(); List constructorSignature = loadSignatureParametersClasess(); return new Compound( ClassConstant.of(targetType), ArrayFactory.forType(TypeDescription.OBJECT.asGenericType()).withValues(loadTargetParameters), ArrayFactory.forType(TypeDescription.CLASS.asGenericType()).withValues(constructorSignature), MethodInvocation.invoke(new ForLoadedMethod(getawayMethod)) ).apply(mv, implementationContext); } } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/bytebuddy/PrimitiveBoxing.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.bytebuddy; import net.bytebuddy.description.type.TypeDefinition; import net.bytebuddy.description.type.TypeDescription; import net.bytebuddy.description.type.TypeDescription.ForLoadedType; import net.bytebuddy.implementation.Implementation; import net.bytebuddy.implementation.bytecode.StackManipulation; import net.bytebuddy.implementation.bytecode.StackSize; import net.bytebuddy.jar.asm.MethodVisitor; import net.bytebuddy.jar.asm.Opcodes; public enum PrimitiveBoxing implements StackManipulation{ BOOLEAN(Boolean.class, StackSize.ZERO, "valueOf", "(Z)Ljava/lang/Boolean;"), BYTE(Byte.class, StackSize.ZERO, "valueOf", "(B)Ljava/lang/Byte;"), SHORT(Short.class, StackSize.ZERO, "valueOf", "(S)Ljava/lang/Short;"), CHARACTER(Character.class, StackSize.ZERO, "valueOf", "(C)Ljava/lang/Character;"), INTEGER(Integer.class, StackSize.ZERO, "valueOf", "(I)Ljava/lang/Integer;"), LONG(Long.class, StackSize.SINGLE, "valueOf", "(J)Ljava/lang/Long;"), FLOAT(Float.class, StackSize.ZERO, "valueOf", "(F)Ljava/lang/Float;"), DOUBLE(Double.class, StackSize.SINGLE, "valueOf", "(D)Ljava/lang/Double;"); private final ForLoadedType wrapperType; private final Size size; private final String boxingMethodName; private final String boxingMethodDescriptor; PrimitiveBoxing(Class wrapperType, StackSize sizeDifference, String boxingMethodName, String boxingMethodDescriptor) { this.wrapperType = new TypeDescription.ForLoadedType(wrapperType); this.size = sizeDifference.toDecreasingSize(); this.boxingMethodName = boxingMethodName; this.boxingMethodDescriptor = boxingMethodDescriptor; } public static PrimitiveBoxing forPrimitive(TypeDefinition typeDefinition) { if (typeDefinition.represents(boolean.class)) { return BOOLEAN; } else if (typeDefinition.represents(byte.class)) { return BYTE; } else if (typeDefinition.represents(short.class)) { return SHORT; } else if (typeDefinition.represents(char.class)) { return CHARACTER; } else if (typeDefinition.represents(int.class)) { return INTEGER; } else if (typeDefinition.represents(long.class)) { return LONG; } else if (typeDefinition.represents(float.class)) { return FLOAT; } else if (typeDefinition.represents(double.class)) { return DOUBLE; } else { throw new IllegalArgumentException("Not a non-void, primitive type: " + typeDefinition); } } @Override public boolean isValid() { return true; } @Override public Size apply(MethodVisitor methodVisitor, Implementation.Context implementationContext) { methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, wrapperType.getInternalName(), boxingMethodName, boxingMethodDescriptor, false); return size; } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/bytebuddy/Variable.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.bytebuddy; import net.bytebuddy.description.type.TypeDescription; import net.bytebuddy.description.type.TypeDescription.Generic; import net.bytebuddy.implementation.bytecode.StackManipulation; import net.bytebuddy.implementation.bytecode.StackManipulation.Compound; import net.bytebuddy.implementation.bytecode.member.MethodVariableAccess; public class Variable { public static Variable of(final Generic variableType, final int offset) { return new Variable(variableType.asErasure(), offset); } private final TypeDescription typeDefinitions; private final int offset; private Variable(final TypeDescription typeDefinitions, final int offset) { this.typeDefinitions = typeDefinitions; this.offset = offset; } public static class VariableAccess { public static StackManipulation load(Variable variable) {return load(variable, false);} public static StackManipulation load(Variable variable, final boolean boxing) { TypeDescription typeDefinitions = variable.typeDefinitions; if (typeDefinitions.isPrimitive() && boxing) { return new Compound( MethodVariableAccess.of(typeDefinitions).loadFrom(variable.offset), PrimitiveBoxing.forPrimitive(typeDefinitions) ); }else { return MethodVariableAccess.of(typeDefinitions).loadFrom(variable.offset); } } public static StackManipulation store(Variable variable) { return MethodVariableAccess.of(variable.typeDefinitions).storeAt(variable.offset); } } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/classloader/ByteCodeFramework.java ================================================ package org.powermock.core.classloader; import org.powermock.configuration.GlobalConfiguration; import org.powermock.core.classloader.annotations.PrepareEverythingForTest; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.core.classloader.annotations.PrepareOnlyThisForTest; import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor; import org.powermock.core.classloader.annotations.UseClassPathAdjuster; import org.powermock.core.classloader.javassist.JavassistMockClassLoader; import org.powermock.core.transformers.MockTransformerChainFactory; import org.powermock.core.transformers.javassist.JavassistMockTransformerChainFactory; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Method; public enum ByteCodeFramework { Javassist { @Override MockClassLoader createClassloader(final MockClassLoaderConfiguration configuration, final UseClassPathAdjuster useClassPathAdjuster) { return new JavassistMockClassLoader(configuration, useClassPathAdjuster); } @Override MockTransformerChainFactory createTransformerChainFactory() { return new JavassistMockTransformerChainFactory(); } }; public static ByteCodeFramework getByteCodeFrameworkForMethod(final Class testClass, final Method method) { ByteCodeFramework byteCodeFramework = getByteCodeFramework(method); if (byteCodeFramework == null) { byteCodeFramework = getByteCodeFramework(testClass); } if (byteCodeFramework == null) { throw new IllegalArgumentException( String.format( "Either method %s or class %s is annotated by PrepareForTest/PrepareEverythingForTest", method.getName(), testClass.getName() ) ); } return byteCodeFramework; } public static ByteCodeFramework getByteCodeFrameworkForTestClass(final Class testClass) { ByteCodeFramework byteCodeFramework = getByteCodeFramework(testClass); if (byteCodeFramework == null){ byteCodeFramework = GlobalConfiguration.powerMockConfiguration().getByteCodeFramework(); } return byteCodeFramework; } private static ByteCodeFramework getByteCodeFramework(final AnnotatedElement element) { if (element.isAnnotationPresent(PrepareForTest.class)) { return element.getAnnotation(PrepareForTest.class).byteCodeFramework(); } else if (element.isAnnotationPresent(PrepareOnlyThisForTest.class)) { return element.getAnnotation(PrepareOnlyThisForTest.class).byteCodeFramework(); } else if (element.isAnnotationPresent(PrepareEverythingForTest.class)) { return element.getAnnotation(PrepareEverythingForTest.class).byteCodeFramework(); } else if (element.isAnnotationPresent(SuppressStaticInitializationFor.class)){ return element.getAnnotation(SuppressStaticInitializationFor.class).byteCodeFramework(); } return null; } abstract MockClassLoader createClassloader(MockClassLoaderConfiguration configuration, final UseClassPathAdjuster useClassPathAdjuster); abstract MockTransformerChainFactory createTransformerChainFactory(); } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/classloader/ClassMarker.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.classloader; import org.powermock.core.transformers.ClassWrapper; /** * Instance of this interface can be used to mark a class that it was created and loaded by PowerMock */ public interface ClassMarker { /** * Mark type as loaded by PowerMock * * @param type to mark. */ void mark(ClassWrapper type); } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/classloader/ClassloaderWrapper.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.classloader; import org.powermock.core.InvocationException; import java.util.concurrent.Callable; // We change the context classloader to the current CL in order for the Mockito // framework to load it's plugins (such as MockMaker) correctly. public class ClassloaderWrapper { public static void runWithClass(final Runnable runnable) { runWithClassClassLoader(ClassloaderWrapper.class.getClassLoader(), runnable); } public static void runWithClassClassLoader(final ClassLoader classLoader, final Runnable runnable) { final ClassLoader originalCL = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(classLoader); try { runnable.run(); } finally { Thread.currentThread().setContextClassLoader(originalCL); } } public static V runWithClass(final Callable callable) { return runWithClassClassLoader(ClassloaderWrapper.class.getClassLoader(), callable); } public static V runWithClassClassLoader(final ClassLoader classLoader, final Callable callable) { final ClassLoader originalCL = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(classLoader); try { return callable.call(); } catch (Exception e) { throw new InvocationException(e); } finally { Thread.currentThread().setContextClassLoader(originalCL); } } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/classloader/DeferSupportingClassLoader.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.core.classloader; import org.powermock.reflect.Whitebox; import java.io.IOException; import java.io.InputStream; import java.lang.ref.SoftReference; import java.net.URL; import java.util.Enumeration; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * Defers classloading of system classes to a delegate. * * @author Johan Haleby * @author Jan Kronquist * @author Arthur Zagretdinov */ abstract class DeferSupportingClassLoader extends ClassLoader { private final ConcurrentMap>> classes; private final ConcurrentMap parallelLockMap; private final MockClassLoaderConfiguration configuration; ClassLoader deferTo; DeferSupportingClassLoader(ClassLoader classloader, MockClassLoaderConfiguration configuration) { this.configuration = configuration; this.classes = new ConcurrentHashMap>>(); if (classloader == null) { deferTo = ClassLoader.getSystemClassLoader(); } else { deferTo = classloader; } parallelLockMap = new ConcurrentHashMap(); } @Override public URL getResource(String s) { return deferTo.getResource(s); } @Override public InputStream getResourceAsStream(String s) { return deferTo.getResourceAsStream(s); } @Override public Enumeration getResources(String name) throws IOException { // If deferTo is already the parent, then we'd end up returning two copies of each resource... if (deferTo.equals(getParent())) { return deferTo.getResources(name); } else { return super.getResources(name); } } public MockClassLoaderConfiguration getConfiguration() { return configuration; } /** * Register a class to the cache of this classloader */ public void cache(Class cls) { if (cls != null) { classes.put(cls.getName(), new SoftReference>(cls)); } } protected abstract Class loadClassByThisClassLoader(String s) throws ClassFormatError, ClassNotFoundException; @Override protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { synchronized (getClassLoadingLock(name)) { Class clazz = findLoadedClass1(name); if (clazz == null) { clazz = loadClass1(name, resolve); } return clazz; } } protected Object getClassLoadingLock(String className) { Object lock = this; if (parallelLockMap != null) { Object newLock = new Object(); lock = parallelLockMap.putIfAbsent(className, newLock); if (lock == null) { lock = newLock; } } return lock; } /** * Finds the resource with the specified name on the search path. * * @param name the name of the resource * @return a {@code URL} for the resource, or {@code null} if the * resource could not be found. */ @Override protected URL findResource(String name) { try { return Whitebox.invokeMethod(deferTo, "findResource", name); } catch (Exception e) { throw new RuntimeException(e); } } @Override protected Enumeration findResources(String name) throws IOException { try { return Whitebox.invokeMethod(deferTo, "findResources", name); } catch (Exception e) { throw new RuntimeException(e); } } private Class loadClass1(String name, boolean resolve) throws ClassNotFoundException { Class clazz; if (shouldDefer(name)) { clazz = loadByDeferClassLoader(name); } else { clazz = loadClassByThisClassLoader(name); } if (resolve) { resolveClass(clazz); } classes.put(name, new SoftReference>(clazz)); return clazz; } private Class loadByDeferClassLoader(final String name) throws ClassNotFoundException { final Class clazz; clazz = deferTo.loadClass(name); return clazz; } private boolean shouldDefer(String name) { return configuration.shouldDefer(name); } private Class findLoadedClass1(String name) {SoftReference> reference = classes.get(name); Class clazz = null; if (reference != null) { clazz = reference.get(); } if (clazz == null) { clazz = findLoadedClass(name); } return clazz; } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/classloader/MockClassLoader.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.classloader; import org.powermock.core.transformers.ClassWrapper; import org.powermock.core.transformers.ClassWrapperFactory; import org.powermock.core.transformers.MockTransformer; import org.powermock.core.transformers.MockTransformerChain; import org.powermock.core.transformers.javassist.support.JavaAssistClassWrapperFactory; import org.powermock.core.transformers.support.DefaultMockTransformerChain; import org.powermock.tests.utils.IgnorePackagesExtractor; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.security.ProtectionDomain; /** *

* The classloader loads and modified all classes except: *

*
    *
  1. system classes. They are deferred to system classloader
  2. *
  3. classes that locate in packages that specified as packages to ignore with using {@link MockClassLoaderConfiguration#addIgnorePackage(String...)}
  4. *
*

* Testing frameworks classes are loaded, but not modified. *

*

* The classloader uses list of {@link MockTransformer} to modify classes during loading. *

* * @author Johan Haleby * @author Jan Kronquist * @author Artur Zagretdinov * * @see MockClassLoaderConfiguration * @see ClassLoader#getSystemClassLoader() * @see IgnorePackagesExtractor */ public abstract class MockClassLoader extends DeferSupportingClassLoader { /** * Pass this string to the constructor to indicate that all classes should * be modified. */ public static final String MODIFY_ALL_CLASSES = "*"; protected ClassMarker classMarker; protected ClassWrapperFactory classWrapperFactory; private MockTransformerChain mockTransformerChain; /** * Creates a new instance of the based on the * following parameters: * * @param classesToMock The classes that must be modified to prepare for testability. * @param packagesToDefer Classes in these packages will be defered to the system * class-loader. */ protected MockClassLoader(String[] classesToMock, String[] packagesToDefer) { this(new MockClassLoaderConfiguration(classesToMock, packagesToDefer), new JavaAssistClassWrapperFactory()); } /** * Creates a new instance of the based on the * following parameters: * * @param configuration The configuration of class loader. Configuration contains information about classes * which should be loaded by class loader, defer to system and mocked. * @param classWrapperFactory an instance of {@link ClassWrapperFactory} which is used to wrap internal framework's representation of * the class into {@link ClassWrapper} * @see MockClassLoaderConfiguration */ protected MockClassLoader(MockClassLoaderConfiguration configuration, final ClassWrapperFactory classWrapperFactory) { super(MockClassLoader.class.getClassLoader(), configuration); this.classWrapperFactory = classWrapperFactory; this.mockTransformerChain = DefaultMockTransformerChain.newBuilder().build(); } @Override protected Class loadClassByThisClassLoader(String className) throws ClassFormatError, ClassNotFoundException { final Class loadedClass; Class deferClass = deferTo.loadClass(className); if (getConfiguration().shouldMockClass(className)) { loadedClass = loadMockClass(className, deferClass.getProtectionDomain()); } else { loadedClass = loadUnmockedClass(className, deferClass.getProtectionDomain()); } return loadedClass; } public void setMockTransformerChain(MockTransformerChain mockTransformerChain) { this.mockTransformerChain = mockTransformerChain; } public MockTransformerChain getMockTransformerChain() { return mockTransformerChain; } protected Class loadUnmockedClass(final String name, final ProtectionDomain protectionDomain) throws ClassNotFoundException { String path = name.replace('.', '/').concat(".class"); URL res = deferTo.getResource(path); if (res != null) { try { return defineClass(name, res, protectionDomain); } catch (IOException e) { throw new ClassNotFoundException(name, e); } } else { throw new ClassNotFoundException(name); } } private Class defineClass(String name, URL url, final ProtectionDomain protectionDomain) throws IOException { byte[] b = readClass(url); return defineClass(name, b, 0, b.length, protectionDomain); } private byte[] readClass(final URL url) throws IOException { final URLConnection connection = url.openConnection(); final InputStream in = connection.getInputStream(); ByteArrayOutputStream tmpOut = null; try { final int contentLength = connection.getContentLength(); // To avoid having to resize the array over and over and over as // bytes are written to the array, provide an accurate estimate of // the ultimate size of the byte array if (contentLength != -1) { tmpOut = new ByteArrayOutputStream(contentLength); } else { tmpOut = new ByteArrayOutputStream(16384); } byte[] buf = new byte[512]; while (true) { int len = in.read(buf); if (len == -1) { break; } tmpOut.write(buf, 0, len); } return tmpOut.toByteArray(); } finally { in.close(); if (tmpOut != null) { tmpOut.close(); } } } private Class loadMockClass(String name, ProtectionDomain protectionDomain) throws ClassNotFoundException { final byte[] clazz = defineAndTransformClass(name, protectionDomain); return defineClass(name, protectionDomain, clazz); } public Class defineClass(final String name, final ProtectionDomain protectionDomain, final byte[] clazz) { return defineClass(name, clazz, 0, clazz.length, protectionDomain); } protected ClassWrapper transformClass(ClassWrapper wrappedType) throws Exception { wrappedType = mockTransformerChain.transform(wrappedType); if (classMarker != null) { classMarker.mark(wrappedType); } return wrappedType; } protected abstract byte[] defineAndTransformClass(final String name, final ProtectionDomain protectionDomain) throws ClassNotFoundException; } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/classloader/MockClassLoaderBuilder.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.classloader; import org.powermock.core.classloader.annotations.UseClassPathAdjuster; import org.powermock.core.transformers.MockTransformer; import org.powermock.core.transformers.MockTransformerChain; import org.powermock.core.transformers.MockTransformerChainFactory; import org.powermock.core.transformers.TestClassAwareTransformer; import org.powermock.utils.ArrayUtil; import java.util.ArrayList; import java.util.List; import static org.powermock.core.transformers.support.FilterPredicates.isInstanceOf; import static org.powermock.utils.Asserts.internalAssertNotNull; public class MockClassLoaderBuilder { private final MockTransformerChainFactory transformerChainFactory; private final List extraMockTransformers; private final ByteCodeFramework byteCodeFramework; private String[] packagesToIgnore; private String[] classesToModify; public static MockClassLoaderBuilder create(ByteCodeFramework byteCodeFramework) { return new MockClassLoaderBuilder(byteCodeFramework); } private UseClassPathAdjuster useClassPathAdjuster; private Class testClass; private MockClassLoaderBuilder(final ByteCodeFramework byteCodeFramework) { this.byteCodeFramework = byteCodeFramework; transformerChainFactory = byteCodeFramework.createTransformerChainFactory(); extraMockTransformers = new ArrayList(); } public MockClassLoader build() { internalAssertNotNull(testClass, "Test class is null during building classloader. "); final MockClassLoaderConfiguration configuration = new MockClassLoaderConfiguration(classesToModify, packagesToIgnore); final MockClassLoader classLoader = byteCodeFramework.createClassloader(configuration, useClassPathAdjuster); classLoader.setMockTransformerChain(createTransformerChain()); return classLoader; } private MockTransformerChain createTransformerChain() { final MockTransformerChain mockTransformerChain = transformerChainFactory.createDefaultChain(extraMockTransformers); final Iterable testAwareTransformer = mockTransformerChain.filter(isInstanceOf(TestClassAwareTransformer.class)); for (MockTransformer transformer : testAwareTransformer) { ((TestClassAwareTransformer) transformer).setTestClass(testClass); } return mockTransformerChain; } public MockClassLoaderBuilder addIgnorePackage(String[] packagesToIgnore) { this.packagesToIgnore = ArrayUtil.addAll(this.packagesToIgnore, packagesToIgnore); return this; } public MockClassLoaderBuilder addClassesToModify(String[] classesToModify) { this.classesToModify = ArrayUtil.addAll(this.classesToModify, classesToModify); return this; } public MockClassLoaderBuilder addExtraMockTransformers(MockTransformer... mockTransformers) { if (mockTransformers != null) { for (MockTransformer mockTransformer : mockTransformers) { if (mockTransformer != null) { extraMockTransformers.add(mockTransformer); } } } return this; } public MockClassLoaderBuilder addClassPathAdjuster(final UseClassPathAdjuster useClassPathAdjuster) { this.useClassPathAdjuster = useClassPathAdjuster; return this; } public MockClassLoaderBuilder forTestClass(final Class testClass) { this.testClass = testClass; return this; } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/classloader/MockClassLoaderConfiguration.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.classloader; import org.powermock.core.ClassReplicaCreator; import org.powermock.core.WildcardMatcher; import org.powermock.core.spi.PowerMockPolicy; import org.powermock.core.spi.support.InvocationSubstitute; import org.powermock.utils.ArrayUtil; import java.util.Collections; import java.util.HashSet; import java.util.Set; import static org.powermock.core.classloader.MockClassLoader.MODIFY_ALL_CLASSES; /** * The instance of the class provides information about classes which have to be mocked, loaded without modification * or defer to system class loader. */ public class MockClassLoaderConfiguration { /* * Classes that should always be deferred regardless of what the user * specifies in annotations etc. */ static final String[] PACKAGES_TO_BE_DEFERRED = new String[]{ "org.hamcrest.*", "jdk.*", "java.*", "javax.accessibility.*", "sun.*", "org.junit.*", "org.testng.*", "junit.*", "org.pitest.*", "org.powermock.modules.junit4.common.internal.*", "org.powermock.modules.junit3.internal.PowerMockJUnit3RunnerDelegate*", "org.powermock.core*", "org.jacoco.agent.rt.*" }; /* * Classes not deferred but loaded by the mock class loader but they're not * modified. */ private static final String[] PACKAGES_TO_LOAD_BUT_NOT_MODIFY = new String[]{ "org.junit.", "junit.", "org.testng.", "org.easymock.", "net.sf.cglib.", "javassist.", "org.powermock.modules.junit4.internal.", "org.powermock.modules.junit4.legacy.internal.", "org.powermock.modules.junit3.internal.", "org.powermock"}; private final String[] specificClassesToLoadButNotModify = new String[]{ InvocationSubstitute.class.getName(), PowerMockPolicy.class.getName(), ClassReplicaCreator.class.getName() }; private final Set modify = Collections.synchronizedSet(new HashSet()); private String[] deferPackages; /** * Create an instance of configuration without any classes to mock or ignore. */ public MockClassLoaderConfiguration() { this(new String[0], new String[0]); } /** * Create an instance of configuration * @param classesToMock classes that should be modified by {@link MockClassLoader}. * @param packagesToDefer classes/packages that should be deferred to system class loader. */ public MockClassLoaderConfiguration(String[] classesToMock, String[] packagesToDefer) { deferPackages = getPackagesToDefer(packagesToDefer); addClassesToModify(classesToMock); } /** * Add packages or classes to ignore. Loading of all classes that locate in the added packages will be delegate to a system classloader. *

* Package should be specified with using mask. Example: *

*
     *     configuration.addIgnorePackage("org.powermock.example.*");
     * 
* * @param packagesToIgnore fully qualified names of classes or names of packages that end by .* */ public void addIgnorePackage(String... packagesToIgnore) { if (packagesToIgnore != null && packagesToIgnore.length > 0) { final int previousLength = deferPackages.length; String[] newDeferPackages = new String[previousLength + packagesToIgnore.length]; System.arraycopy(deferPackages, 0, newDeferPackages, 0, previousLength); System.arraycopy(packagesToIgnore, 0, newDeferPackages, previousLength, packagesToIgnore.length); deferPackages = newDeferPackages; } } /** * Add classes that will be loaded by the mock classloader, i.e. these * classes will be byte-code manipulated to allow for testing. Any classes * contained in the {@link #PACKAGES_TO_BE_DEFERRED} will be ignored. How ever * classes added here have precedence over additionally deferred (ignored) * packages (those ignored by the user using @PrepareForTest). * * @param classes The fully qualified name of the classes that will be appended * to the list of classes that will be byte-code modified to * enable testability. */ public final void addClassesToModify(String... classes) { if (classes != null) { for (String clazz : classes) { if (!shouldDefer(PACKAGES_TO_BE_DEFERRED, clazz)) { modify.add(clazz); } } } } boolean shouldDefer(String className) { return shouldDefer(deferPackages, className); } boolean shouldMockClass(String className) { return shouldModify(className) && !shouldLoadWithMockClassloaderWithoutModifications(className); } String[] getDeferPackages() { return ArrayUtil.clone(deferPackages); } private boolean shouldDefer(String[] packages, String name) { for (String packageToCheck : packages) { if (deferConditionMatches(name, packageToCheck)) { return true; } } return false; } private boolean deferConditionMatches(String name, String packageName) { final boolean wildcardMatch = WildcardMatcher.matches(name, packageName); return wildcardMatch && !(shouldLoadUnmodifiedClass(name) || shouldModifyClass(name)); } private boolean shouldIgnore(String[] packages, String name) { for (String ignore : packages) { if (WildcardMatcher.matches(name, ignore)) { return true; } } return false; } private boolean shouldLoadUnmodifiedClass(String className) { for (String classNameToLoadButNotModify : specificClassesToLoadButNotModify) { if (className.equals(classNameToLoadButNotModify)) { return true; } } return false; } private boolean shouldLoadWithMockClassloaderWithoutModifications(String className) { if (className.startsWith("org.powermock.example")) { return false; } for (String packageToLoadButNotModify : PACKAGES_TO_LOAD_BUT_NOT_MODIFY) { if (className.startsWith(packageToLoadButNotModify)) { return true; } } return false; } private boolean shouldModifyClass(String className) { return modify.contains(className); } private boolean shouldIgnore(String className) { return shouldIgnore(deferPackages, className); } boolean shouldModify(String className) { final boolean shouldIgnoreClass = shouldIgnore(className); final boolean shouldModifyAll = shouldModifyAll(); if (shouldModifyAll) { return !shouldIgnoreClass; } else { /* * Never mind if we should ignore the class here since * classes added by prepared for test should (i.e. those added in "modify") * have precedence over ignored packages. */ return WildcardMatcher.matchesAny(modify, className); } } private boolean shouldModifyAll() { return (modify.size() == 1 && modify.iterator().next().equals(MODIFY_ALL_CLASSES)); } private static String[] getPackagesToDefer(final String[] additionalDeferPackages) { final int additionalIgnorePackagesLength = additionalDeferPackages == null ? 0 : additionalDeferPackages.length; final int defaultDeferPackagesLength = PACKAGES_TO_BE_DEFERRED.length; final int allIgnoreLength = defaultDeferPackagesLength + additionalIgnorePackagesLength; final String[] allPackagesToBeIgnored = new String[allIgnoreLength]; if (allIgnoreLength > defaultDeferPackagesLength) { System.arraycopy(PACKAGES_TO_BE_DEFERRED, 0, allPackagesToBeIgnored, 0, defaultDeferPackagesLength); System.arraycopy(additionalDeferPackages != null ? additionalDeferPackages : new String[0], 0, allPackagesToBeIgnored, defaultDeferPackagesLength, additionalIgnorePackagesLength); return allPackagesToBeIgnored; } return PACKAGES_TO_BE_DEFERRED; } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/classloader/MockClassLoaderFactory.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.classloader; import org.powermock.core.classloader.annotations.MockPolicy; import org.powermock.core.classloader.annotations.PrepareEverythingForTest; import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor; import org.powermock.core.classloader.annotations.UseClassPathAdjuster; import org.powermock.core.spi.PowerMockPolicy; import org.powermock.core.transformers.MockTransformer; import org.powermock.tests.utils.ArrayMerger; import org.powermock.tests.utils.TestClassesExtractor; import org.powermock.tests.utils.impl.ArrayMergerImpl; import org.powermock.tests.utils.impl.MockPolicyInitializerImpl; import org.powermock.tests.utils.impl.PowerMockIgnorePackagesExtractorImpl; import org.powermock.tests.utils.impl.PrepareForTestExtractorImpl; import org.powermock.tests.utils.impl.StaticConstructorSuppressExtractorImpl; import java.lang.reflect.Method; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.List; public class MockClassLoaderFactory { private final String[] packagesToIgnore; private final Class testClass; private final TestClassesExtractor prepareForTestExtractor; private final TestClassesExtractor suppressionExtractor; private final ArrayMerger arrayMerger; public MockClassLoaderFactory(Class testClass) { this(testClass, new PowerMockIgnorePackagesExtractorImpl().getPackagesToIgnore(testClass)); } public MockClassLoaderFactory(Class testClass, String[] packagesToIgnore) { this.testClass = testClass; this.prepareForTestExtractor = new PrepareForTestExtractorImpl(); this.suppressionExtractor = new StaticConstructorSuppressExtractorImpl(); this.packagesToIgnore = packagesToIgnore; arrayMerger = new ArrayMergerImpl(); } public ClassLoader createForClass(final MockTransformer... extraMockTransformer) { final ByteCodeFramework byteCodeFramework = ByteCodeFramework.getByteCodeFrameworkForTestClass(testClass); if (testClass.isAnnotationPresent(PrepareEverythingForTest.class)) { return create(byteCodeFramework, new String[]{MockClassLoader.MODIFY_ALL_CLASSES}, extraMockTransformer); } else { final String[] prepareForTestClasses = prepareForTestExtractor.getTestClasses(testClass); final String[] suppressStaticClasses = suppressionExtractor.getTestClasses(testClass); return create(byteCodeFramework, arrayMerger.mergeArrays(String.class, prepareForTestClasses, suppressStaticClasses), extraMockTransformer); } } public ClassLoader createForMethod(final Method method, final MockTransformer... extraMockTransformers) { final ByteCodeFramework byteCodeFramework = ByteCodeFramework.getByteCodeFrameworkForMethod(testClass, method); if (method.isAnnotationPresent(PrepareEverythingForTest.class)) { final String[] classesToLoadByMockClassloader = {MockClassLoader.MODIFY_ALL_CLASSES}; return create(byteCodeFramework, classesToLoadByMockClassloader, extraMockTransformers); } else { final String[] suppressStaticClasses = getStaticSuppressionClasses(method); final String[] prepareForTestClasses = prepareForTestExtractor.getTestClasses(method); final String[] classesToLoadByMockClassloader = arrayMerger.mergeArrays(String.class, prepareForTestClasses, suppressStaticClasses); return create(byteCodeFramework, classesToLoadByMockClassloader, extraMockTransformers); } } private ClassLoader create(final ByteCodeFramework byteCodeFramework, final String[] prepareForTestClasses, final MockTransformer... extraMockTransformer) { final String[] classesToLoadByMockClassloader = makeSureArrayContainsTestClassName(prepareForTestClasses, testClass.getName()); final ClassLoader mockLoader; if (isContextClassLoaderShouldBeUsed(classesToLoadByMockClassloader)) { mockLoader = Thread.currentThread().getContextClassLoader(); } else { mockLoader = createMockClassLoader(byteCodeFramework, classesToLoadByMockClassloader, extraMockTransformer); } return mockLoader; } private String[] getStaticSuppressionClasses(Method method) { final String[] testClasses; if (method.isAnnotationPresent(SuppressStaticInitializationFor.class)) { testClasses = suppressionExtractor.getTestClasses(method); } else { testClasses = suppressionExtractor.getTestClasses(testClass); } return testClasses; } private ClassLoader createMockClassLoader(final ByteCodeFramework byteCodeFramework, final String[] classesToLoadByMockClassloader, final MockTransformer... extraMockTransformer) { final ClassLoader mockLoader = createWithPrivilegeAccessController(byteCodeFramework, classesToLoadByMockClassloader, extraMockTransformer); initialize(mockLoader); return mockLoader; } private ClassLoader createWithPrivilegeAccessController(final ByteCodeFramework byteCodeFramework, final String[] classesToLoadByMockClassloader, final MockTransformer... extraMockTransformer) { return AccessController.doPrivileged(new PrivilegedAction() { @Override public MockClassLoader run() { final UseClassPathAdjuster useClassPathAdjuster = testClass.getAnnotation(UseClassPathAdjuster.class); return MockClassLoaderFactory.this.createMockClassLoader(byteCodeFramework, classesToLoadByMockClassloader, useClassPathAdjuster, extraMockTransformer); } }); } private MockClassLoader createMockClassLoader(final ByteCodeFramework byteCodeFramework, final String[] classesToLoadByMockClassloader, final UseClassPathAdjuster useClassPathAdjuster, final MockTransformer... extraMockTransformer) { return MockClassLoaderBuilder.create(byteCodeFramework) .forTestClass(testClass) .addIgnorePackage(packagesToIgnore) .addClassesToModify(classesToLoadByMockClassloader) .addClassPathAdjuster(useClassPathAdjuster) .addExtraMockTransformers(extraMockTransformer) .build(); } private void initialize(final ClassLoader mockLoader) { new MockPolicyInitializerImpl(testClass).initialize(mockLoader); } private boolean isContextClassLoaderShouldBeUsed(String[] classesToLoadByMockClassloader) { return (classesToLoadByMockClassloader == null || classesToLoadByMockClassloader.length == 0) && !hasMockPolicyProvidedClasses(testClass); } private String[] makeSureArrayContainsTestClassName(String[] arrayOfClassNames, String testClassName) { if (null == arrayOfClassNames || 0 == arrayOfClassNames.length) { return new String[]{testClassName}; } else { List modifiedArrayOfClassNames = new ArrayList(arrayOfClassNames.length + 1); modifiedArrayOfClassNames.add(testClassName); for (String className : arrayOfClassNames) { if (testClassName.equals(className)) { return arrayOfClassNames; } else { modifiedArrayOfClassNames.add(className); } } return modifiedArrayOfClassNames.toArray( new String[arrayOfClassNames.length + 1]); } } /** * @return {@code true} if there are some mock policies that * contributes with classes that should be loaded by the mock * classloader, {@code false} otherwise. */ private boolean hasMockPolicyProvidedClasses(Class testClass) { boolean hasMockPolicyProvidedClasses = false; if (testClass.isAnnotationPresent(MockPolicy.class)) { MockPolicy annotation = testClass.getAnnotation(MockPolicy.class); Class[] value = annotation.value(); hasMockPolicyProvidedClasses = new MockPolicyInitializerImpl(value).needsInitialization(); } return hasMockPolicyProvidedClasses; } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/classloader/PowerMockModified.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.classloader; /** * Interface marker. If an interface extends the PowerMockModified or a class implements * PowerMockModified this means that the interface/class has been modified by PowerMock. */ public interface PowerMockModified { } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/classloader/annotations/MockPolicy.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.core.classloader.annotations; import org.powermock.core.spi.PowerMockPolicy; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * A Mock Policy can be used to make it easier to unit test some code with * PowerMock in isolation from a certain framework. A mock policy implementation * can for example suppress some methods, suppress static initializers or * intercept method calls and change their return value (for example to return a * mock object) for a certain framework or set of classes or interfaces. *

* A mock policy can for example be implemented to avoid writing repetitive * setup code for your tests. Say that you're using a framework X that in order * for you to test it requires that certain methods should always return a mock * implementation. Perhaps some static initializers must be suppressed as well. * Instead of copying this code between tests it would be a good idea to write a * reusable mock policy. */ @Target( { ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited public @interface MockPolicy { /** * @return A list of mock policies that should be used in the test class. */ Class[] value(); } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/classloader/annotations/PowerMockIgnore.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.core.classloader.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** *

* This annotation tells PowerMock to defer the loading of classes with the * names supplied to {@link #value()} to the system classloader. *

*

* For example suppose you'd like to defer the loading of all classes in the * org.myproject package and all its sub-packages but you still like to * prepare "MyClass" for test. Then you do like this: *

*
 * @PowerMockIgnore("org.myproject.*")
 * @PrepareForTest(MyClass.class)
 * @RunWith(PowerMockRunner.class)
 * public class MyTest {
 * ...
 * }
 *
 * 
*

* This is useful in situations when you have e.g. a test/assertion utility * framework (such as something similar to Hamcrest) whose classes must be * loaded by the same classloader as EasyMock, JUnit and PowerMock etc. *

*

* Note that the {@link PrepareForTest} and {@link PrepareOnlyThisForTest} will * have precedence over this annotation. This annotation will have precedence * over the {@link PrepareEverythingForTest} annotation. *

*

* Since PowerMock 1.7.0 list of packages/classes which should be loaded by the * system classloader can be specified with using {@link org.powermock.configuration.PowerMockConfiguration}. * If you want that the test annotated by {@link PowerMockIgnore} then set {@link PowerMockIgnore#globalIgnore()} to false. *

* * @see ClassLoader#getSystemClassLoader() * @see org.powermock.configuration.PowerMockConfiguration */ @Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited public @interface PowerMockIgnore { String[] value() default ""; /** * Set to true if packages from configuration should merge with list of packages/classes from {@link #value()}. * Default value: true * * @return true if packages from configuration should merge with list of packages/classes from {@link #value()} * @since 1.7.0 */ boolean globalIgnore() default true; } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/classloader/annotations/PowerMockListener.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.core.classloader.annotations; import org.powermock.core.spi.PowerMockTestListener; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * The PowerMock listener annotation can be used to tell PowerMock which * listeners should be instantiated and invoked during a test. A listener is * invoked according to the events specified in the * {@link PowerMockTestListener} interface. */ @Target( { ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited public @interface PowerMockListener { Class[] value(); } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/classloader/annotations/PrepareEverythingForTest.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.core.classloader.annotations; import org.powermock.core.classloader.ByteCodeFramework; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * This annotation tells PowerMock to prepare all classes (except certain system * and test related classes) for test. Note that static initializers are * not removed. *

* The annotation should always be combined with the * {@code @RunWith(PowerMockRunner.class)} if using junit 4.x or * *

 * public static TestSuite suite() throws Exception {
 * 	return new PowerMockSuite(MyTestCase.class);
 * }
 * 
* * if using junit3. */ @Target( { ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited public @interface PrepareEverythingForTest { ByteCodeFramework byteCodeFramework() default ByteCodeFramework.Javassist; } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/classloader/annotations/PrepareForTest.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.core.classloader.annotations; import org.powermock.core.IndicateReloadClass; import org.powermock.core.classloader.ByteCodeFramework; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * This annotation tells PowerMock to prepare certain classes for testing. * Classes needed to be defined using this annotation are typically those that * needs to be byte-code manipulated. This includes final classes, classes with * final, private, static or native methods that should be mocked and also * classes that should be return a mock object upon instantiation. *

* This annotation can be placed at both test classes and individual test * methods. If placed on a class all test methods in this test class will be * handled by PowerMock (to allow for testability). To override this behavior * for a single method just place a {@code @PrepareForTest} annotation * on the specific test method. This is useful in situations where for example * you'd like to modify class X in test method A but in test method B you want X * to be left intact. In situations like this you place a * {@code @PrepareForTest} on method B and exclude class X from the * {@link #value()} list. *

* Sometimes you need to prepare inner classes for testing, this can be done by * suppling the fully-qualified name of the inner-class that should be mocked to * the {@link #fullyQualifiedNames()} list. *

* You can also prepare whole packages for test by using wildcards: * *

 * @PrepareForTest(fullyQualifiedNames="com.mypackage.*")
 * 
* *

* The annotation should always be combined with the * {@code @RunWith(PowerMockRunner.class)} if using junit 4.x or * *

 * public static TestSuite suite() throws Exception {
 *     return new PowerMockSuite(MyTestCase.class);
 * }
 * 
* * if using junit3. *

* The difference between this annotation and the {@link PrepareOnlyThisForTest} * annotation is that this annotation modifies the specified classes and all its * super classes whereas the {@link PrepareOnlyThisForTest} annotation * manipulates only the specified classes. */ @Target( { ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited public @interface PrepareForTest { Class[] value() default IndicateReloadClass.class; String[] fullyQualifiedNames() default ""; ByteCodeFramework byteCodeFramework() default ByteCodeFramework.Javassist; } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/classloader/annotations/PrepareOnlyThisForTest.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.core.classloader.annotations; import org.powermock.core.IndicateReloadClass; import org.powermock.core.classloader.ByteCodeFramework; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * This annotation tells PowerMock to prepare certain classes for testing. * Classes needed to be defined using this annotation are typically those that * needs to be byte-code manipulated. This includes final classes, classes with * final, private, static or native methods that should be mocked and also * classes that should be return a mock object upon instantiation. *

* This annotation can be placed at both test classes and individual test * methods. If placed on a class all test methods in this test class will be * handled by PowerMock (to allow for testability). To override this behavior * for a single method just place a {@code @PrepareForTest} annotation * on the specific test method. This is useful in situations where for example * you'd like to modify class X in test method A but in test method B you want X * to be left intact. In situations like this you place a * {@code @PrepareForTest} on method B and exclude class X from the * {@link #value()} list. *

* Sometimes you need to prepare inner classes for testing, this can be done by * suppling the fully-qualified name of the inner-class that should be mocked to * the {@link #fullyQualifiedNames()} list. * *

* The annotation should always be combined with the * {@code @RunWith(PowerMockRunner.class)} if using junit 4.x or * *

 * public static TestSuite suite() throws Exception {
 * 	return new PowerMockSuite(MyTestCase.class);
 * }
 * 
* * if using junit3. *

* The difference between this annotation and the {@link PrepareForTest} * annotation is that this annotation only modifies the specified classes * whereas the {@link PrepareForTest} annotation manipulates the full class * hierarchy. This annotation is recommend if you want full control over which * classes that are byte-code manipulated. */ @Target( { ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited public @interface PrepareOnlyThisForTest { Class[] value() default IndicateReloadClass.class; String[] fullyQualifiedNames() default ""; ByteCodeFramework byteCodeFramework() default ByteCodeFramework.Javassist; } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/classloader/annotations/SuppressStaticInitializationFor.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.core.classloader.annotations; import org.powermock.core.classloader.ByteCodeFramework; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Use this annotation to suppress static initializers (constructors) for one or * more classes. *

* The reason why an annotation is needed for this is because we need to know at * load-time if the static constructor execution for this * class should be skipped or not. Unfortunately we cannot pass the class as the * value parameter to the annotation (and thus get type-safe values) because * then the class would be loaded before PowerMock could have suppressed its * constructor. */ @Target( { ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited public @interface SuppressStaticInitializationFor { String[] value() default ""; ByteCodeFramework byteCodeFramework() default ByteCodeFramework.Javassist; } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/classloader/annotations/UseClassPathAdjuster.java ================================================ /* * Copyright 2013 Jonas Berlin * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.core.classloader.annotations; import org.powermock.core.classloader.javassist.ClassPathAdjuster; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Use this annotation to enable adjusting of the class path used by powermock * to locate class files. * @deprecated Class path adjuster is supported only for Javassist and will be removed in next release. */ @Target( { ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @Deprecated() public @interface UseClassPathAdjuster { Class value(); } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/classloader/javassist/ClassPathAdjuster.java ================================================ /* * Copyright 2013 Jonas Berlin * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.core.classloader.javassist; import javassist.ClassPool; import org.powermock.core.classloader.annotations.UseClassPathAdjuster; /** * This interface can be used to adjust the classpath used by powermock to locate * class files. Use the @{@link UseClassPathAdjuster} to activate. */ public interface ClassPathAdjuster { void adjustClassPath(ClassPool classPool); } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/classloader/javassist/ClassPoolFactory.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.classloader.javassist; import javassist.ClassClassPath; import javassist.ClassPool; import org.powermock.core.classloader.annotations.UseClassPathAdjuster; class ClassPoolFactory { private UseClassPathAdjuster useClassPathAdjuster; ClassPoolFactory(UseClassPathAdjuster useClassPathAdjuster) { this.useClassPathAdjuster = useClassPathAdjuster; } ClassPool create() { ClassPool classPool = new ClassPool(); classPool.appendClassPath(new ClassClassPath(this.getClass())); if (useClassPathAdjuster != null) { try { Class value = useClassPathAdjuster.value(); ClassPathAdjuster classPathAdjuster = value.newInstance(); classPathAdjuster.adjustClassPath(classPool); } catch (Exception e) { throw new RuntimeException("Error instantiating class path adjuster", e); } } return classPool; } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/classloader/javassist/JavaAssistClassMarkerFactory.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.classloader.javassist; import javassist.ClassPool; import javassist.CtClass; import org.powermock.core.classloader.ClassMarker; import org.powermock.core.classloader.PowerMockModified; import org.powermock.core.transformers.ClassWrapper; class JavaAssistClassMarkerFactory { static ClassMarker createClassMarker(ClassPool classPool) { return new InterfaceClassMarker(classPool); } /** * The implementation of the {@link ClassMarker} which use an interface to mark type. * * @see PowerMockModified */ private static class InterfaceClassMarker implements ClassMarker { private final ClassPool classPool; InterfaceClassMarker(ClassPool classPool) { this.classPool = classPool; } /** * Mark type as loaded by PowerMock * * @param type to mark. */ @Override public void mark(ClassWrapper type) { T unwrapped = type.unwrap(); if (unwrapped instanceof CtClass) { mark((CtClass) unwrapped); } } public void mark(CtClass type) { CtClass powerMockInterface = classPool.makeInterface("org.powermock.core.classloader.PowerMockModified"); type.addInterface(powerMockInterface); powerMockInterface.detach(); } } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/classloader/javassist/JavassistMockClassLoader.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.classloader.javassist; import javassist.ClassPool; import javassist.CtClass; import javassist.NotFoundException; import org.powermock.core.classloader.MockClassLoader; import org.powermock.core.classloader.MockClassLoaderConfiguration; import org.powermock.core.classloader.annotations.UseClassPathAdjuster; import org.powermock.core.transformers.ClassWrapper; import org.powermock.core.transformers.javassist.support.JavaAssistClassWrapperFactory; import java.security.ProtectionDomain; public class JavassistMockClassLoader extends MockClassLoader { public static final String CGLIB_ENHANCER = "net.sf.cglib.proxy.Enhancer$EnhancerKey$$KeyFactoryByCGLIB$$"; public static final String CGLIB_METHOD_WRAPPER = "net.sf.cglib.core.MethodWrapper$MethodWrapperKey$$KeyFactoryByCGLIB"; private final ClassPool classPool; public JavassistMockClassLoader(String[] classesToMock) { this(classesToMock, new String[0], null); } public JavassistMockClassLoader(String[] classesToMock, String[] packagesToDefer, UseClassPathAdjuster useClassPathAdjuster) { this(new MockClassLoaderConfiguration(classesToMock, packagesToDefer), useClassPathAdjuster); } public JavassistMockClassLoader(MockClassLoaderConfiguration configuration) { this(configuration, null); } public JavassistMockClassLoader(MockClassLoaderConfiguration configuration, UseClassPathAdjuster useClassPathAdjuster) { super(configuration, new JavaAssistClassWrapperFactory()); classPool = new ClassPoolFactory(useClassPathAdjuster).create(); classMarker = JavaAssistClassMarkerFactory.createClassMarker(classPool); } @Override protected Class loadUnmockedClass(String name, ProtectionDomain protectionDomain) throws ClassFormatError, ClassNotFoundException { byte bytes[] = null; try { /* * TODO This if-statement is a VERY ugly hack to avoid the * java.lang.ExceptionInInitializerError caused by * "javassist.NotFoundException: * net.sf.cglib.proxy.Enhancer$EnhancerKey$$KeyFactoryByCGLIB$$7fb24d72 * ". This happens after the * se.jayway.examples.tests.privatefield. * SimplePrivateFieldServiceClassTest#testUseService(..) tests has * been run and all other tests will fail if this class is tried to * be loaded. Atm I have found no solution other than this ugly hack * to make it work. We really need to investigate the real cause of * this behavior. */ if (!name.startsWith(CGLIB_ENHANCER) && !name.startsWith(CGLIB_METHOD_WRAPPER)) { final CtClass ctClass = classPool.get(name); if (ctClass.isFrozen()) { ctClass.defrost(); } bytes = ctClass.toBytecode(); } } catch (NotFoundException e) { return ClassLoader.getSystemClassLoader().loadClass(name); } catch (Exception e) { throw new RuntimeException("Failed to loaded class " + name, e); } return bytes == null ? null : defineClass(name, bytes, 0, bytes.length, protectionDomain); } protected byte[] defineAndTransformClass(String name, ProtectionDomain protectionDomain) { final byte[] clazz; ClassPool.doPruning = false; try { CtClass type = classPool.get(name); ClassWrapper wrappedType = classWrapperFactory.wrap(type); wrappedType = transformClass(wrappedType); type = wrappedType.unwrap(); /* * ClassPool may cause huge memory consumption if the number of CtClass * objects becomes amazingly large (this rarely happens since Javassist * tries to reduce memory consumption in various ways). To avoid this * problem, you can explicitly remove an unnecessary CtClass object from * the ClassPool. If you call detach() on a CtClass object, then that * CtClass object is removed from the ClassPool. */ type.detach(); clazz = type.toBytecode(); } catch (Exception e) { throw new IllegalStateException("Failed to transform class with name " + name + ". Reason: " + e.getMessage(), e); } return clazz; } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/reporter/MockingFrameworkReporter.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.reporter; /** * The instance of the interface is used to replace default mocking frameworks * exception message via message specific for PowerMock use-cases. */ public interface MockingFrameworkReporter { /** * Start replacing mocking frameworks exception message */ void enable(); /** * Stop replacing mocking frameworks exception message */ void disable(); } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/reporter/PowerMockReporter.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.reporter; /** * The interface is used to provide a user well-defined exception description. */ public interface PowerMockReporter { void classNotPrepared(Class type); } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/reporter/PowerMockReporterFactory.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.reporter; /** * */ @SuppressWarnings("unused") public interface PowerMockReporterFactory { PowerMockReporter createPowerMockReporter(); } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/spi/DefaultBehavior.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.core.spi; /** * Interface that provides the replay, verify and reset behavior for mock * objects and classes. */ public interface DefaultBehavior { /** * Replay the given objects or classes. May throw exception if replay is not * needed or not supported. * * @param mocks * The object(s) to replay. May be {@code null}. * * @return the result of the replay (may be {@code null}). */ Object replay(Object... mocks); /** * Reset the given objects or classes. May throw exception if reset is not * needed or not supported. * * @param mocks * The object(s) to replay. May be {@code null}. * * @return the result of the replay (may be {@code null}). */ Object reset(Object... mocks); } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/spi/MethodInvocationControl.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.core.spi; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; /** * The purpose of a method invocation control is to invoke a proxy to simulate a * method call. It also has functionality to replay and verify mocks (which may * not be needed for certain invocation controls) and to check whether a certain * method is mocked or not. * */ public interface MethodInvocationControl extends InvocationHandler, DefaultBehavior { /** * Determine whether a certain method is mocked by this Invocation Control. * * @param method * The method that should be checked. * @return {@code true} if the method is mocked, {@code false} * otherwise. */ boolean isMocked(Method method); } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/spi/NewInvocationControl.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.core.spi; import org.powermock.core.spi.support.InvocationSubstitute; /** * A new invocation control pairs up a {@link InvocationSubstitute} with the * mock object created when invoking * {@link InvocationSubstitute#performSubstitutionLogic(Object...)} object. * */ public interface NewInvocationControl extends DefaultBehavior { /** * Invoke the constructor invocation control * @param type invocation target type * @param args arguments of constructor invocation * @param sig parameters of a constructor * @return result of invocation */ Object invoke(Class type, Object[] args, Class[] sig) throws Exception; /** * Expect a call to the new instance substitution logic. * @param arguments constructor arguments * @return result of stubbing a constructor. Result depends on mocking framework. */ T expectSubstitutionLogic(Object... arguments) throws Exception; } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/spi/PowerMockPolicy.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.core.spi; import org.powermock.mockpolicies.MockPolicyClassLoadingSettings; import org.powermock.mockpolicies.MockPolicyInterceptionSettings; /** * This interface can be implemented to create policies for certain frameworks * to make it easier for users to test their code in isolation from these * frameworks. A mock policy implementation can for example suppress some * methods, suppress static initializers or intercept method calls and change * their return value (for example to return a mock object). A mock policy * implementation must be stateless. The reason why there are two methods * for applying settings is that PowerMock needs to know which classes that * should be modified by the mock class loader before these classes have * loaded. The {@link #applyClassLoadingPolicy(MockPolicyClassLoadingSettings)} * tells PowerMock which classes that should be loaded and then the * {@link #applyInterceptionPolicy(MockPolicyInterceptionSettings)} is called * from the mock class-loader itself. This means you can create mocks for e.g. * final and static methods in the * {@link #applyInterceptionPolicy(MockPolicyInterceptionSettings)} which would * not have been possible otherwise. *

* Since mock policies can be chained subsequent policies can override behavior * of a previous policy. To avoid accidental overrides it's recommended * add behavior instead of setting behavior since the latter * overrides all previous configurations. */ public interface PowerMockPolicy { /** * Apply all class-loading related policies that must be present before the * interception policies can take place. * * @param settings * The settings objects where the class-loading policies can be * applied. */ void applyClassLoadingPolicy(MockPolicyClassLoadingSettings settings); /** * Apply the interception policies, for example which methods that should be * suppressed or which methods that should be intercepted and return some * else than their original value. * * @param settings * The settings objects where the interception policies can be * applied. */ void applyInterceptionPolicy(MockPolicyInterceptionSettings settings); } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/spi/PowerMockTestListener.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.core.spi; import org.powermock.core.spi.testresult.TestMethodResult; import org.powermock.core.spi.testresult.TestSuiteResult; import java.lang.reflect.Method; /** * This interface should be implemented by all PowerMock test listeners. The * listener will be notified on the events present in this interface. Please * note that a listener cannot hold state. */ public interface PowerMockTestListener { /** * Invoked once before the test run has started. * * @param testClass * The type of the test to be executed. * @param testMethods * The test methods that will be executed during the test. * @throws Exception * If something unexpected occurs. */ void beforeTestSuiteStarted(Class testClass, Method[] testMethods) throws Exception; /** * Invoked before each test method. * * @param testInstance * The test case instance. * @param method * The test method that is currently executed. * @param arguments * The arguments passed to the test method if any. May be an * empty array but never {@code null}. * @throws Exception * If something unexpected occurs. */ void beforeTestMethod(Object testInstance, Method method, Object[] arguments) throws Exception; /** * Invoked after each test method. * * * @param testInstance The test case instance. * * @param method * The test method that is currently executed. * @param arguments * The arguments passed to the test method if any. May be an * empty array but never {@code null}. * @param testResult * The outcome of the test method. * @throws Exception * If something unexpected occurs. */ void afterTestMethod(Object testInstance, Method method, Object[] arguments, TestMethodResult testResult) throws Exception; /** * Invoked after a test suite has ended. * * @param testClass * The type of the test to be executed. * @param methods * The test methods that were executed during the test. * @param testResult * The outcome of the test suite. * @throws Exception * If something unexpected occurs. */ void afterTestSuiteEnded(Class testClass, Method[] methods, TestSuiteResult testResult) throws Exception; } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/spi/listener/AnnotationEnablerListener.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.core.spi.listener; import org.powermock.core.spi.PowerMockTestListener; import java.lang.annotation.Annotation; public interface AnnotationEnablerListener extends PowerMockTestListener { /** * @return The mock annotations considered by this annotation enabler. */ Class[] getMockAnnotations(); } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/spi/support/AbstractPowerMockTestListenerBase.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.core.spi.support; import org.powermock.core.spi.PowerMockTestListener; import org.powermock.core.spi.testresult.TestMethodResult; import org.powermock.core.spi.testresult.TestSuiteResult; import java.lang.reflect.Method; /** * An empty implementation of the {@link PowerMockTestListener} interface. May * be inherited by clients that wants to provide empty implementations of some * of the interface methods. */ public class AbstractPowerMockTestListenerBase implements PowerMockTestListener { /** * Provides an empty implementation. */ @Override public void afterTestMethod(Object testInstance, Method method, Object[] arguments, TestMethodResult testResult) throws Exception { } /** * Provides an empty implementation. */ @Override public void beforeTestMethod(Object testInstance, Method method, Object[] arguments) throws Exception { } /** * Provides an empty implementation. */ @Override public void beforeTestSuiteStarted(Class testClass, Method[] testMethods) throws Exception { } /** * Provides an empty implementation. */ @Override public void afterTestSuiteEnded(Class testClass, Method[] methods, TestSuiteResult testResult) throws Exception { } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/spi/support/InvocationSubstitute.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.core.spi.support; /** * A class that can be used as a substitution instead of mocking a particular * class. For example when mocking a new instance call you can fake the * constructor invocation by creating a mock object (A) for this class and * invoke the {@link #performSubstitutionLogic(Object...)} method instead with * the constructor arguments. The interception process must take care of doing * this. Also remember that behaviors such as replay and/or verify must be * performed on (A). * */ public interface InvocationSubstitute { T performSubstitutionLogic(Object... arguments) throws Exception; } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/spi/testresult/Result.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.core.spi.testresult; public enum Result { SUCCESSFUL, FAILED, IGNORED } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/spi/testresult/TestMethodResult.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.core.spi.testresult; public interface TestMethodResult { Result getResult(); } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/spi/testresult/TestSuiteResult.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.core.spi.testresult; public interface TestSuiteResult { int getTestCount(); int getIgnoreCount(); int getSuccessCount(); int getFailureCount(); Result getResult(); } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/spi/testresult/impl/TestMethodResultImpl.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.core.spi.testresult.impl; import org.powermock.core.spi.testresult.Result; import org.powermock.core.spi.testresult.TestMethodResult; public class TestMethodResultImpl implements TestMethodResult { private final Result result; public TestMethodResultImpl(Result result) { super(); this.result = result; } @Override public Result getResult() { return result; } @Override public String toString() { return result.toString(); } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/spi/testresult/impl/TestSuiteResultImpl.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.core.spi.testresult.impl; import org.powermock.core.spi.testresult.Result; import org.powermock.core.spi.testresult.TestSuiteResult; public class TestSuiteResultImpl implements TestSuiteResult { private int failureCount; private int successCount; private int testCount; private int ignoreCount; public TestSuiteResultImpl() { } public TestSuiteResultImpl(int failureCount, int successCount, int testCount, int ignoreCount) { this.failureCount = failureCount; this.successCount = successCount; this.testCount = testCount; this.ignoreCount = ignoreCount; } @Override public int getFailureCount() { return failureCount; } @Override public int getSuccessCount() { return successCount; } @Override public int getIgnoreCount() { return ignoreCount; } @Override public Result getResult() { Result result = Result.SUCCESSFUL; if (testCount == 0) { result = Result.IGNORED; } else if (failureCount != 0) { result = Result.FAILED; } return result; } @Override public int getTestCount() { return testCount; } @Override public String toString() { return getResult().toString(); } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/testlisteners/FieldDefaulter.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.core.testlisteners; import org.powermock.core.spi.support.AbstractPowerMockTestListenerBase; import org.powermock.core.spi.testresult.TestMethodResult; import org.powermock.reflect.Whitebox; import org.powermock.reflect.internal.TypeUtils; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Set; /** * A test listener that automatically set all instance fields to their default * values after each test method. E.g. an object field is set to * {@code null}, an {@code int} field is set to 0 and so on. */ public class FieldDefaulter extends AbstractPowerMockTestListenerBase { @Override public void afterTestMethod(Object testInstance, Method method, Object[] arguments, TestMethodResult testResult) throws Exception { Set allFields = Whitebox.getAllInstanceFields(testInstance); for (Field field : allFields) { field.set(testInstance, TypeUtils.getDefaultValue(field.getType())); } } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/testlisteners/GlobalNotificationBuildSupport.java ================================================ /* * Copyright 2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.core.testlisteners; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * Core static utility to help modules, such as PowerMockRunner, that needs to * communicate with some 3rd-party framework in order to properly fire * events to PowerMockTestListener instances. */ public class GlobalNotificationBuildSupport { public interface Callback { void suiteClassInitiated(Class testClass); void testInstanceCreated(Object testInstance); } private static final Map testSuiteCallbacks = new ConcurrentHashMap(); private static final Map, Callback> initiatedTestSuiteClasses = new ConcurrentHashMap, Callback>(); private static final ThreadLocal> pendingInitiatedTestClass = new ThreadLocal>(); public static void prepareTestSuite( String testClassName, Callback callback) { if (testSuiteCallbacks.containsKey(testClassName)) { throw new IllegalStateException( "Needs to wait for concurrent test-suite execution to start!"); } else { testSuiteCallbacks.put(testClassName, callback); Class initiatedTestClass = pendingInitiatedTestClass.get(); if (null != initiatedTestClass && initiatedTestClass.getName().equals(testClassName)) { System.err.println("Detected late test-suite preparation of " + "already initiated test-" + initiatedTestClass); testClassInitiated(initiatedTestClass); } } } public static void testClassInitiated(Class testClass) { if (!initiatedTestSuiteClasses.containsKey(testClass)) { Callback callback = testSuiteCallbacks.get(testClass.getName()); if (null == callback) { pendingInitiatedTestClass.set(testClass); } else { initiatedTestSuiteClasses.put(testClass, callback); callback.suiteClassInitiated(testClass); pendingInitiatedTestClass.set(null); } } } private static int countInitializersInTrace(final String className) { int initializerCount = 0; for (StackTraceElement ste : Thread.currentThread().getStackTrace()) { if ("".equals(ste.getMethodName()) && className.equals(ste.getClassName()) && 2 <= ++initializerCount) { return 2; } } return initializerCount; } public static void testInstanceCreated(Object testInstance) { for (Class c = testInstance.getClass(); Object.class != c; c = c.getSuperclass()) { Callback callback = initiatedTestSuiteClasses.get(c); if (null != callback) { if (1 == countInitializersInTrace(c.getName())) { callback.testInstanceCreated(testInstance); } return; } } } public static void closeTestSuite(Class testClass) { Callback callback = initiatedTestSuiteClasses.remove(testClass); if (null != callback && !initiatedTestSuiteClasses.values().contains(callback)) { testSuiteCallbacks.values().remove(callback); } } public static void closePendingTestSuites(Callback callback) { testSuiteCallbacks.values().remove(callback); initiatedTestSuiteClasses.values() .removeAll(java.util.Collections.singleton(callback)); } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/transformers/ClassWrapper.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.transformers; /** * An interface represents an abstraction of the class to be able to pass class to different byte-code instrumentation frameworks. * * @param - original class specific for byte-code modification framework. * @author Arthur Zagretdinov */ public interface ClassWrapper { /** * Check if class is interface * * @return true if class is an interface. */ boolean isInterface(); /** * Get original object which represent class * * @return instance of original object. */ T unwrap(); /** * Wrap changed implementation to get a new instance of ClassWrapper * @param original - original class specific for byte-code modification framework. * @return a new instance of ClassWrapper */ ClassWrapper wrap(T original); } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/transformers/ClassWrapperFactory.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.transformers; /** * An implementation should wrap original instance. * * @param - original class specific for byte-code modification framework. * @author Arthur Zagretdinov */ public interface ClassWrapperFactory { /** * @param original - original class specific for byte-code modification framework. * @return wrapped original class as {@link ClassWrapper} */ ClassWrapper wrap(T original); } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/transformers/MethodSignatureWriter.java ================================================ package org.powermock.core.transformers; import java.lang.reflect.Method; public interface MethodSignatureWriter { String signatureFor(T method); String signatureForReflection(Method method); } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/transformers/MethodSignatures.java ================================================ package org.powermock.core.transformers; import javassist.CtClass; import javassist.CtMethod; import javassist.NotFoundException; import net.bytebuddy.description.method.MethodDescription; import org.powermock.PowerMockInternalException; import java.lang.reflect.Method; public enum MethodSignatures { ByteBuddy { @Override public MethodSignatureWriter methodSignatureWriter() { return new ByteBuddyMethodSignatureWriterWriter(); } }, Javassist { @Override public MethodSignatureWriter methodSignatureWriter() { return new JavassistMethodSignatureWriterWriter(); } }; public abstract MethodSignatureWriter methodSignatureWriter(); private static class ByteBuddyMethodSignatureWriterWriter implements MethodSignatureWriter { @Override public String signatureFor(final MethodDescription method) { return method.toGenericString(); } @Override public String signatureForReflection(final Method method) { return method.toString(); } } private static class JavassistMethodSignatureWriterWriter implements MethodSignatureWriter { @Override public String signatureFor(final CtMethod m) { try { CtClass[] paramTypes = m.getParameterTypes(); String[] paramTypeNames = new String[paramTypes.length]; for (int i = 0; i < paramTypeNames.length; ++i) { paramTypeNames[i] = paramTypes[i].getSimpleName(); } return createSignature( m.getDeclaringClass().getSimpleName(), m.getReturnType().getSimpleName(), m.getName(), paramTypeNames); } catch (NotFoundException e) { throw new PowerMockInternalException(e); } } @Override public String signatureForReflection(final Method m) { Class[] paramTypes = m.getParameterTypes(); String[] paramTypeNames = new String[paramTypes.length]; for (int i = 0; i < paramTypeNames.length; ++i) { paramTypeNames[i] = paramTypes[i].getSimpleName(); } return createSignature( m.getDeclaringClass().getSimpleName(), m.getReturnType().getSimpleName(), m.getName(), paramTypeNames); } private String createSignature( String testClass, String returnType, String methodName, String[] paramTypes) { StringBuilder builder = new StringBuilder(testClass) .append('\n').append(returnType) .append('\n').append(methodName); for (String param : paramTypes) { builder.append('\n').append(param); } return builder.toString(); } } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/transformers/MockTransformer.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.transformers; /** * Interface that all mock transformers must implement. The purpose of a mock * transformer is to create a modified version of a {@code Class} so that * it is mock enabled. * * @author Johan Haleby */ public interface MockTransformer { /** * Transforms the {@code clazz}. * * @param clazz The class to be * transform into a mock enabled class. * @return A {@code ClassWrapper} representation of the mocked class. */ ClassWrapper transform(ClassWrapper clazz) throws Exception; } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/transformers/MockTransformerChain.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.transformers; import java.util.Collection; /** * Interface represent chain of {@link MockTransformer}. * Each transformer in chain instruments a class to enable one of mocking feature. * * @author Arthur Zagretdinov */ public interface MockTransformerChain { /** * Go thought all transformers in chain and instrument the {@code clazz}. * * @param clazz The class to be instrument to enabled class mocking. * @return A {@code ClassWrapper} representation of the instrumented class. */ ClassWrapper transform(ClassWrapper clazz) throws Exception; /** * Filter and return collection of {@link MockTransformer} which fit the predicate. * @param predicate to test MockTransformer * @return collection of {@link MockTransformer} which fit the {@link FilterPredicate} */ Collection filter(FilterPredicate predicate); interface FilterPredicate { boolean test(MockTransformer mockTransformer); } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/transformers/MockTransformerChainFactory.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.transformers; import java.util.List; /** * An implementation of interface should create a {@link MockTransformerChain} with full set of required transformers to enable all mocking features. * * @author Arthur Zagretdinov */ public interface MockTransformerChainFactory { /** * Create an {@link MockTransformerChain} with using default strategy {@link TransformStrategy#CLASSLOADER} * * @return an instance of MockTransformerChain */ MockTransformerChain createDefaultChain(); /** * Create an {@link MockTransformerChain} with using the given transformStrategy * * @return an instance of MockTransformerChain */ MockTransformerChain createDefaultChain(TransformStrategy transformStrategy); /** * Create an {@link MockTransformerChain} with using default strategy {@link TransformStrategy#CLASSLOADER} and with the given extraMockTransformers * * @return an instance of MockTransformerChain */ MockTransformerChain createDefaultChain(List extraMockTransformers); /** * Create an {@link MockTransformerChain} with using the given testClassTransformer as transformer for test class. * * @return an instance of MockTransformerChain */ MockTransformerChain createTestClassChain(MockTransformer testClassTransformer); } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/transformers/TestClassAwareTransformer.java ================================================ package org.powermock.core.transformers; /** * 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}. * IMPORTANT * This may take affect only with running PowerMock with class loader mode, a testClass will not be set in case if PowerMock used as JavaAgent. */ public interface TestClassAwareTransformer { void setTestClass(Class testClass); } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/transformers/TestClassTransformer.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.transformers; import org.powermock.core.transformers.javassist.ConstructorsMockTransformer; import java.lang.annotation.Annotation; import java.lang.reflect.Method; /** * MockTransformer implementation that will make PowerMock test-class * enhancements for four purposes... * 1) Make test-class static initializer and constructor send crucial details * (for PowerMockTestListener events) to GlobalNotificationBuildSupport so that * this information can be forwarded to whichever * facility is used for composing the PowerMockTestListener events. * 2) Removal of test-method annotations as a mean to achieve test-suite * chunking! * 3) Restore original test-class constructors` accesses * (in case they have all been made public by {@link ConstructorsMockTransformer}) * - to avoid that multiple public test-class constructors cause * a delegate runner from JUnit (or 3rd party) to bail out with an * error message such as "Test class can only have one constructor". * 4) Set test-class defer constructor (if exist) as protected instead of public. * Otherwise a delegate runner from JUnit (or 3rd party) might get confused by * the presence of more than one test-class constructor and bail out with an * error message such as "Test class can only have one constructor". *

* The #3 and #4 enhancements will also be enforced on the constructors * of classes that are nested within the test-class. */ public abstract class TestClassTransformer implements MockTransformer { private final Class testClass; private final Class testMethodAnnotationType; private final MethodSignatureWriter methodSignatureWriter; public TestClassTransformer(Class testClass, Class testMethodAnnotationType, MethodSignatureWriter methodSignatureWriter) { this.testClass = testClass; this.testMethodAnnotationType = testMethodAnnotationType; this.methodSignatureWriter = methodSignatureWriter; } protected String signatureOf(final M method) { return methodSignatureWriter.signatureFor(method); } protected String signatureOf(final Method m) { return methodSignatureWriter.signatureForReflection(m); } protected Class getTestMethodAnnotationType() { return testMethodAnnotationType; } protected Class getTestClass() { return testClass; } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/transformers/TestClassTransformerBuilder.java ================================================ package org.powermock.core.transformers; import javassist.CtMethod; import org.powermock.core.classloader.ByteCodeFramework; import org.powermock.core.transformers.javassist.testclass.ForMethodsJavaAssistTestClassTransformer; import org.powermock.core.transformers.javassist.testclass.FromAllMethodsExceptJavaAssistTestClassTransformer; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.Collection; public class TestClassTransformerBuilder { public static TestClassTransformerBuilder forTestClass(final Class testClass) { return new TestClassTransformerBuilder(testClass); } private final Class testClass; private TestClassTransformerBuilder(final Class testClass) { this.testClass = testClass; } public RemovesTestMethodAnnotation removesTestMethodAnnotation(final Class testMethodAnnotation) { return new RemovesTestMethodAnnotation(testClass, testMethodAnnotation, ByteCodeFramework.getByteCodeFrameworkForTestClass(testClass)); } public TestClassTransformerBuilderWithClue bytecodeFrameworkClue(final Method method) { return new TestClassTransformerBuilderWithClue(testClass, method); } public static class TestClassTransformerBuilderWithClue { private final Class testClass; private final Method method; private TestClassTransformerBuilderWithClue(final Class testClass, final Method method) { this.testClass = testClass; this.method = method; } public RemovesTestMethodAnnotation removesTestMethodAnnotation(final Class testMethodAnnotation) { return new RemovesTestMethodAnnotation(testClass, testMethodAnnotation, ByteCodeFramework.getByteCodeFrameworkForMethod(testClass, method)); } } public static class RemovesTestMethodAnnotation { private final Class testMethodAnnotation; private final Class testClass; private final ByteCodeFramework byteCodeFramework; private RemovesTestMethodAnnotation(final Class testClass, final Class testMethodAnnotation, final ByteCodeFramework byteCodeFramework) { this.testClass = testClass; this.testMethodAnnotation = testMethodAnnotation; this.byteCodeFramework = byteCodeFramework; } public TestClassTransformer fromMethods(final Collection testMethodsThatRunOnOtherClassLoaders) { switch (byteCodeFramework) { case Javassist: return new ForMethodsJavaAssistTestClassTransformer( testClass, testMethodAnnotation, MethodSignatures.Javassist.methodSignatureWriter(), testMethodsThatRunOnOtherClassLoaders ); default: throw new IllegalArgumentException(String.format("Unknown bytecode framework `%s`", byteCodeFramework)); } } public TestClassTransformer fromAllMethodsExcept(Method singleMethodToRunOnTargetClassLoader) { switch (byteCodeFramework) { case Javassist: return new FromAllMethodsExceptJavaAssistTestClassTransformer( testClass, testMethodAnnotation, MethodSignatures.Javassist.methodSignatureWriter(), singleMethodToRunOnTargetClassLoader ); default: throw new IllegalArgumentException(String.format("Unknown bytecode framework `%s`", byteCodeFramework)); } } } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/transformers/TransformStrategy.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.core.transformers; /** * The enum provide information for {@link MockTransformer} have PowerMock is started via Runner(FactoryObject), Rule or JavaAgent */ public enum TransformStrategy { CLASSLOADER { @Override public boolean isClassloaderMode() { return true; } @Override public boolean isAgentMode() { return false; } }, INST_REDEFINE { @Override public boolean isClassloaderMode() { return false; } @Override public boolean isAgentMode() { return true; } }; /** * Check if this strategy is supported by class loader. It means that more byte code instrumenting are allowed: like adding constructor, * changeling method signature and so on * @return true if a strategy is supported by class loader. */ public abstract boolean isClassloaderMode(); /** * Check if this strategy is supported only by Java Agent. It means that lest byte code instrumenting are allowed and PowerMock should * avoid using some instrument things. * @return true if a strategy is supported only by Java Agent */ public abstract boolean isAgentMode(); } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/transformers/javassist/AbstractJavaAssistMockTransformer.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.transformers.javassist; import javassist.CtClass; import org.powermock.core.transformers.ClassWrapper; import org.powermock.core.transformers.MockTransformer; import org.powermock.core.transformers.TransformStrategy; public abstract class AbstractJavaAssistMockTransformer implements MockTransformer { private final TransformStrategy strategy; public AbstractJavaAssistMockTransformer(TransformStrategy strategy) { this.strategy = strategy; } @Override public ClassWrapper transform(final ClassWrapper clazz) throws Exception { if (clazz.unwrap() instanceof CtClass) { CtClass classImpl = clazz.unwrap(); if (classImpl != null) { transform(classImpl); } } return clazz; } public abstract CtClass transform(CtClass clazz) throws Exception; protected TransformStrategy getStrategy() { return strategy; } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/transformers/javassist/ClassFinalModifierMockTransformer.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.transformers.javassist; import javassist.CtClass; import javassist.Modifier; import javassist.bytecode.AttributeInfo; import javassist.bytecode.ClassFile; import javassist.bytecode.InnerClassesAttribute; import org.powermock.core.transformers.TransformStrategy; import static org.powermock.core.transformers.TransformStrategy.INST_REDEFINE; public class ClassFinalModifierMockTransformer extends AbstractJavaAssistMockTransformer { public ClassFinalModifierMockTransformer(final TransformStrategy strategy) { super(strategy); } @Override public CtClass transform(final CtClass clazz) { if (clazz.isInterface()) { return clazz; } if (getStrategy() != INST_REDEFINE) { if (Modifier.isFinal(clazz.getModifiers())) { clazz.setModifiers(clazz.getModifiers() ^ Modifier.FINAL); } ClassFile classFile = clazz.getClassFile2(); AttributeInfo attribute = classFile.getAttribute(InnerClassesAttribute.tag); if (attribute != null && attribute instanceof InnerClassesAttribute) { InnerClassesAttribute ica = (InnerClassesAttribute) attribute; String name = classFile.getName(); int n = ica.tableLength(); for (int i = 0; i < n; ++i) { if (name.equals(ica.innerClass(i))) { int accessFlags = ica.accessFlags(i); if (Modifier.isFinal(accessFlags)) { ica.setAccessFlags(i, accessFlags ^ Modifier.FINAL); } } } } } return clazz; } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/transformers/javassist/ConstructorsMockTransformer.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.transformers.javassist; import javassist.CtClass; import javassist.CtConstructor; import javassist.Modifier; import javassist.NotFoundException; import org.powermock.core.transformers.TransformStrategy; import static org.powermock.core.transformers.TransformStrategy.CLASSLOADER; /** * Convert all constructors to public */ public class ConstructorsMockTransformer extends AbstractJavaAssistMockTransformer { public ConstructorsMockTransformer(final TransformStrategy strategy) { super(strategy); } @Override public CtClass transform(final CtClass clazz) { if (clazz.isInterface()) { return clazz; } if (getStrategy() == CLASSLOADER) { transform(new CtClass[]{clazz}); // we also need to transform nested class at this time due to JEP181 since JDK11 // otherwise, we might have trouble during further transformation // see github #958 try { CtClass[] nestedClasses = clazz.getDeclaredClasses(); transform(nestedClasses); } catch (NotFoundException ignored) { // ignored } } return clazz; } private static void transform(final CtClass[] clazzArray) { for (CtClass nestedClazz : clazzArray) { for (CtConstructor c : nestedClazz.getDeclaredConstructors()) { final int modifiers = c.getModifiers(); if (!Modifier.isPublic(modifiers)) { c.setModifiers(Modifier.setPublic(modifiers)); } } } } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/transformers/javassist/InstrumentMockTransformer.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.transformers.javassist; import javassist.CannotCompileException; import javassist.CtClass; import org.powermock.core.MockGateway; import org.powermock.core.transformers.TransformStrategy; import org.powermock.core.transformers.javassist.support.PowerMockExpressionEditor; import java.io.File; import java.io.OutputStream; public class InstrumentMockTransformer extends AbstractJavaAssistMockTransformer { private Class mockGetawayClass; public InstrumentMockTransformer(final TransformStrategy strategy) { super(strategy); this.mockGetawayClass = MockGateway.class; } @Override public CtClass transform(final CtClass clazz) throws CannotCompileException { clazz.instrument(new PowerMockExpressionEditor(getStrategy(), clazz, mockGetawayClass)); return clazz; } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/transformers/javassist/JavassistMockTransformerChainFactory.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.transformers.javassist; import org.powermock.core.transformers.MockTransformer; import org.powermock.core.transformers.MockTransformerChain; import org.powermock.core.transformers.MockTransformerChainFactory; import org.powermock.core.transformers.TransformStrategy; import org.powermock.core.transformers.support.DefaultMockTransformerChain; import org.powermock.core.transformers.support.DefaultMockTransformerChain.MockTransformerChainBuilder; import java.util.List; public class JavassistMockTransformerChainFactory implements MockTransformerChainFactory { private static final TransformStrategy DEFAULT = TransformStrategy.CLASSLOADER; @Override public MockTransformerChain createDefaultChain() { return createDefaultChain(DEFAULT); } @Override public MockTransformerChain createDefaultChain(final TransformStrategy transformStrategy) { return createDefaultChainBuilder(transformStrategy).build(); } @Override public MockTransformerChain createDefaultChain(final List extraMockTransformers) { return createDefaultChainBuilder(DEFAULT) .append(extraMockTransformers) .build(); } @Override public MockTransformerChain createTestClassChain(final MockTransformer testClassTransformer) { return createDefaultChainBuilder(DEFAULT) .append(testClassTransformer) .build(); } private MockTransformerChainBuilder createDefaultChainBuilder(final TransformStrategy transformStrategy) { return DefaultMockTransformerChain.newBuilder() .append(new ClassFinalModifierMockTransformer(transformStrategy)) .append(new ConstructorsMockTransformer(transformStrategy)) .append(new InstrumentMockTransformer(transformStrategy)) .append(new PackagePrivateClassesMockTransformer(transformStrategy)) .append(new StaticFinalFieldsMockTransformer(transformStrategy)) .append(new StaticFinalNativeMethodMockTransformer(transformStrategy)) .append(new SuppressStaticInitializerMockTransformer(transformStrategy)) .append(new MethodSizeMockTransformer(transformStrategy)); } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/transformers/javassist/MethodMockTransformer.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.transformers.javassist; import javassist.CannotCompileException; import javassist.CtClass; import javassist.CtMethod; import javassist.Modifier; import javassist.NotFoundException; import org.powermock.core.MockGateway; import org.powermock.core.transformers.TransformStrategy; import static org.powermock.core.transformers.javassist.support.TransformerHelper.VOID; import static org.powermock.core.transformers.javassist.support.TransformerHelper.getCorrectReturnValueType; import static org.powermock.core.transformers.javassist.support.TransformerHelper.getReturnTypeAsString; import static org.powermock.core.transformers.javassist.support.TransformerHelper.shouldSkipMethod; abstract class MethodMockTransformer extends AbstractJavaAssistMockTransformer { private Class mockGetawayClass; MethodMockTransformer(final TransformStrategy strategy) { super(strategy); this.mockGetawayClass = MockGateway.class; } void modifyMethod(final CtMethod method) throws NotFoundException, CannotCompileException { if (!shouldSkipMethod(method)) { // Lookup the method return type final CtClass returnTypeAsCtClass = method.getReturnType(); final String returnTypeAsString = getReturnTypeAsString(method); if (Modifier.isNative(method.getModifiers())) { modifyNativeMethod(method, returnTypeAsCtClass, returnTypeAsString); } else { modifyMethod(method, returnTypeAsCtClass, returnTypeAsString); } } } private void modifyNativeMethod(CtMethod method, CtClass returnTypeAsCtClass, String returnTypeAsString) throws CannotCompileException { String methodName = method.getName(); String returnValue = "($r)value"; if (returnTypeAsCtClass.equals(CtClass.voidType)) { returnValue = VOID; } String classOrInstance = classOrInstance(method); method.setModifiers(method.getModifiers() - Modifier.NATIVE); String code = "Object value = " + mockGetawayClass.getName() + ".methodCall(" + classOrInstance + ", \"" + method.getName() + "\", $args, $sig, \"" + returnTypeAsString + "\");" + "if (value != " + MockGateway.class.getName() + ".PROCEED) " + "return " + returnValue + "; " + "throw new java.lang.UnsupportedOperationException(\"" + methodName + " is native\");"; method.setBody("{" + code + "}"); } private String classOrInstance(CtMethod method) { String classOrInstance = "this"; if (Modifier.isStatic(method.getModifiers())) { classOrInstance = "$class"; } return classOrInstance; } private void modifyMethod(CtMethod method, CtClass returnTypeAsCtClass, String returnTypeAsString) throws CannotCompileException { final String returnValue = getCorrectReturnValueType(returnTypeAsCtClass); String classOrInstance = classOrInstance(method); String code = "Object value = " + mockGetawayClass.getName() + ".methodCall(" + classOrInstance + ", \"" + method.getName() + "\", $args, $sig, \"" + returnTypeAsString + "\");" + "if (value != " + MockGateway.class.getName() + ".PROCEED) " + "return " + returnValue + "; "; method.insertBefore("{ " + code + "}"); } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/transformers/javassist/MethodSizeMockTransformer.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.transformers.javassist; import javassist.CannotCompileException; import javassist.CtClass; import javassist.CtMethod; import javassist.NotFoundException; import javassist.bytecode.CodeAttribute; import org.powermock.core.transformers.TransformStrategy; /** * According to JVM specification method size must be lower than 65536 bytes. * When that limit is exceeded class loader will fail to load the class. * Since instrumentation can increase method size significantly it must be * ensured that JVM limit is not exceeded. *

* When the limit is exceeded method's body is replaced by exception throw. * Method is then instrumented again to allow mocking and suppression. * * @see JVM specification */ public class MethodSizeMockTransformer extends MethodMockTransformer { private static final int MAX_METHOD_CODE_LENGTH_LIMIT = 65536; public MethodSizeMockTransformer(final TransformStrategy strategy) { super(strategy); } public CtClass transform(final CtClass clazz) throws CannotCompileException, NotFoundException { for (CtMethod method : clazz.getDeclaredMethods()) { if (isMethodSizeExceeded(method)) { String code = "{throw new IllegalAccessException(\"" + "Method was too large and after instrumentation exceeded JVM limit. " + "PowerMock modified the method to allow JVM to load the class. " + "You can use PowerMock API to suppress or mock this method behaviour." + "\");}"; method.setBody(code); modifyMethod(method); } } return clazz; } private boolean isMethodSizeExceeded(CtMethod method) { CodeAttribute codeAttribute = method.getMethodInfo().getCodeAttribute(); return codeAttribute != null && codeAttribute.getCodeLength() >= MAX_METHOD_CODE_LENGTH_LIMIT; } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/transformers/javassist/PackagePrivateClassesMockTransformer.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.transformers.javassist; import javassist.CtClass; import javassist.Modifier; import javassist.NotFoundException; import org.powermock.core.transformers.TransformStrategy; import static org.powermock.core.transformers.TransformStrategy.INST_REDEFINE; /** * Set class modifier to public to allow for mocking of package private * classes. This is needed because we've changed to CgLib naming policy * to allow for mocking of signed classes. */ public class PackagePrivateClassesMockTransformer extends AbstractJavaAssistMockTransformer { public PackagePrivateClassesMockTransformer(final TransformStrategy strategy) { super(strategy); } @Override public CtClass transform(final CtClass clazz) { final String name = clazz.getName(); if (getStrategy() != INST_REDEFINE) { transform(clazz, name); } return clazz; } private static void transform(final CtClass clazz, final String name) { try { final int modifiers = clazz.getModifiers(); if (Modifier.isPackage(modifiers)) { if (isNotSystemClass(name) && !(clazz.isInterface() && clazz.getDeclaringClass() != null)) { clazz.setModifiers(Modifier.setPublic(modifiers)); } } } catch (NotFoundException e) { // OK, continue } } private static boolean isNotSystemClass(final String name) { return !name.startsWith("java."); } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/transformers/javassist/StaticFinalFieldsMockTransformer.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.transformers.javassist; import javassist.CtClass; import javassist.CtField; import javassist.Modifier; import org.powermock.core.transformers.TransformStrategy; import static org.powermock.core.transformers.TransformStrategy.INST_REDEFINE; /** * Remove final from all static final fields. Not possible if using a java agent. */ public class StaticFinalFieldsMockTransformer extends AbstractJavaAssistMockTransformer { public StaticFinalFieldsMockTransformer(final TransformStrategy strategy) { super(strategy); } public CtClass transform(final CtClass clazz) { if (clazz.isInterface()) { return clazz; } if (getStrategy() != INST_REDEFINE) { for (CtField f : clazz.getDeclaredFields()) { final int modifiers = f.getModifiers(); if (Modifier.isFinal(modifiers) && Modifier.isStatic(modifiers)) { f.setModifiers(modifiers ^ Modifier.FINAL); } } } return clazz; } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/transformers/javassist/StaticFinalNativeMethodMockTransformer.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.transformers.javassist; import javassist.CannotCompileException; import javassist.CtClass; import javassist.CtMethod; import javassist.NotFoundException; import org.powermock.core.transformers.TransformStrategy; public class StaticFinalNativeMethodMockTransformer extends MethodMockTransformer { public StaticFinalNativeMethodMockTransformer(final TransformStrategy strategy) { super(strategy); } @Override public CtClass transform(final CtClass clazz) throws NotFoundException, CannotCompileException { for (CtMethod m : clazz.getDeclaredMethods()) { modifyMethod(m); } return clazz; } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/transformers/javassist/SuppressStaticInitializerMockTransformer.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.transformers.javassist; import javassist.CannotCompileException; import javassist.CtClass; import javassist.CtConstructor; import org.powermock.core.MockGateway; import org.powermock.core.transformers.TransformStrategy; import static org.powermock.core.transformers.TransformStrategy.CLASSLOADER; public class SuppressStaticInitializerMockTransformer extends AbstractJavaAssistMockTransformer { public SuppressStaticInitializerMockTransformer(final TransformStrategy strategy) { super(strategy); } @Override public CtClass transform(final CtClass clazz) throws CannotCompileException { if (getStrategy() == CLASSLOADER) { if (MockGateway.staticConstructorCall(clazz.getName()) != MockGateway.PROCEED) { CtConstructor classInitializer = clazz.makeClassInitializer(); classInitializer.setBody("{}"); } } return clazz; } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/transformers/javassist/support/JavaAssistClassWrapperFactory.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.transformers.javassist.support; import javassist.CtClass; import org.powermock.core.transformers.ClassWrapper; import org.powermock.core.transformers.ClassWrapperFactory; public class JavaAssistClassWrapperFactory implements ClassWrapperFactory { @Override public ClassWrapper wrap(CtClass ctClass) { return new JavaAssistClassWrapper(ctClass); } public static class JavaAssistClassWrapper implements ClassWrapper { private final CtClass ctClass; private JavaAssistClassWrapper(CtClass ctClass) { this.ctClass = ctClass; } @Override public boolean isInterface() { return ctClass.isInterface(); } @Override public CtClass unwrap() { return ctClass; } @Override public ClassWrapper wrap(final CtClass original) { return new JavaAssistClassWrapper(original); } } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/transformers/javassist/support/PowerMockExpressionEditor.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.transformers.javassist.support; import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; import javassist.CtField; import javassist.CtMethod; import javassist.CtNewConstructor; import javassist.NotFoundException; import javassist.bytecode.DuplicateMemberException; import javassist.bytecode.FieldInfo; import javassist.expr.ConstructorCall; import javassist.expr.ExprEditor; import javassist.expr.FieldAccess; import javassist.expr.MethodCall; import javassist.expr.NewExpr; import org.powermock.core.IndicateReloadClass; import org.powermock.core.MockGateway; import org.powermock.core.transformers.TransformStrategy; import static org.powermock.core.transformers.TransformStrategy.INST_REDEFINE; import static org.powermock.core.transformers.javassist.support.TransformerHelper.VOID; import static org.powermock.core.transformers.javassist.support.TransformerHelper.getCorrectReturnValueType; import static org.powermock.core.transformers.javassist.support.TransformerHelper.getReturnTypeAsString; import static org.powermock.core.transformers.javassist.support.TransformerHelper.isNotSyntheticField; public final class PowerMockExpressionEditor extends ExprEditor { private final CtClass clazz; private final Class mockGetawayClass; private final TransformStrategy strategy; public PowerMockExpressionEditor(final TransformStrategy strategy, final CtClass clazz, final Class mockGetawayClass) { this.strategy = strategy; this.clazz = clazz; this.mockGetawayClass = mockGetawayClass; } @Override public void edit(NewExpr e) throws CannotCompileException { String code = "Object instance =" + MockGateway.class.getName() + ".newInstanceCall($type,$args,$sig);" + "if(instance != " + MockGateway.class.getName() + ".PROCEED) {" + " if(instance instanceof java.lang.reflect.Constructor) {" + " $_ = ($r) sun.reflect.ReflectionFactory.getReflectionFactory().newConstructorForSerialization($type, java.lang.Object.class.getDeclaredConstructor(null)).newInstance(null);" + " } else {" + " $_ = ($r) instance;" + " }" + "} else {" + " $_ = $proceed($$);" + "}"; // TODO Change to objenisis instead e.replace(code); } @Override public void edit(MethodCall m) throws CannotCompileException { try { final CtMethod method = m.getMethod(); final CtClass declaringClass = method.getDeclaringClass(); if (declaringClass != null) { if (TransformerHelper.shouldTreatAsSystemClassCall(declaringClass)) { StringBuilder code = new StringBuilder(); code.append("{Object classOrInstance = null; if($0!=null){classOrInstance = $0;} else { classOrInstance = $class;}"); code.append("Object value = ") .append(MockGateway.class.getName()) .append(".methodCall(") .append("classOrInstance,\"") .append(m.getMethodName()) .append("\",$args, $sig,\"") .append(getReturnTypeAsString(method)) .append("\");"); code.append("if(value == ").append(MockGateway.class.getName()).append(".PROCEED) {"); code.append(" $_ = $proceed($$);"); code.append("} else {"); final String correctReturnValueType = getCorrectReturnValueType(method.getReturnType()); if (!VOID.equals(correctReturnValueType)) { code.append(" $_ = ").append(correctReturnValueType).append(";"); } code.append("}}"); m.replace(code.toString()); } } } catch (NotFoundException e) { /* * If multiple java agents are active (in INST_REDEFINE mode), the types implicitly loaded by javassist from disk * might differ from the types available in memory. Thus, this error might occur. * * It may also happen if PowerMock is modifying an SPI where the SPI require some classes to be available in the classpath * at runtime but they are not! This is valid in some cases such as slf4j. */ } } @Override public void edit(ConstructorCall c) throws CannotCompileException { /* * Note that constructor call only intercepts calls to super or this * from an instantiated class. This means that A a = new A(); will * NOT trigger a ConstructorCall for the default constructor in A. * If A where to extend B and A's constructor only delegates to * super(), the default constructor of B would trigger a * ConstructorCall. This means that we need to handle * "suppressConstructorCode" both here and in NewExpr. */ if (strategy != INST_REDEFINE && !c.getClassName().startsWith("java.lang")) { final CtClass superclass; try { superclass = clazz.getSuperclass(); } catch (NotFoundException e) { throw new RuntimeException(e); } /* * Create a default constructor in the super class if it doesn't * exist. This is needed because if the code in the current * constructor should be suppressed (which we don't know at this * moment of time) the parent class must have a default * constructor that we can delegate to. */ addNewDeferConstructor(clazz); final StringBuilder code = new StringBuilder(); code.append("{Object value =") .append(mockGetawayClass.getName()) .append(".constructorCall($class, $args, $sig);"); code.append("if (value != ").append(MockGateway.class.getName()).append(".PROCEED){"); /* * TODO Suppress and lazy inject field (when this feature is ready). */ if (superclass.getName().equals(Object.class.getName())) { code.append(" super();"); } else { code.append(" super((").append(IndicateReloadClass.class.getName()).append(") null);"); } code.append("} else {"); code.append(" $proceed($$);"); code.append("}}"); c.replace(code.toString()); } } @Override public void edit(FieldAccess f) throws CannotCompileException { if (f.isReader()) { CtClass returnTypeAsCtClass; FieldInfo fieldInfo; try { CtField field = f.getField(); returnTypeAsCtClass = field.getType(); fieldInfo = field.getFieldInfo2(); } catch (NotFoundException e) { /* * If multiple java agents are active (in INST_REDEFINE mode), the types implicitly loaded by javassist from disk * might differ from the types available in memory. Thus, this error might occur. * * It may also happen if PowerMock is modifying an SPI where the SPI require some classes to be available in the classpath * at runtime but they are not! This is valid in some cases such as slf4j. */ return; } if (isNotSyntheticField(fieldInfo)) { String code = "{Object value = " + MockGateway.class.getName() + ".fieldCall(" + "$0,$class,\"" + f.getFieldName() + "\",$type);" + "if(value == " + MockGateway.class.getName() + ".PROCEED) {" + " $_ = $proceed($$);" + "} else {" + " $_ = " + getCorrectReturnValueType(returnTypeAsCtClass) + ";" + "}}"; f.replace(code); } } } /** * Create a defer constructor in the class which will be called when the * constructor is suppressed. * * @param clazz The class whose super constructor will get a new defer * constructor if it doesn't already have one. * @throws CannotCompileException If an unexpected compilation error occurs. */ private void addNewDeferConstructor(final CtClass clazz) throws CannotCompileException { final CtClass superClass; try { superClass = clazz.getSuperclass(); } catch (NotFoundException e1) { throw new IllegalArgumentException("Internal error: Failed to get superclass for " + clazz.getName() + " when about to create a new default constructor."); } ClassPool classPool = clazz.getClassPool(); /* * To make a unique defer constructor we create a new constructor * with one argument (IndicateReloadClass). So we get this class a * Javassist class below. */ final CtClass constructorType; try { constructorType = classPool.get(IndicateReloadClass.class.getName()); } catch (NotFoundException e) { throw new IllegalArgumentException("Internal error: failed to get the " + IndicateReloadClass.class.getName() + " when added defer constructor."); } clazz.defrost(); if (superClass.getName().equals(Object.class.getName())) { try { clazz.addConstructor(CtNewConstructor.make(new CtClass[]{constructorType}, new CtClass[0], "{super();}", clazz)); } catch (DuplicateMemberException e) { // OK, the constructor has already been added. } } else { addNewDeferConstructor(superClass); try { clazz.addConstructor(CtNewConstructor.make(new CtClass[]{constructorType}, new CtClass[0], "{super($$);}", clazz)); } catch (DuplicateMemberException e) { // OK, the constructor has already been added. } } } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/transformers/javassist/support/Primitives.java ================================================ /* * Copyright 2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.core.transformers.javassist.support; import javassist.CtPrimitiveType; import java.util.Collections; import java.util.IdentityHashMap; import java.util.Map; import static javassist.CtClass.booleanType; import static javassist.CtClass.byteType; import static javassist.CtClass.charType; import static javassist.CtClass.doubleType; import static javassist.CtClass.floatType; import static javassist.CtClass.intType; import static javassist.CtClass.longType; import static javassist.CtClass.shortType; import static javassist.CtClass.voidType; /** * Simple utility that maps constant fields of {@link javassist.CtClass} to * their corresponding java class-objects for primitive types. */ public class Primitives { private static final Map> ct2primitiveClass = lookupMappings(); private static Map> lookupMappings() { Map> mappings = new IdentityHashMap>(10); for (Object[] each : new Object[][]{ {booleanType, boolean.class}, {byteType, byte.class}, {charType, char.class}, {doubleType, double.class}, {floatType, float.class}, {intType, int.class}, {longType, long.class}, {shortType, short.class}, {voidType, void.class} }) { mappings.put((CtPrimitiveType) each[0], (Class) each[1]); } return Collections.unmodifiableMap(mappings); } public static Class getClassFor(CtPrimitiveType ctPrimitiveType) { return ct2primitiveClass.get(ctPrimitiveType); } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/transformers/javassist/support/TransformerHelper.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.transformers.javassist.support; import javassist.CtClass; import javassist.CtMethod; import javassist.Modifier; import javassist.NotFoundException; import javassist.bytecode.AccessFlag; import javassist.bytecode.FieldInfo; public class TransformerHelper { public static final String VOID = ""; private static boolean isAccessFlagSynthetic(CtMethod method) { int accessFlags = method.getMethodInfo2().getAccessFlags(); return ((accessFlags & AccessFlag.SYNTHETIC) != 0) && !isBridgeMethod(method); } private static boolean isBridgeMethod(CtMethod method) { return (method.getMethodInfo2() .getAccessFlags() & AccessFlag.BRIDGE) != 0; } /** * @return The correct return type, i.e. takes care of casting the a wrapper * type to primitive type if needed. */ public static String getCorrectReturnValueType(final CtClass returnTypeAsCtClass) { final String returnTypeAsString = returnTypeAsCtClass.getName(); final String returnValue; if (returnTypeAsCtClass.equals(CtClass.voidType)) { returnValue = VOID; } else if (returnTypeAsCtClass.isPrimitive()) { if (returnTypeAsString.equals("char")) { returnValue = "((java.lang.Character)value).charValue()"; } else if (returnTypeAsString.equals("boolean")) { returnValue = "((java.lang.Boolean)value).booleanValue()"; } else { returnValue = "((java.lang.Number)value)." + returnTypeAsString + "Value()"; } } else { returnValue = "(" + returnTypeAsString + ")value"; } return returnValue; } public static boolean isNotSyntheticField(FieldInfo fieldInfo) { return (fieldInfo.getAccessFlags() & AccessFlag.SYNTHETIC) == 0; } public static boolean shouldSkipMethod(CtMethod method) { return isAccessFlagSynthetic(method) || Modifier.isAbstract(method.getModifiers()); } public static String getReturnTypeAsString(final CtMethod method) throws NotFoundException { CtClass returnType = method.getReturnType(); String returnTypeAsString = VOID; if (!returnType.equals(CtClass.voidType)) { returnTypeAsString = returnType.getName(); } return returnTypeAsString; } public static boolean shouldTreatAsSystemClassCall(CtClass declaringClass) { final String className = declaringClass.getName(); return className.startsWith("java."); } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/transformers/javassist/testclass/ForMethodsJavaAssistTestClassTransformer.java ================================================ package org.powermock.core.transformers.javassist.testclass; import javassist.CtMethod; import org.powermock.core.transformers.MethodSignatureWriter; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; public class ForMethodsJavaAssistTestClassTransformer extends JavaAssistTestClassTransformer { private final Collection testMethodsThatRunOnOtherClassLoaders; /** * Is lazily initilized because of * AbstractTestSuiteChunkerImpl#chunkClass(Class) */ private Collection methodsThatRunOnOtherClassLoaders; public ForMethodsJavaAssistTestClassTransformer(final Class testClass, final Class testMethodAnnotation, final MethodSignatureWriter methodSignatureWriter, final Collection testMethodsThatRunOnOtherClassLoaders) { super(testClass, testMethodAnnotation, methodSignatureWriter); this.testMethodsThatRunOnOtherClassLoaders = testMethodsThatRunOnOtherClassLoaders; } @Override protected boolean mustHaveTestAnnotationRemoved(CtMethod method) throws Exception { if (null == methodsThatRunOnOtherClassLoaders) { /* This lazy initialization is necessary - see above */ methodsThatRunOnOtherClassLoaders = new HashSet(); for (Method m : testMethodsThatRunOnOtherClassLoaders) { methodsThatRunOnOtherClassLoaders.add(signatureOf(m)); } testMethodsThatRunOnOtherClassLoaders.clear(); } return methodsThatRunOnOtherClassLoaders.contains(signatureOf(method)); } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/transformers/javassist/testclass/FromAllMethodsExceptJavaAssistTestClassTransformer.java ================================================ package org.powermock.core.transformers.javassist.testclass; import javassist.CtMethod; import org.powermock.core.transformers.MethodSignatureWriter; import java.lang.annotation.Annotation; import java.lang.reflect.Method; public class FromAllMethodsExceptJavaAssistTestClassTransformer extends JavaAssistTestClassTransformer { private final String targetMethodSignature; public FromAllMethodsExceptJavaAssistTestClassTransformer(final Class testClass, final Class testMethodAnnotation, final MethodSignatureWriter signatureWriter, final Method methodToExclude) { super(testClass, testMethodAnnotation, signatureWriter); this.targetMethodSignature = signatureWriter.signatureForReflection(methodToExclude); } @Override protected boolean mustHaveTestAnnotationRemoved(CtMethod method) throws Exception { return !signatureOf(method).equals(targetMethodSignature); } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/transformers/javassist/testclass/JavaAssistTestClassTransformer.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.transformers.javassist.testclass; import javassist.CannotCompileException; import javassist.CtClass; import javassist.CtConstructor; import javassist.CtMethod; import javassist.CtPrimitiveType; import javassist.Modifier; import javassist.NotFoundException; import javassist.bytecode.AnnotationsAttribute; import org.powermock.core.IndicateReloadClass; import org.powermock.core.testlisteners.GlobalNotificationBuildSupport; import org.powermock.core.transformers.ClassWrapper; import org.powermock.core.transformers.MethodSignatureWriter; import org.powermock.core.transformers.TestClassTransformer; import org.powermock.core.transformers.javassist.support.Primitives; import java.lang.annotation.Annotation; import java.lang.reflect.Array; public abstract class JavaAssistTestClassTransformer extends TestClassTransformer { JavaAssistTestClassTransformer(Class testClass, Class testMethodAnnotationType, MethodSignatureWriter signatureWriter) { super(testClass, testMethodAnnotationType, signatureWriter); } protected abstract boolean mustHaveTestAnnotationRemoved(CtMethod method) throws Exception; @Override public ClassWrapper transform(final ClassWrapper clazz) throws Exception { transform(clazz.unwrap()); return clazz; } private void transform(final CtClass clazz) throws Exception { if (clazz.isFrozen()) { clazz.defrost(); } if (isTestClass(clazz)) { removeTestAnnotationsForTestMethodsThatRunOnOtherClassLoader(clazz); addLifeCycleNotifications(clazz); makeDeferConstructorNonPublic(clazz); restoreOriginalConstructorsAccesses(clazz); } else if (isNestedWithinTestClass(clazz)) { makeDeferConstructorNonPublic(clazz); restoreOriginalConstructorsAccesses(clazz); } } private boolean isTestClass(CtClass clazz) { try { return Class.forName(clazz.getName(), false, getTestClass().getClassLoader()) .isAssignableFrom(getTestClass()); } catch (ClassNotFoundException ex) { return false; } } private boolean isNestedWithinTestClass(CtClass clazz) { String clazzName = clazz.getName(); return clazzName.startsWith(getTestClass().getName()) && '$' == clazzName.charAt(getTestClass().getName().length()); } private Class asOriginalClass(CtClass type) throws Exception { try { return type.isArray() ? Array.newInstance(asOriginalClass(type.getComponentType()), 0).getClass() : type.isPrimitive() ? Primitives.getClassFor((CtPrimitiveType) type) : Class.forName(type.getName(), true, getTestClass().getClassLoader()); } catch (Exception ex) { throw new RuntimeException("Cannot resolve type: " + type, ex); } } private Class[] asOriginalClassParams(CtClass[] parameterTypes) throws Exception { final Class[] classParams = new Class[parameterTypes.length]; for (int i = 0; i < classParams.length; ++i) { classParams[i] = asOriginalClass(parameterTypes[i]); } return classParams; } private void removeTestMethodAnnotationFrom(CtMethod m) { final AnnotationsAttribute attr = (AnnotationsAttribute) m.getMethodInfo().getAttribute(AnnotationsAttribute.visibleTag); javassist.bytecode.annotation.Annotation[] newAnnotations = new javassist.bytecode.annotation.Annotation[attr.numAnnotations() - 1]; int i = -1; for (javassist.bytecode.annotation.Annotation a : attr.getAnnotations()) { if (a.getTypeName().equals(getTestMethodAnnotationType().getName())) { continue; } newAnnotations[++i] = a; } attr.setAnnotations(newAnnotations); } private void removeTestAnnotationsForTestMethodsThatRunOnOtherClassLoader(CtClass clazz) throws Exception { for (CtMethod m : clazz.getDeclaredMethods()) { if (m.hasAnnotation(getTestMethodAnnotationType()) && mustHaveTestAnnotationRemoved(m)) { removeTestMethodAnnotationFrom(m); } } } private void addLifeCycleNotifications(CtClass clazz) { try { addClassInitializerNotification(clazz); addConstructorNotification(clazz); } catch (CannotCompileException ex) { throw new Error("Powermock error: " + ex.getMessage(), ex); } } private void addClassInitializerNotification(CtClass clazz) throws CannotCompileException { if (null == clazz.getClassInitializer()) { clazz.makeClassInitializer(); } clazz.getClassInitializer().insertBefore( GlobalNotificationBuildSupport.class.getName() + ".testClassInitiated(" + clazz.getName() + ".class);"); } private static boolean hasSuperClass(CtClass clazz) { try { CtClass superClazz = clazz.getSuperclass(); /* * Being extra careful here - and backup in case the * work-in-progress clazz doesn't cause NotFoundException ... */ return null != superClazz && !"java.lang.Object".equals(superClazz.getName()); } catch (NotFoundException noWasSuperClassFound) { return false; } } private void addConstructorNotification(final CtClass clazz) throws CannotCompileException { final String notificationCode = GlobalNotificationBuildSupport.class.getName() + ".testInstanceCreated(this);"; final boolean asFinally = !hasSuperClass(clazz); for (final CtConstructor constr : clazz.getDeclaredConstructors()) { constr.insertAfter( notificationCode, asFinally/* unless there is a super-class, because of this * problem: https://community.jboss.org/thread/94194*/); } } private void restoreOriginalConstructorsAccesses(CtClass clazz) throws Exception { Class originalClass = getTestClass().getName().equals(clazz.getName()) ? getTestClass() : Class.forName(clazz.getName(), true, getTestClass().getClassLoader()); for (final CtConstructor ctConstr : clazz.getConstructors()) { int ctModifiers = ctConstr.getModifiers(); if (!Modifier.isPublic(ctModifiers)) { /* Probably a defer-constructor */ continue; } int desiredAccessModifiers = originalClass.getDeclaredConstructor( asOriginalClassParams(ctConstr.getParameterTypes())).getModifiers(); if (Modifier.isPrivate(desiredAccessModifiers)) { ctConstr.setModifiers(Modifier.setPrivate(ctModifiers)); } else if (Modifier.isProtected(desiredAccessModifiers)) { ctConstr.setModifiers(Modifier.setProtected(ctModifiers)); } else if (!Modifier.isPublic(desiredAccessModifiers)) { ctConstr.setModifiers(Modifier.setPackage(ctModifiers)); } else { /* ctConstr remains public */ } } } private void makeDeferConstructorNonPublic(final CtClass clazz) { for (final CtConstructor constr : clazz.getConstructors()) { try { for (CtClass paramType : constr.getParameterTypes()) { if (IndicateReloadClass.class.getName() .equals(paramType.getName())) { /* Found defer constructor ... */ final int modifiers = constr.getModifiers(); if (Modifier.isPublic(modifiers)) { constr.setModifiers(Modifier.setProtected(modifiers)); } break; } } } catch (NotFoundException thereAreNoParameters) { /* ... but to get an exception here seems odd. */ } } } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/transformers/support/DefaultMockTransformerChain.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.transformers.support; import org.powermock.core.transformers.ClassWrapper; import org.powermock.core.transformers.MockTransformer; import org.powermock.core.transformers.MockTransformerChain; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; public class DefaultMockTransformerChain implements MockTransformerChain { private final List transformers; private DefaultMockTransformerChain(final List transformers) { this.transformers = Collections.unmodifiableList(transformers); } @Override public ClassWrapper transform(final ClassWrapper clazz) throws Exception { ClassWrapper classWrapper = clazz; for (MockTransformer transformer : transformers) { classWrapper = transformer.transform(classWrapper); } return classWrapper; } @Override public Collection filter(final FilterPredicate predicate) { final ArrayList filtered = new ArrayList(); for (MockTransformer transformer : transformers) { if (predicate.test(transformer)) { filtered.add(transformer); } } return filtered; } @Override public String toString() { return "MockTransformerChain{" + "transformers=" + transformers + '}'; } public static MockTransformerChainBuilder newBuilder() { return new MockTransformerChainBuilder(); } public static class MockTransformerChainBuilder { private final List transformers; private MockTransformerChainBuilder() { transformers = new ArrayList(); } public MockTransformerChainBuilder append(MockTransformer transformer) { transformers.add(transformer); return this; } public MockTransformerChainBuilder append(final List mockTransformerChain) { transformers.addAll(mockTransformerChain); return this; } public MockTransformerChain build() { return new DefaultMockTransformerChain(transformers); } } } ================================================ FILE: powermock-core/src/main/java/org/powermock/core/transformers/support/FilterPredicates.java ================================================ package org.powermock.core.transformers.support; import org.powermock.core.transformers.MockTransformer; import org.powermock.core.transformers.MockTransformerChain.FilterPredicate; public class FilterPredicates { public static FilterPredicate isInstanceOf(final Class klass) { return new FilterPredicate() { @Override public boolean test(final MockTransformer mockTransformer) { return klass.isAssignableFrom(mockTransformer.getClass()); } }; } } ================================================ FILE: powermock-core/src/main/java/org/powermock/mockpolicies/MockPolicyClassLoadingSettings.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.mockpolicies; /** * Contains class-loading related settings. PowerMock uses the information * stored in this object to configure it's mock classloader to allow for * testability. *

* Since mock policies can be chained subsequent policies can override behavior * of a previous policy. To avoid accidental overrides it's recommended * add behavior instead of setting behavior since the latter * overrides all previous configurations. */ public interface MockPolicyClassLoadingSettings { /** * Set which static initializers to suppress. Note that this overrides all * previous configurations. */ void setStaticInitializersToSuppress(String[] staticInitializersToSuppress); /** * Add static initializers to suppress. */ void addStaticInitializersToSuppress(String firstStaticInitializerToSuppress, String... additionalStaticInitializersToSuppress); /** * Add static initializers to suppress. */ void addStaticInitializersToSuppress(String[] staticInitializersToSuppress); /** * Set which types that should be loaded (and possibly modified) by the mock * classloader. Note that this overrides all previous configurations. */ void setFullyQualifiedNamesOfClassesToLoadByMockClassloader(String[] classes); /** * Add types that should be loaded (and possibly modified) by the mock * classloader. */ void addFullyQualifiedNamesOfClassesToLoadByMockClassloader(String firstClass, String... additionalClasses); /** * Add types that should be loaded (and possibly modified) by the mock * classloader. */ void addFullyQualifiedNamesOfClassesToLoadByMockClassloader(String[] classes); /** * @return The fully-qualified names to the classes whose static * initializers that should be suppressed. */ String[] getStaticInitializersToSuppress(); /** * @return The fully-qualified names to all types that should be loaded by * the mock classloader. */ String[] getFullyQualifiedNamesOfClassesToLoadByMockClassloader(); } ================================================ FILE: powermock-core/src/main/java/org/powermock/mockpolicies/MockPolicyInterceptionSettings.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.mockpolicies; import java.lang.reflect.Field; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.util.Map; /** * Contains interception related settings. PowerMock uses the information stored * in this object to intercept method calls and field calls etc and specify a * return value or suppression. *

* Since mock policies can be chained subsequent policies can override behavior * of a previous policy. To avoid accidental overrides it's recommended * add behavior instead of setting behavior since the latter * overrides all previous configurations. */ public interface MockPolicyInterceptionSettings { /** * Set which methods to suppress. Note that this overrides all previous * configurations. */ void setMethodsToSuppress(Method[] methods); /** * Add methods to suppress upon invocation. */ void addMethodsToSuppress(Method methodToSuppress, Method... additionalMethodsToSuppress); /** * Add methods to suppress upon invocation. */ void addMethodsToSuppress(Method[] methods); /** * Set the substitute return values. The substitute return values is a * key-value map where each key is a method that should be intercepted and * each value is the new return value for that method when it's intercepted. *

* Note that this overrides all previous configurations. */ void setMethodsToStub(Map substituteReturnValues); /** * Add a method that should be intercepted and return another value ( * {@code returnObject}) (i.e. the method is stubbed). */ void stubMethod(Method method, Object returnObject); /** * Proxy a method with the given invocation handler. Each call to the method * will be routed to the invocationHandler instead. */ void proxyMethod(Method method, InvocationHandler invocationHandler); /** * Get all methods that should be proxied and the invocation handler for * each method. */ Map getProxiedMethods(); /** * Set the methods to proxy. The proxies are a key-value map where each key * is a method that should be intercepted and routed to the invocation * handler instead. *

* Note that this overrides all previous configurations. */ void setMethodsToProxy(Map proxies); /** * Set the substitute return values. The substitute return values is a * key-value map where each key is a method that should be intercepted and * each value is the new return value for that method when it's intercepted. *

* Note that this overrides all previous configurations. * * @deprecated Use {@link #stubMethod(Method, Object)} instead. */ @Deprecated void setSubtituteReturnValues(Map substituteReturnValues); /** * Add a method that should be intercepted and return another value ( * {@code returnObject}). The substitute return values is a key-value * map where each key is a method that should be intercepted and each value * is the new return value for that method when it's intercepted. * * @deprecated Use {@link #stubMethod(Method, Object)} instead. */ @Deprecated void addSubtituteReturnValue(Method method, Object returnObject); /** * Set specific fields that should be suppressed upon invocation. Note that * this overrides all previous configurations. */ void setFieldsSuppress(Field[] fields); /** * Add specific fields that should be suppressed upon invocation. */ void addFieldToSuppress(Field firstField, Field... additionalFields); /** * Add specific fields that should be suppressed upon invocation. */ void addFieldToSuppress(Field[] fields); /** * Set which field types that should be suppressed. Note that this overrides * all previous configurations. */ void setFieldTypesToSuppress(String[] fieldTypes); /** * Add field types that should be suppressed. */ void addFieldTypesToSuppress(String firstType, String... additionalFieldTypes); /** * Add field types that should be suppressed. */ void addFieldTypesToSuppress(String[] fieldTypes); /** * @return Which methods that should be suppressed/stubbed (i.e. return a * default value when invoked). */ Method[] getMethodsToSuppress(); /** * Get all substitute return values and also returns an unmodifiable map of * all method-object pairs the were initialized. */ Map getStubbedMethods(); /** * Get all substitute return values and also returns an unmodifiable map of * all method-object pairs the were initialized. * * @deprecated Use {@link #getStubbedMethods()} instead. */ @Deprecated Map getSubstituteReturnValues(); /** * @return Which fields should be suppressed (i.e. will be set to * {@code null} or other default values). */ Field[] getFieldsToSuppress(); /** * @return The fully-qualified names to the fields that should be * suppressed. */ String[] getFieldTypesToSuppress(); } ================================================ FILE: powermock-core/src/main/java/org/powermock/mockpolicies/impl/MockPolicyClassLoadingSettingsImpl.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.mockpolicies.impl; import org.powermock.mockpolicies.MockPolicyClassLoadingSettings; import java.util.Collections; import java.util.LinkedHashSet; import java.util.Set; /** * The default implementation of the {@link MockPolicyClassLoadingSettings} * interface. */ public class MockPolicyClassLoadingSettingsImpl implements MockPolicyClassLoadingSettings { private Set fullyQualifiedNamesOfClassesToLoadByMockClassloader; private Set staticInitializersToSuppress; public MockPolicyClassLoadingSettingsImpl() { fullyQualifiedNamesOfClassesToLoadByMockClassloader = new LinkedHashSet(); staticInitializersToSuppress = new LinkedHashSet(); } @Override public String[] getFullyQualifiedNamesOfClassesToLoadByMockClassloader() { if (fullyQualifiedNamesOfClassesToLoadByMockClassloader == null) { return new String[0]; } return fullyQualifiedNamesOfClassesToLoadByMockClassloader.toArray(new String[fullyQualifiedNamesOfClassesToLoadByMockClassloader.size()]); } @Override public String[] getStaticInitializersToSuppress() { if (staticInitializersToSuppress == null) { return new String[0]; } return staticInitializersToSuppress.toArray(new String[staticInitializersToSuppress.size()]); } @Override public void addFullyQualifiedNamesOfClassesToLoadByMockClassloader(String firstClass, String... additionalClasses) { fullyQualifiedNamesOfClassesToLoadByMockClassloader.add(firstClass); addFullyQualifiedNamesOfClassesToLoadByMockClassloader(additionalClasses); } @Override public void addFullyQualifiedNamesOfClassesToLoadByMockClassloader(String[] classes) { Collections.addAll(fullyQualifiedNamesOfClassesToLoadByMockClassloader, classes); } @Override public void addStaticInitializersToSuppress(String firstStaticInitializerToSuppress, String... additionalStaticInitializersToSuppress) { staticInitializersToSuppress.add(firstStaticInitializerToSuppress); addStaticInitializersToSuppress(additionalStaticInitializersToSuppress); } @Override public void addStaticInitializersToSuppress(String[] staticInitializersToSuppress) { Collections.addAll(this.staticInitializersToSuppress, staticInitializersToSuppress); } @Override public void setFullyQualifiedNamesOfClassesToLoadByMockClassloader(String[] classes) { fullyQualifiedNamesOfClassesToLoadByMockClassloader.clear(); addFullyQualifiedNamesOfClassesToLoadByMockClassloader(classes); } @Override public void setStaticInitializersToSuppress(String[] staticInitializersToSuppress) { this.staticInitializersToSuppress.clear(); addStaticInitializersToSuppress(staticInitializersToSuppress); } } ================================================ FILE: powermock-core/src/main/java/org/powermock/mockpolicies/impl/MockPolicyInterceptionSettingsImpl.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.mockpolicies.impl; import org.powermock.mockpolicies.MockPolicyInterceptionSettings; import java.lang.reflect.Field; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; public class MockPolicyInterceptionSettingsImpl implements MockPolicyInterceptionSettings { private Set fieldsToSuppress; private Set methodsToSuppress; private Map substituteReturnValues; private Set fieldsTypesToSuppress; private Map proxies; public MockPolicyInterceptionSettingsImpl() { fieldsToSuppress = new LinkedHashSet(); methodsToSuppress = new LinkedHashSet(); substituteReturnValues = new HashMap(); proxies = new HashMap(); fieldsTypesToSuppress = new LinkedHashSet(); } @Override public void addFieldTypesToSuppress(String firstType, String... additionalFieldTypes) { fieldsTypesToSuppress.add(firstType); addFieldTypesToSuppress(additionalFieldTypes); } @Override public void addFieldTypesToSuppress(String[] fieldTypes) { Collections.addAll(fieldsTypesToSuppress, fieldTypes); } @Override public void setFieldTypesToSuppress(String[] fieldTypes) { fieldsTypesToSuppress.clear(); addFieldTypesToSuppress(fieldTypes); } @Override public Field[] getFieldsToSuppress() { return fieldsToSuppress.toArray(new Field[fieldsToSuppress.size()]); } @Override public Method[] getMethodsToSuppress() { return methodsToSuppress.toArray(new Method[methodsToSuppress.size()]); } @Override public Map getStubbedMethods() { return Collections.unmodifiableMap(substituteReturnValues); } @Override public void addFieldToSuppress(Field firstField, Field... fields) { fieldsToSuppress.add(firstField); addFieldToSuppress(fields); } @Override public void addFieldToSuppress(Field[] fields) { Collections.addAll(fieldsToSuppress, fields); } @Override public void addMethodsToSuppress(Method methodToSuppress, Method... additionalMethodsToSuppress) { methodsToSuppress.add(methodToSuppress); addMethodsToSuppress(additionalMethodsToSuppress); } @Override public void addMethodsToSuppress(Method[] methods) { Collections.addAll(methodsToSuppress, methods); } @Override public void stubMethod(Method method, Object returnObject) { substituteReturnValues.put(method, returnObject); } @Override public void setFieldsSuppress(Field[] fields) { fieldsToSuppress.clear(); addFieldToSuppress(fields); } @Override public void setMethodsToSuppress(Method[] methods) { methodsToSuppress.clear(); addMethodsToSuppress(methods); } @Override public void setMethodsToStub(Map substituteReturnValues) { this.substituteReturnValues = substituteReturnValues; } @Override public String[] getFieldTypesToSuppress() { return fieldsTypesToSuppress.toArray(new String[fieldsTypesToSuppress.size()]); } @Override public void addSubtituteReturnValue(Method method, Object returnObject) { substituteReturnValues.put(method, returnObject); } @Override public void setSubtituteReturnValues(Map substituteReturnValues) { this.substituteReturnValues = substituteReturnValues; } @Override public Map getSubstituteReturnValues() { return getStubbedMethods(); } @Override public Map getProxiedMethods() { return proxies; } @Override public void proxyMethod(Method method, InvocationHandler invocationHandler) { proxies.put(method, invocationHandler); } @Override public void setMethodsToProxy(Map proxies) { this.proxies = proxies; } } ================================================ FILE: powermock-core/src/main/java/org/powermock/mockpolicies/support/LogPolicySupport.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.mockpolicies.support; import org.powermock.reflect.Whitebox; import java.lang.reflect.Method; /** * A support class for mock policies dealing with logging frameworks. */ public class LogPolicySupport { /** * Get the methods that should be mocked. * * @param fullyQualifiedClassName * The fully-qualified name to the class that contains the * method. * @param methodName * The name of the method that should be mocked. * @param logFramework * The log framework that should be printed if the class * {@code fullyQualifiedClassName} cannot be found. * @return The array of {@link Method}'s that should be mocked. */ public Method[] getLoggerMethods(String fullyQualifiedClassName, String methodName, String logFramework) { try { return Whitebox.getMethods(getType(fullyQualifiedClassName, logFramework), methodName); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } } /** * Get the class type representing the fully-qualified name. * * @param name * The fully-qualified name of a class to get. * @param logFramework * The log framework that should be printed if the class cannot * be found. * @return The class representing the fully-qualified name. * @throws Exception * If something unexpected goes wrong, for example if the class * cannot be found. */ public Class getType(String name, String logFramework) throws Exception { final Class loggerType; try { loggerType = Class.forName(name); } catch (ClassNotFoundException e) { final String message = String.format("Cannot find %s in the classpath which the %s policy requires.", logFramework, getClass() .getSimpleName()); throw new RuntimeException(message, e); } return loggerType; } } ================================================ FILE: powermock-core/src/main/java/org/powermock/tests/utils/ArrayMerger.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.tests.utils; /** * An array merger concatenates several arrays to one. */ public interface ArrayMerger { /** * Merge arrays of a specific type. */ T[] mergeArrays(Class type, T[]... arraysToMerge); } ================================================ FILE: powermock-core/src/main/java/org/powermock/tests/utils/IgnorePackagesExtractor.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.tests.utils; import java.lang.reflect.AnnotatedElement; public interface IgnorePackagesExtractor { /** * @return Returns a string-array of all package names if annotation was * found. */ String[] getPackagesToIgnore(AnnotatedElement element); } ================================================ FILE: powermock-core/src/main/java/org/powermock/tests/utils/Keys.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.tests.utils; /** * Holds various keys that may be put into the MockRepository to store state. */ public class Keys { /** * Key that can be used to set or get the current test instance in the mock * repository. */ public static final String CURRENT_TEST_INSTANCE = "powermock.test.instance"; /** * Key that can be used to set or get the current test method in the mock * repository. */ public static final String CURRENT_TEST_METHOD = "powermock.test.method"; /** * Key that can be used to set or get the current test method arguments in * the mock repository. */ public static final String CURRENT_TEST_METHOD_ARGUMENTS = "powermock.test.arguments"; } ================================================ FILE: powermock-core/src/main/java/org/powermock/tests/utils/MockPolicyInitializer.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.tests.utils; import org.powermock.core.classloader.MockClassLoader; /** * A Mock Policy initializer takes care of initializing the behavior defined by * the mock policies. */ public interface MockPolicyInitializer { /** * Initializes the mock policies for a given class loader. Note that this * method must not be called from the class loader ( * {@code classLoader}) that you pass in to this method. *

* Note that if the class-loader is not an instance of * {@link MockClassLoader} this method will return silently. */ void initialize(ClassLoader classLoader); boolean needsInitialization(); /** * @return {@code true} if the class with the fully-qualified name of * {@code fullyQualifiedClassName} was prepared for testing by * this mock policy initializer. */ boolean isPrepared(String fullyQualifiedClassName); /** * Re executes the {@link org.powermock.core.classloader.annotations.MockPolicy} of all the policies for a given class * loader. This method must be called after a call to * {@link MockPolicyInitializer#initialize(ClassLoader)} on the same class * loader. *

* Note that if the class-loader is not an instance of * {@link MockClassLoader} this method will return silently. */ void refreshPolicies(ClassLoader classLoader); } ================================================ FILE: powermock-core/src/main/java/org/powermock/tests/utils/PowerMockTestNotifier.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.tests.utils; import org.powermock.core.spi.testresult.TestMethodResult; import org.powermock.core.spi.testresult.TestSuiteResult; import java.lang.reflect.Method; /** * Implementors of this interface that must provide the ability to notify * PowerMock test listeners with the events as specified by the methods declared * in this interface. */ public interface PowerMockTestNotifier { /** * Notifies all listeners with the "before test method started" event. * * @param testInstance instance of test * @param testMethod test method to be executed * @param arguments arguments of test methods */ void notifyBeforeTestMethod(final Object testInstance, final Method testMethod, final Object[] arguments); /** * Notifies all listeners with the "after test method ended" event. * * @param testInstance instance of test * @param testMethod test method to be executed * @param arguments arguments of test methods * @param testResult result of running of test */ void notifyAfterTestMethod(Object testInstance, Method testMethod, Object[] arguments, TestMethodResult testResult); /** * Notifies all listeners with the "after test method ended" event. Uses * some state-store to get the needed state. For this method to work * {@link #notifyBeforeTestMethod(Object, Method, Object[])} must have been * called before this method. Otherwise revert to using the * {@link #notifyAfterTestMethod(Object, Method, Object[], TestMethodResult)} * method. * * @param successful {@code true} if the test was successful, * {@code false} otherwise. */ void notifyAfterTestMethod(boolean successful); /** * Notifies all listeners with the "before test suite started" event. * * @param testClass class of test suite * @param testMethods test case methods */ void notifyBeforeTestSuiteStarted(final Class testClass, final Method[] testMethods); /** * Notifies all listeners with the "after test suite ended" event. * * @param testClass class of test suite * @param methods test case methods * @param testResult result of running of test */ void notifyAfterTestSuiteEnded(Class testClass, Method[] methods, TestSuiteResult testResult); } ================================================ FILE: powermock-core/src/main/java/org/powermock/tests/utils/RunnerTestSuiteChunker.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.tests.utils; import java.util.List; /** * An interface that should be implemented by classes that performs test suite * chunking. Test suite chunking may be performed because certain classes may * need to be byte-code manipulated in tests without impacting on other tests. * * @author Johan Haleby */ public interface RunnerTestSuiteChunker extends TestSuiteChunker { /** * Create the test delegators needed for a whole class. */ void createTestDelegators(Class testClass, List chunks) throws Exception; /** * Get the number of total tests defined in the suite (the sum of all tests * defined in all chunks for this suite). * * @return The number of tests in this suite. */ int getTestCount(); } ================================================ FILE: powermock-core/src/main/java/org/powermock/tests/utils/TestChunk.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.tests.utils; import java.lang.reflect.Method; import java.util.List; /** * A test chunk consists of a list of methods that should be executed by a * particular classloader. * */ public interface TestChunk { ClassLoader getClassLoader(); List getTestMethodsToBeExecutedByThisClassloader(); boolean isMethodToBeExecutedByThisClassloader(Method method); } ================================================ FILE: powermock-core/src/main/java/org/powermock/tests/utils/TestClassesExtractor.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.tests.utils; import java.lang.reflect.AnnotatedElement; public interface TestClassesExtractor { /** * @return Returns {@code null} if the element was not annotated, an * empty String[] if it is annotated but contains no classes, or a * string-array of all class names if interest. */ String[] getTestClasses(AnnotatedElement element); boolean isPrepared(AnnotatedElement element, String fullyQualifiedClassName); } ================================================ FILE: powermock-core/src/main/java/org/powermock/tests/utils/TestSuiteChunker.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.tests.utils; import java.lang.reflect.Method; import java.util.List; /** * */ public interface TestSuiteChunker { /** * Get the number of chunks defined in this suite. * * @return The number of chunks defined in the correct suite. */ int getChunkSize(); /** * Get all chunk entries. * * @return An set of entries that contains a list of methods contained in * the chunk and the class loader that loaded these methods. */ List getTestChunks(); /** * Get all chunk entries for a specific class. * * @param testClass The class whose chunk entries to get. * @return An set of entries that contains a list of methods contained in * the chunk for the specific test class and the class loader that * loaded these methods. */ List getTestChunksEntries(Class testClass); /** * Get TestChunk for the given method. * * @param method - method for which test chunk should be found. * @return TestChunk for this method. */ TestChunk getTestChunk(Method method); /** * Should reflect whether or not this method is eligible for testing. * * @param testClass The class that defines the method. * @param potentialTestMethod The method to inspect whether it should be executed in the * test suite or not. * @return {@code true} if the method is a test method and should be * executed, {@code false} otherwise. */ boolean shouldExecuteTestForMethod(Class testClass, Method potentialTestMethod); } ================================================ FILE: powermock-core/src/main/java/org/powermock/tests/utils/impl/AbstractCommonTestSuiteChunkerImpl.java ================================================ package org.powermock.tests.utils.impl; import org.powermock.core.classloader.MockClassLoaderFactory; import org.powermock.core.classloader.annotations.PrepareEverythingForTest; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.core.classloader.annotations.PrepareOnlyThisForTest; import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor; import org.powermock.core.transformers.MockTransformer; import org.powermock.core.transformers.TestClassTransformerBuilder; import org.powermock.tests.utils.TestChunk; import org.powermock.tests.utils.TestSuiteChunker; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; public abstract class AbstractCommonTestSuiteChunkerImpl implements TestSuiteChunker { protected static final int NOT_INITIALIZED = -1; static final int DEFAULT_TEST_LISTENERS_SIZE = 1; static final int INTERNAL_INDEX_NOT_FOUND = NOT_INITIALIZED; /* * Maps between a specific class and a map of test methods loaded by a * specific mock class loader. */ private final List internalSuites = new LinkedList(); /* * Maps the list of test indexes that is assigned to a specific test suite * index. */ final LinkedHashMap> testAtDelegateMapper = new LinkedHashMap>(); final Class[] testClasses; private int currentTestIndex = NOT_INITIALIZED; protected AbstractCommonTestSuiteChunkerImpl(Class testClass) throws Exception { this(new Class[]{testClass}); } AbstractCommonTestSuiteChunkerImpl(Class... testClasses) throws Exception { this.testClasses = testClasses; for (Class clazz : testClasses) { chunkClass(clazz); } } @Override public int getChunkSize() { return getTestChunks().size(); } public List getTestChunks() { List allChunks = new LinkedList(); for (TestCaseEntry entry : internalSuites) { allChunks.addAll(entry.getTestChunks()); } return allChunks; } public List getTestChunksEntries(Class testClass) { for (TestCaseEntry entry : internalSuites) { if (entry.getTestClass().equals(testClass)) { return entry.getTestChunks(); } } return null; } public TestChunk getTestChunk(Method method) { for (TestChunk testChunk : getTestChunks()) { if (testChunk.isMethodToBeExecutedByThisClassloader(method)) { return testChunk; } } return null; } private void chunkClass(final Class testClass) throws Exception { List testMethodsForOtherClassLoaders = new ArrayList(); final ClassLoader defaultMockLoader = createDefaultMockLoader(testClass, testMethodsForOtherClassLoaders); List currentClassloaderMethods = new LinkedList(); TestChunk defaultTestChunk = new TestChunkImpl(defaultMockLoader, currentClassloaderMethods); // Put the first suite in the map of internal suites. List testChunks = new LinkedList(); testChunks.add(defaultTestChunk); internalSuites.add(new TestCaseEntry(testClass, testChunks)); initEntries(internalSuites); if (!currentClassloaderMethods.isEmpty()) { List allTestChunks = internalSuites.get(0).getTestChunks(); for (TestChunk chunk : allTestChunks.subList(1, allTestChunks.size())) { testMethodsForOtherClassLoaders.addAll(chunk.getTestMethodsToBeExecutedByThisClassloader()); } } else if (2 <= internalSuites.size() || 1 == internalSuites.size() && 2 <= internalSuites.get(0).getTestChunks().size()) { /* * If we don't have any test that should be executed by the default * class loader remove it to avoid duplicate test print outs. */ internalSuites.get(0).getTestChunks().remove(0); } //else{ /*Delegation-runner maybe doesn't use test-method annotations!*/ } } private ClassLoader createDefaultMockLoader(final Class testClass, final Collection testMethodsForOtherClassLoaders) { final MockTransformer extraMockTransformer; if (null == testMethodAnnotation()) { extraMockTransformer = null; } else { extraMockTransformer = TestClassTransformerBuilder .forTestClass(testClass) .removesTestMethodAnnotation(testMethodAnnotation()) .fromMethods(testMethodsForOtherClassLoaders); } return new MockClassLoaderFactory(testClass).createForClass(extraMockTransformer); } private void putMethodToChunk(TestCaseEntry testCaseEntry, Class testClass, Method method) { if (shouldExecuteTestForMethod(testClass, method)) { currentTestIndex++; if (hasChunkAnnotation(method)) { LinkedList methodsInThisChunk = new LinkedList(); methodsInThisChunk.add(method); final ClassLoader mockClassloader = createClassLoaderForMethod(testClass, method); final TestChunkImpl chunk = new TestChunkImpl(mockClassloader, methodsInThisChunk); testCaseEntry.getTestChunks().add(chunk); updatedIndexes(); } else { testCaseEntry.getTestChunks().get(0).getTestMethodsToBeExecutedByThisClassloader().add(method); // currentClassloaderMethods.add(method); final int currentDelegateIndex = internalSuites.size() - 1; /* * Add this test index to the main junit runner * delegator. */ List testList = testAtDelegateMapper.get(currentDelegateIndex); if (testList == null) { testList = new LinkedList(); testAtDelegateMapper.put(currentDelegateIndex, testList); } testList.add(currentTestIndex); } } } private ClassLoader createClassLoaderForMethod(final Class testClass, final Method method) { final MockTransformer extraMockTransformer; if (null == testMethodAnnotation()) { extraMockTransformer = null; } else { extraMockTransformer = TestClassTransformerBuilder.forTestClass(testClass) .bytecodeFrameworkClue(method) .removesTestMethodAnnotation(testMethodAnnotation()) .fromAllMethodsExcept(method); } final MockClassLoaderFactory classLoaderFactory = new MockClassLoaderFactory(testClass); return classLoaderFactory.createForMethod(method, extraMockTransformer); } protected Class testMethodAnnotation() { return null; } private void initEntries(List entries) { for (TestCaseEntry testCaseEntry : entries) { final Class testClass = testCaseEntry.getTestClass(); findMethods(testCaseEntry, testClass); } } private void findMethods(TestCaseEntry testCaseEntry, Class testClass) { Method[] allMethods = testClass.getMethods(); for (Method method : allMethods) { putMethodToChunk(testCaseEntry, testClass, method); } testClass = testClass.getSuperclass(); if (!Object.class.equals(testClass)) { findMethods(testCaseEntry, testClass); } } private boolean hasChunkAnnotation(Method method) { return method.isAnnotationPresent(PrepareForTest.class) || method.isAnnotationPresent(SuppressStaticInitializationFor.class) || method.isAnnotationPresent(PrepareOnlyThisForTest.class) || method.isAnnotationPresent(PrepareEverythingForTest.class); } private void updatedIndexes() { final List testIndexesForThisClassloader = new LinkedList(); testIndexesForThisClassloader.add(currentTestIndex); testAtDelegateMapper.put(internalSuites.size(), testIndexesForThisClassloader); } } ================================================ FILE: powermock-core/src/main/java/org/powermock/tests/utils/impl/AbstractTestClassExtractor.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.tests.utils.impl; import org.powermock.tests.utils.TestClassesExtractor; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Method; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Set; /** * Base class for all test class extractors. */ public abstract class AbstractTestClassExtractor implements TestClassesExtractor { protected final boolean includeMethods; protected AbstractTestClassExtractor(){ this(false); } protected AbstractTestClassExtractor(boolean includeMethods) {this.includeMethods = includeMethods;} /** * If {@code element} is a class this method traverses the hierarchy * and extracts classes that should be prepared for test in all super * classes. */ @Override public final String[] getTestClasses(AnnotatedElement element) { final Set classesToPrepareForTest = new HashSet(); if (element instanceof Class) { extractClassesFromTestClass((Class) element, classesToPrepareForTest); } else { extractClassesAndAddThemToList(element, classesToPrepareForTest); } return classesToPrepareForTest.toArray(new String[classesToPrepareForTest.size()]); } private void extractClassesFromTestClass(final Class element, Set classesToPrepareForTest) { Class classToInvestigate = element; while (classToInvestigate != null && !classToInvestigate.equals(Object.class)) { extractClassesAndAddThemToList(classToInvestigate, classesToPrepareForTest); if (includeMethods) { classesToPrepareForTest.addAll(lookOverMethods(classToInvestigate)); } classToInvestigate = classToInvestigate.getSuperclass(); } } private Collection lookOverMethods(Class classToInvestigate) { Set classesToPrepareForTest = new HashSet(); for (Method method : classToInvestigate.getMethods()) { extractClassesAndAddThemToList(method, classesToPrepareForTest); } return classesToPrepareForTest; } private void extractClassesAndAddThemToList(AnnotatedElement elementToExtractClassFrom, final Set classesToPrepareForTest) { final String[] classesToModify = getClassesToModify(elementToExtractClassFrom); if (classesToModify != null) { Collections.addAll(classesToPrepareForTest, classesToModify); } } /** * Get the fully qualified names for classes that must should be modified * for this {@code element}. * * @param element The element that may contain info regarding which classes that * must be modified by PowerMock. * @return An array of fully-qualified names to classes that must be * modified by PowerMock for the specific {@code element}. */ protected abstract String[] getClassesToModify(AnnotatedElement element); @Override public boolean isPrepared(AnnotatedElement element, String fullyQualifiedClassName) { if (fullyQualifiedClassName == null) { throw new IllegalArgumentException("fullyQualifiedClassName cannot be null."); } final String[] testClasses = getTestClasses(element); for (String className : testClasses) { if (className.equals(fullyQualifiedClassName)) { return true; } } return false; } } ================================================ FILE: powermock-core/src/main/java/org/powermock/tests/utils/impl/AbstractTestSuiteChunkerImpl.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.tests.utils.impl; import org.powermock.core.classloader.annotations.PowerMockListener; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.core.spi.PowerMockTestListener; import org.powermock.reflect.Whitebox; import org.powermock.tests.utils.RunnerTestSuiteChunker; import org.powermock.tests.utils.TestChunk; import java.lang.reflect.Array; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Map.Entry; import java.util.Set; /** * Abstract base class for test suite chunking, i.e. a suite is chunked into * several smaller pieces which are ran with different classloaders. A chunk is * defined by the {@link PrepareForTest} annotation and whichever test-method * annotation the actual implementation-class specifies by overriding the * method {@link #testMethodAnnotation()}. This to make sure that you * can byte-code manipulate classes in tests without impacting on other tests. * */ public abstract class AbstractTestSuiteChunkerImpl extends AbstractCommonTestSuiteChunkerImpl implements RunnerTestSuiteChunker { /* * The classes listed in this set has been chunked and its delegates has * been created. */ protected final Set> delegatesCreatedForTheseClasses = new LinkedHashSet>(); // A list of junit delegates. protected final List delegates = new ArrayList(); protected volatile int testCount = NOT_INITIALIZED; protected AbstractTestSuiteChunkerImpl(Class testClass) throws Exception { super(testClass); } protected AbstractTestSuiteChunkerImpl(Class... testClasses) throws Exception { super(testClasses); } protected Object getPowerMockTestListenersLoadedByASpecificClassLoader(Class clazz, ClassLoader classLoader) { try { int defaultListenerSize = DEFAULT_TEST_LISTENERS_SIZE; Class annotationEnablerClass = null; try { annotationEnablerClass = Class.forName("org.powermock.api.extension.listener.AnnotationEnabler", false, classLoader); } catch (ClassNotFoundException e) { // Annotation enabler wasn't found in class path defaultListenerSize = 0; } final Class powerMockTestListenerType = Class.forName(PowerMockTestListener.class.getName(), false, classLoader); Object testListeners = null; if (clazz.isAnnotationPresent(PowerMockListener.class)) { PowerMockListener annotation = clazz.getAnnotation(PowerMockListener.class); final Class[] powerMockTestListeners = annotation.value(); if (powerMockTestListeners.length > 0) { testListeners = Array.newInstance(powerMockTestListenerType, powerMockTestListeners.length + defaultListenerSize); for (int i = 0; i < powerMockTestListeners.length; i++) { String testListenerClassName = powerMockTestListeners[i].getName(); final Class listenerTypeLoadedByClassLoader = Class.forName(testListenerClassName, false, classLoader); Array.set(testListeners, i, Whitebox.newInstance(listenerTypeLoadedByClassLoader)); } } } else { testListeners = Array.newInstance(powerMockTestListenerType, defaultListenerSize); } // Add default annotation enabler listener if (annotationEnablerClass != null) { Array.set(testListeners, Array.getLength(testListeners) - 1, Whitebox.newInstance(annotationEnablerClass)); } return testListeners; } catch (ClassNotFoundException e) { throw new IllegalStateException("PowerMock internal error: Failed to load class.", e); } } public final void createTestDelegators(Class testClass, List chunks) throws Exception { for (TestChunk chunk : chunks) { ClassLoader classLoader = chunk.getClassLoader(); List methodsToTest = chunk.getTestMethodsToBeExecutedByThisClassloader(); T runnerDelegator = createDelegatorFromClassloader(classLoader, testClass, methodsToTest); delegates.add(runnerDelegator); } delegatesCreatedForTheseClasses.add(testClass); } protected abstract T createDelegatorFromClassloader(ClassLoader classLoader, Class testClass, final List methodsToTest) throws Exception; /** * Get the internal test index for a junit runner delegate based on the * "real" original test index. For example, the test may need to run a * single test, for example the test with index 3. However since PowerMock * may have chunked the test suite to use many classloaders and junit * delegators the index (3) must be mapped to an internal representation for * the specific junit runner delegate. This is what this method does. I.e. * it will iterate through all junit runner delegates and see if they * contain the test with index 3, in the internal index of this test * delegator is returned. * * @param originalTestIndex * The original test index as seen by the test runner. * @return The internal test index as seen by PowerMock or {@code -1} * if no index was found. * */ public int getInternalTestIndex(int originalTestIndex) { Set>> delegatorEntrySet = testAtDelegateMapper.entrySet(); for (Entry> entry : delegatorEntrySet) { final List testIndexesForThisDelegate = entry.getValue(); final int internalIndex = testIndexesForThisDelegate.indexOf(originalTestIndex); if (internalIndex != INTERNAL_INDEX_NOT_FOUND) { return internalIndex; } } return INTERNAL_INDEX_NOT_FOUND; } /** * Get the junit runner delegate that handles the test at index * {@code testIndex}. Throws a {@link RuntimeException} if a delegator * is not found for the specific test index. * * @param testIndex * The test index that a delegator should hold. * @return The index for of the junit runner delegate as seen by JTestRack. */ public int getDelegatorIndex(int testIndex) { int delegatorIndex = -1; Set>> entrySet = testAtDelegateMapper.entrySet(); for (Entry> entry : entrySet) { // If the delegator contains the test case, return the index of the // delegator. if (entry.getValue().contains(testIndex)) { delegatorIndex = entry.getKey(); break; } } if (delegatorIndex == -1) { throw new RuntimeException("Internal error: Failed to find the delegator index."); } return delegatorIndex; } protected Class[] getTestClasses() { return testClasses; } } ================================================ FILE: powermock-core/src/main/java/org/powermock/tests/utils/impl/ArrayMergerImpl.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.tests.utils.impl; import org.powermock.tests.utils.ArrayMerger; import java.lang.reflect.Array; /** * The default implementation of the {@link ArrayMerger} interface. */ public class ArrayMergerImpl implements ArrayMerger { @SuppressWarnings("unchecked") @Override public T[] mergeArrays(Class type, T[]... arraysToMerge) { if (arraysToMerge == null || arraysToMerge.length == 0) { return (T[]) Array.newInstance(type, 0); } int size = 0; for (T[] array : arraysToMerge) { if (array != null) { size += array.length; } } final T[] finalArray = (T[]) Array.newInstance(type, size); int lastIndex = 0; for (final T[] currentArray : arraysToMerge) { if (currentArray != null) { final int currentArrayLength = currentArray.length; System.arraycopy(currentArray, 0, finalArray, lastIndex, currentArrayLength); lastIndex += currentArrayLength; } } return finalArray; } } ================================================ FILE: powermock-core/src/main/java/org/powermock/tests/utils/impl/MockPolicyInitializerImpl.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.tests.utils.impl; import org.powermock.core.MockRepository; import org.powermock.core.classloader.MockClassLoader; import org.powermock.core.classloader.MockClassLoaderConfiguration; import org.powermock.core.classloader.annotations.MockPolicy; import org.powermock.core.spi.PowerMockPolicy; import org.powermock.mockpolicies.MockPolicyClassLoadingSettings; import org.powermock.mockpolicies.MockPolicyInterceptionSettings; import org.powermock.mockpolicies.impl.MockPolicyClassLoadingSettingsImpl; import org.powermock.mockpolicies.impl.MockPolicyInterceptionSettingsImpl; import org.powermock.reflect.Whitebox; import org.powermock.tests.utils.MockPolicyInitializer; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Map.Entry; /** * The default implementation of the {@link MockPolicyInitializer} interface for * mock policies. */ public class MockPolicyInitializerImpl implements MockPolicyInitializer { private final PowerMockPolicy[] mockPolicies; private final Class[] mockPolicyTypes; private final Class testClass; public MockPolicyInitializerImpl(Class[] mockPolicies) { this(mockPolicies, false); } public MockPolicyInitializerImpl(Class testClass) { this(getMockPolicies(testClass), testClass, false); } private MockPolicyInitializerImpl(Class[] mockPolicies, boolean internal) { this(mockPolicies, null, internal); } private MockPolicyInitializerImpl(Class[] mockPolicies, Class testClass, boolean internal) { this.testClass = testClass; if (internal) { mockPolicyTypes = null; } else { mockPolicyTypes = mockPolicies; } if (mockPolicies == null) { this.mockPolicies = new PowerMockPolicy[0]; } else { this.mockPolicies = new PowerMockPolicy[mockPolicies.length]; for (int i = 0; i < mockPolicies.length; i++) { this.mockPolicies[i] = Whitebox.newInstance(mockPolicies[i]); } } } /** * Get the mock policies from a test-class. */ @SuppressWarnings("unchecked") private static Class[] getMockPolicies(Class testClass) { Class[] powerMockPolicies = new Class[0]; if (testClass.isAnnotationPresent(MockPolicy.class)) { MockPolicy annotation = testClass.getAnnotation(MockPolicy.class); powerMockPolicies = annotation.value(); } return powerMockPolicies; } @Override public boolean isPrepared(String fullyQualifiedClassName) { MockPolicyClassLoadingSettings settings = getClassLoadingSettings(); final boolean foundInSuppressStaticInitializer = Arrays.binarySearch(settings.getStaticInitializersToSuppress(), fullyQualifiedClassName) < 0; final boolean foundClassesLoadedByMockClassloader = Arrays.binarySearch(settings.getFullyQualifiedNamesOfClassesToLoadByMockClassloader(), fullyQualifiedClassName) < 0; return foundInSuppressStaticInitializer || foundClassesLoadedByMockClassloader; } @Override public boolean needsInitialization() { MockPolicyClassLoadingSettings settings = getClassLoadingSettings(); return settings.getStaticInitializersToSuppress().length > 0 || settings.getFullyQualifiedNamesOfClassesToLoadByMockClassloader().length > 0; } @Override public void initialize(ClassLoader classLoader) { if (classLoader instanceof MockClassLoader) { initialize(((MockClassLoader) classLoader)); } } private void initialize(MockClassLoader classLoader) { if (mockPolicies.length > 0) { updateClassLoaderConfiguration(classLoader.getConfiguration()); invokeInitializeInterceptionSettingsFromClassLoader(classLoader); } } private void updateClassLoaderConfiguration(MockClassLoaderConfiguration configuration) { MockPolicyClassLoadingSettings classLoadingSettings = getClassLoadingSettings(); String[] fullyQualifiedNamesOfClassesToLoadByMockClassloader = classLoadingSettings.getFullyQualifiedNamesOfClassesToLoadByMockClassloader(); configuration.addClassesToModify(fullyQualifiedNamesOfClassesToLoadByMockClassloader); if (testClass == null) { throw new IllegalStateException("Internal error: testClass should never be null when calling initialize on a mock policy"); } configuration.addClassesToModify(testClass.getName()); Class[] classes = testClass.getDeclaredClasses(); for (Class clazz : classes) { configuration.addClassesToModify(clazz.getName()); } Class[] declaredClasses = testClass.getClasses(); for (Class clazz : declaredClasses) { configuration.addClassesToModify(clazz.getName()); } for (String string : classLoadingSettings.getStaticInitializersToSuppress()) { configuration.addClassesToModify(string); MockRepository.addSuppressStaticInitializer(string); } } @Override public void refreshPolicies(ClassLoader classLoader) { if (classLoader instanceof MockClassLoader) { invokeInitializeInterceptionSettingsFromClassLoader((MockClassLoader) classLoader); } } private void invokeInitializeInterceptionSettingsFromClassLoader(MockClassLoader classLoader) { try { final int sizeOfPolicies = mockPolicyTypes.length; Object mockPolicies = Array.newInstance(Class.class, sizeOfPolicies); for (int i = 0; i < sizeOfPolicies; i++) { final Class policyLoadedByClassLoader = Class.forName(mockPolicyTypes[i].getName(), false, classLoader); Array.set(mockPolicies, i, policyLoadedByClassLoader); } final Class thisTypeLoadedByMockClassLoader = Class.forName(this.getClass() .getName(), false, classLoader); Object mockPolicyHandler = Whitebox.invokeConstructor(thisTypeLoadedByMockClassLoader, mockPolicies, true); Whitebox.invokeMethod(mockPolicyHandler, "initializeInterceptionSettings"); } catch (InvocationTargetException e) { final Throwable targetException = e.getTargetException(); if (targetException instanceof RuntimeException) { throw (RuntimeException) targetException; } else if (targetException instanceof Error) { throw (Error) targetException; } else { throw new RuntimeException(e); } } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new IllegalStateException("PowerMock internal error: Failed to load class.", e); } } /* * This method IS used, but it's invoked using reflection from the * invokeInitializeInterceptionSettingsFromClassLoader method. */ @SuppressWarnings("unused") private void initializeInterceptionSettings() { MockPolicyInterceptionSettings interceptionSettings = getInterceptionSettings(); for (Method method : interceptionSettings.getMethodsToSuppress()) { MockRepository.addMethodToSuppress(method); } for (Entry entry : interceptionSettings.getProxiedMethods().entrySet()) { MockRepository.putMethodProxy(entry.getKey(), entry.getValue()); } for (Entry entry : interceptionSettings.getStubbedMethods().entrySet()) { final Method method = entry.getKey(); final Object className = entry.getValue(); MockRepository.putMethodToStub(method, className); } for (Field field : interceptionSettings.getFieldsToSuppress()) { MockRepository.addFieldToSuppress(field); } for (String type : interceptionSettings.getFieldTypesToSuppress()) { MockRepository.addFieldTypeToSuppress(type); } } private MockPolicyInterceptionSettings getInterceptionSettings() { MockPolicyInterceptionSettings settings = new MockPolicyInterceptionSettingsImpl(); for (PowerMockPolicy mockPolicy : mockPolicies) { mockPolicy.applyInterceptionPolicy(settings); } return settings; } private MockPolicyClassLoadingSettings getClassLoadingSettings() { MockPolicyClassLoadingSettings settings = new MockPolicyClassLoadingSettingsImpl(); for (PowerMockPolicy mockPolicy : mockPolicies) { mockPolicy.applyClassLoadingPolicy(settings); } return settings; } } ================================================ FILE: powermock-core/src/main/java/org/powermock/tests/utils/impl/PowerMockIgnorePackagesExtractorImpl.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.tests.utils.impl; import org.powermock.configuration.GlobalConfiguration; import org.powermock.configuration.PowerMockConfiguration; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.tests.utils.IgnorePackagesExtractor; import java.lang.reflect.AnnotatedElement; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Set; public class PowerMockIgnorePackagesExtractorImpl implements IgnorePackagesExtractor { @Override public String[] getPackagesToIgnore(AnnotatedElement element) { PowerMockIgnore annotation = element.getAnnotation(PowerMockIgnore.class); boolean useGlobal = true; if (annotation != null){ useGlobal = annotation.globalIgnore(); } Set ignoredPackages = new HashSet(); useGlobal &= extractPackageToIgnore(element, ignoredPackages); final String[] packageToIgnore = ignoredPackages.toArray(new String[ignoredPackages.size()]); if (useGlobal) { return getPackageToIgnoreWithGlobal(packageToIgnore); } else { return packageToIgnore; } } private String[] getPackageToIgnoreWithGlobal(final String[] packageToIgnore) { String[] globalIgnore = getGlobalIgnore(); final String[] allPackageToIgnore; if (globalIgnore != null) { allPackageToIgnore = addGlobalIgnore(packageToIgnore, globalIgnore); } else { allPackageToIgnore = packageToIgnore; } return allPackageToIgnore; } private String[] getGlobalIgnore() { final PowerMockConfiguration powerMockConfiguration = GlobalConfiguration.powerMockConfiguration(); return powerMockConfiguration.getGlobalIgnore(); } private boolean extractPackageToIgnore(final AnnotatedElement element, final Set ignoredPackages) { boolean useGlobalFromAnnotation = addValueFromAnnotation(element, ignoredPackages); boolean useGlobalFromSuperclass = addValuesFromSuperclass((Class) element, ignoredPackages); return useGlobalFromAnnotation & useGlobalFromSuperclass; } private boolean addValuesFromSuperclass(final Class element, final Set ignoredPackages) { final Collection> superclasses = new ArrayList>(); Collections.addAll(superclasses, element.getSuperclass()); Collections.addAll(superclasses, element.getInterfaces()); boolean useGlobalIgnore = true; for (Class superclass : superclasses) { if (superclass != null && !superclass.equals(Object.class)) { useGlobalIgnore &= extractPackageToIgnore(superclass, ignoredPackages); } } return useGlobalIgnore; } private boolean addValueFromAnnotation(final AnnotatedElement element, final Set ignoredPackages) { PowerMockIgnore annotation = element.getAnnotation(PowerMockIgnore.class); if (annotation != null) { String[] ignores = annotation.value(); Collections.addAll(ignoredPackages, ignores); return annotation.globalIgnore(); } return true; } private String[] addGlobalIgnore(final String[] packageToIgnore, final String[] globalIgnore) { final String[] allPackageToIgnore; allPackageToIgnore = new String[globalIgnore.length + packageToIgnore.length]; System.arraycopy(globalIgnore, 0, allPackageToIgnore, 0, globalIgnore.length); System.arraycopy(packageToIgnore, 0, allPackageToIgnore, globalIgnore.length, packageToIgnore.length); return allPackageToIgnore; } } ================================================ FILE: powermock-core/src/main/java/org/powermock/tests/utils/impl/PowerMockTestNotifierImpl.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.tests.utils.impl; import org.powermock.core.MockRepository; import org.powermock.core.spi.PowerMockTestListener; import org.powermock.core.spi.testresult.Result; import org.powermock.core.spi.testresult.TestMethodResult; import org.powermock.core.spi.testresult.TestSuiteResult; import org.powermock.core.spi.testresult.impl.TestMethodResultImpl; import org.powermock.tests.utils.Keys; import org.powermock.tests.utils.PowerMockTestNotifier; import java.lang.reflect.Method; /** * Utility class that may be used by PowerMock test runners to notify listeners. * Uses the {@link MockRepository} to set and get state. */ public class PowerMockTestNotifierImpl implements PowerMockTestNotifier { private static final String ERROR_MESSAGE_TEMPLATE = "Invoking the %s method on PowerMock test listener %s failed."; private final PowerMockTestListener[] powerMockTestListeners; /** * Create a new instance with the following parameters. * * @param powerMockTestListeners * The PowerMock listeners that will be notified. */ public PowerMockTestNotifierImpl(PowerMockTestListener[] powerMockTestListeners) { if (powerMockTestListeners == null) { this.powerMockTestListeners = new PowerMockTestListener[0]; } else { this.powerMockTestListeners = powerMockTestListeners; } } @Override public void notifyAfterTestMethod(Object testInstance, Method method, Object[] arguments, TestMethodResult testResult) { for (final PowerMockTestListener testListener : powerMockTestListeners) { try { testListener.afterTestMethod(testInstance, method, arguments, testResult); } catch (Exception e) { throw new RuntimeException(String.format(ERROR_MESSAGE_TEMPLATE, "afterTestMethod", testListener), e); } } } @Override public void notifyAfterTestSuiteEnded(Class testClass, Method[] methods, TestSuiteResult testResult) { for (PowerMockTestListener powerMockTestListener : powerMockTestListeners) { try { powerMockTestListener.afterTestSuiteEnded(testClass, methods, testResult); } catch (Exception e) { throw new RuntimeException(String.format(ERROR_MESSAGE_TEMPLATE, "afterTestSuiteEnded", powerMockTestListener), e); } } } @Override public void notifyBeforeTestMethod(Object testInstance, Method testMethod, Object[] arguments) { MockRepository.putAdditionalState(Keys.CURRENT_TEST_INSTANCE, testInstance); MockRepository.putAdditionalState(Keys.CURRENT_TEST_METHOD, testMethod); MockRepository.putAdditionalState(Keys.CURRENT_TEST_METHOD_ARGUMENTS, arguments); for (final PowerMockTestListener testListener : powerMockTestListeners) { try { testListener.beforeTestMethod(testInstance, testMethod, arguments); } catch (Exception e) { throw new RuntimeException(String.format(ERROR_MESSAGE_TEMPLATE, "beforeTestMethod", testListener), e); } } } @Override public void notifyBeforeTestSuiteStarted(Class testClass, Method[] testMethods) { for (PowerMockTestListener powerMockTestListener : powerMockTestListeners) { try { powerMockTestListener.beforeTestSuiteStarted(testClass, testMethods); } catch (Exception e) { throw new RuntimeException(String.format(ERROR_MESSAGE_TEMPLATE, "beforeTestSuiteStarted", powerMockTestListener), e); } } } @Override public void notifyAfterTestMethod(boolean successful) { final Object test = MockRepository.getAdditionalState(Keys.CURRENT_TEST_INSTANCE); final Method testMethod = MockRepository.getAdditionalState(Keys.CURRENT_TEST_METHOD); final Object[] testArguments = MockRepository.getAdditionalState(Keys.CURRENT_TEST_METHOD_ARGUMENTS); final TestMethodResult testResult = new TestMethodResultImpl((successful ? Result.SUCCESSFUL : Result.FAILED)); notifyAfterTestMethod(test, testMethod, testArguments, testResult); } } ================================================ FILE: powermock-core/src/main/java/org/powermock/tests/utils/impl/PrepareForTestExtractorImpl.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.tests.utils.impl; import org.powermock.core.IndicateReloadClass; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.core.classloader.annotations.PrepareOnlyThisForTest; import org.powermock.tests.utils.TestClassesExtractor; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Method; import java.util.LinkedHashSet; import java.util.Set; /** * Implementation of the {@link TestClassesExtractor} interface that extract * classes from the {@link PrepareForTest} or {@link PrepareOnlyThisForTest} * annotations. It also adds the test case to the array of classes that should * be modified. * */ public class PrepareForTestExtractorImpl extends AbstractTestClassExtractor { public PrepareForTestExtractorImpl(){ this(false); } public PrepareForTestExtractorImpl(boolean includeMethods) { super(includeMethods); } @Override protected String[] getClassesToModify(AnnotatedElement element) { Set all = new LinkedHashSet(); addTestCase(all, element); PrepareForTest prepareForTestAnnotation = element.getAnnotation(PrepareForTest.class); PrepareOnlyThisForTest prepareOnlyThisForTestAnnotation = element.getAnnotation(PrepareOnlyThisForTest.class); final boolean prepareForTestAnnotationPresent = prepareForTestAnnotation != null; final boolean prepareOnlyThisForTestAnnotationPresent = prepareOnlyThisForTestAnnotation != null; if (!prepareForTestAnnotationPresent && !prepareOnlyThisForTestAnnotationPresent) { return null; } if (prepareForTestAnnotationPresent) { final Class[] classesToMock = prepareForTestAnnotation.value(); for (Class classToMock : classesToMock) { if (!classToMock.equals(IndicateReloadClass.class)) { addClassHierarchy(all, classToMock); } } addFullyQualifiedNames(all, prepareForTestAnnotation); } if (prepareOnlyThisForTestAnnotationPresent) { final Class[] classesToMock = prepareOnlyThisForTestAnnotation.value(); for (Class classToMock : classesToMock) { if (!classToMock.equals(IndicateReloadClass.class)) { all.add(classToMock.getName()); } } addFullyQualifiedNames(all, prepareOnlyThisForTestAnnotation); } return all.toArray(new String[all.size()]); } private void addTestCase(Set all, AnnotatedElement element) { Class testClass = null; if (element instanceof Class) { testClass = (Class) element; } else if (element instanceof Method) { testClass = ((Method) element).getDeclaringClass(); } addClassHierarchy(all, testClass); } private void addFullyQualifiedNames(Set all, PrepareForTest annotation) { String[] fullyQualifiedNames = annotation.fullyQualifiedNames(); addFullyQualifiedNames(all, fullyQualifiedNames); } private void addFullyQualifiedNames(Set all, PrepareOnlyThisForTest annotation) { String[] fullyQualifiedNames = annotation.fullyQualifiedNames(); addFullyQualifiedNames(all, fullyQualifiedNames); } private void addFullyQualifiedNames(Set all, String[] fullyQualifiedNames) { for (String string : fullyQualifiedNames) { if (!"".equals(string)) { all.add(string); } } } private void addClassHierarchy(Set all, Class classToMock) { while (classToMock != null && !classToMock.equals(Object.class)) { addInnerClassesAndInterfaces(all, classToMock); all.add(classToMock.getName()); classToMock = classToMock.getSuperclass(); } } private void addInnerClassesAndInterfaces(Set all, Class classToMock) { Class[] declaredClasses = classToMock.getDeclaredClasses(); for (Class innerClass : declaredClasses) { all.add(innerClass.getName()); } } } ================================================ FILE: powermock-core/src/main/java/org/powermock/tests/utils/impl/StaticConstructorSuppressExtractorImpl.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.tests.utils.impl; import org.powermock.core.MockRepository; import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor; import org.powermock.tests.utils.TestClassesExtractor; import java.lang.reflect.AnnotatedElement; import java.util.LinkedList; import java.util.List; /** * Implementation of the {@link TestClassesExtractor} interface for classes that * should have their static initializers suppressed. * */ public class StaticConstructorSuppressExtractorImpl extends AbstractTestClassExtractor { @Override public String[] getClassesToModify(AnnotatedElement element) { List all = new LinkedList(); final SuppressStaticInitializationFor suppressAnnotation = element.getAnnotation(SuppressStaticInitializationFor.class); if (suppressAnnotation == null) { return null; } else { final String[] value = suppressAnnotation.value(); for (String classToSuppress : value) { if (!"".equals(classToSuppress)) { all.add(classToSuppress); MockRepository.addSuppressStaticInitializer(classToSuppress); } } } return all.toArray(new String[all.size()]); } } ================================================ FILE: powermock-core/src/main/java/org/powermock/tests/utils/impl/TestCaseEntry.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.tests.utils.impl; import org.powermock.tests.utils.TestChunk; import java.util.List; /** * A test case entry consists of a test class and a list of test chunks that * should be executed for this entry. */ public class TestCaseEntry { private final List testChunks; private final Class testClass; public TestCaseEntry(Class testClass, List chunks) { this.testClass = testClass; this.testChunks = chunks; } public List getTestChunks() { return testChunks; } public Class getTestClass() { return testClass; } } ================================================ FILE: powermock-core/src/main/java/org/powermock/tests/utils/impl/TestChunkImpl.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.tests.utils.impl; import org.powermock.tests.utils.TestChunk; import java.lang.reflect.Method; import java.util.List; /** * A test chunk consists of a list of methods that should be executed by a * particular classloader. */ public class TestChunkImpl implements TestChunk { private final ClassLoader classLoader; private final List testMethodsToBeExecutedByThisClassloader; public TestChunkImpl(ClassLoader classLoader, List testMethodsToBeExecutedByThisClassloader) { this.classLoader = classLoader; this.testMethodsToBeExecutedByThisClassloader = testMethodsToBeExecutedByThisClassloader; } @Override public ClassLoader getClassLoader() { return classLoader; } @Override public List getTestMethodsToBeExecutedByThisClassloader() { return testMethodsToBeExecutedByThisClassloader; } @Override public boolean isMethodToBeExecutedByThisClassloader(Method method) { return testMethodsToBeExecutedByThisClassloader.contains(method); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Classloader = ").append(classLoader).append("\n"); sb.append("Methods:\n"); for (Method method : testMethodsToBeExecutedByThisClassloader) { sb.append(" ").append(method).append("\n"); } return sb.toString(); } } ================================================ FILE: powermock-core/src/main/java/org/powermock/utils/ArrayUtil.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.utils; import java.lang.reflect.Array; import java.util.HashSet; import java.util.Set; import static java.util.Arrays.asList; public class ArrayUtil { public static T[] addAll(T[] array1, T[] array2) { if (isEmpty(array1)) { return clone(array2); } else if (isEmpty(array2)) { return clone(array1); } int newLength = array1.length + array2.length; T[] joinedArray = createNewArrayWithSameType(array1, newLength); System.arraycopy(array1, 0, joinedArray, 0, array1.length); System.arraycopy(array2, 0, joinedArray, array1.length, array2.length); return joinedArray; } private static boolean isEmpty(T[] a) { return a == null || a.length == 0; } public static T[] clone(T[] array) { if (array == null) { return null; } return array.clone(); } @SuppressWarnings("unchecked") private static T[] createNewArrayWithSameType(T[] arrayPrototype, int newLength) { return (T[]) Array.newInstance(arrayPrototype[0].getClass(), newLength); } public static String[] mergeArrays(final String[] firstArray, final String[] secondArray) { if (firstArray == null && secondArray == null){ return null; } if (firstArray == null){ return secondArray; } if (secondArray == null){ return firstArray; } Set globalIgnore = new HashSet(); globalIgnore.addAll(asList(firstArray)); globalIgnore.addAll(asList(secondArray)); return globalIgnore.toArray(new String[globalIgnore.size()]); } } ================================================ FILE: powermock-core/src/main/java/org/powermock/utils/Asserts.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.utils; import org.powermock.PowerMockInternalException; public class Asserts { public static void assertNotNull(Object value, String message){ if (value == null) { throw new IllegalArgumentException(message); } } public static void internalAssertNotNull(Object value, String message){ if (value == null) { throw new PowerMockInternalException(message); } } } ================================================ FILE: powermock-core/src/main/java/org/powermock/utils/IOUtils.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.utils; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class IOUtils { public static void copyFileUsingStream(File source, File dest) throws IOException { InputStream is = null; OutputStream os = null; try { is = new FileInputStream(source); os = new FileOutputStream(dest); byte[] buffer = new byte[1024]; int length; while ((length = is.read(buffer)) > 0) { os.write(buffer, 0, length); } } finally { if (is != null) { is.close(); } if (os != null) { os.close(); } } } } ================================================ FILE: powermock-core/src/main/java/org/powermock/utils/JavaVersion.java ================================================ package org.powermock.utils; public enum JavaVersion { /** * The Java version reported by Android. This is not an official Java version number. */ JAVA_0_9(1.5f, "0.9"), /** * Java 1.1. */ JAVA_1_1(1.1f, "1.1"), /** * Java 1.2. */ JAVA_1_2(1.2f, "1.2"), /** * Java 1.3. */ JAVA_1_3(1.3f, "1.3"), /** * Java 1.4. */ JAVA_1_4(1.4f, "1.4"), /** * Java 1.5. */ JAVA_1_5(1.5f, "1.5"), /** * Java 1.6. */ JAVA_1_6(1.6f, "1.6"), /** * Java 1.7. */ JAVA_1_7(1.7f, "1.7"), /** * Java 1.8. */ JAVA_1_8(1.8f, "1.8"), /** * Java 1.9. * * @deprecated As of release 3.5, replaced by {@link #JAVA_9} */ @Deprecated JAVA_1_9(9.0f, "9"), /** * Java 9 * * @since 3.5 */ JAVA_9(9.0f, "9"), /** * Java 10 * * @since 3.7 */ JAVA_10(10.0f, "10"), /** * Java 11 * * @since 3.8 */ JAVA_11(11.0f, "11"), /** * Java 12 * * @since 3.9 */ JAVA_12(12.0f, "12"), /** * Java 13 * * @since 3.9 */ JAVA_13(13.0f, "13"), /** * The most recent java version. Mainly introduced to avoid to break when a new version of Java is used. */ JAVA_RECENT(maxVersion(), Float.toString(maxVersion())); /** * The float value. */ private final float value; /** * The standard name. */ private final String name; /** * Constructor. * * @param value the float value * @param name the standard name, not null */ JavaVersion(final float value, final String name) { this.value = value; this.name = name; } //----------------------------------------------------------------------- /** *

Whether this version of Java is at least the version of Java passed in.

* *

For example:
* {@code myVersion.atLeast(JavaVersion.JAVA_1_4)}

* * @param requiredVersion the version to check against, not null * @return true if this version is equal to or greater than the specified version */ public boolean atLeast(final JavaVersion requiredVersion) { return this.value >= requiredVersion.value; } /** * Transforms the given string with a Java version number to the * corresponding constant of this enumeration class. This method is used * internally. * * @param nom the Java version as string * @return the corresponding enumeration constant or null if the * version is unknown */ static JavaVersion get(final String nom) { if ("0.9".equals(nom)) { return JAVA_0_9; } else if ("1.1".equals(nom)) { return JAVA_1_1; } else if ("1.2".equals(nom)) { return JAVA_1_2; } else if ("1.3".equals(nom)) { return JAVA_1_3; } else if ("1.4".equals(nom)) { return JAVA_1_4; } else if ("1.5".equals(nom)) { return JAVA_1_5; } else if ("1.6".equals(nom)) { return JAVA_1_6; } else if ("1.7".equals(nom)) { return JAVA_1_7; } else if ("1.8".equals(nom)) { return JAVA_1_8; } else if ("9".equals(nom)) { return JAVA_9; } else if ("10".equals(nom)) { return JAVA_10; } else if ("11".equals(nom)) { return JAVA_11; } else if ("12".equals(nom)) { return JAVA_12; } else if ("13".equals(nom)) { return JAVA_13; } if (nom == null) { return null; } final float v = toFloatVersion(nom); if ((v - 1.) < 1.) { // then we need to check decimals > .9 final int firstComma = Math.max(nom.indexOf('.'), nom.indexOf(',')); final int end = Math.max(nom.length(), nom.indexOf(',', firstComma)); if (Float.parseFloat(nom.substring(firstComma + 1, end)) > .9f) { return JAVA_RECENT; } } else if (v > 10) { return JAVA_RECENT; } return null; } //----------------------------------------------------------------------- /** *

The string value is overridden to return the standard name.

* *

For example, "1.5".

* * @return the name, not null */ @Override public String toString() { return name; } /** * Gets the Java Version from the system or 99.0 if the {@code java.specification.version} system property is not set. * * @return the value of {@code java.specification.version} system property or 99.0 if it is not set. */ private static float maxVersion() { final float v = toFloatVersion(System.getProperty("java.specification.version", "99.0")); if (v > 0) { return v; } return 99f; } /** * Parses a float value from a String. * * @param value the String to parse. * @return the float value represented by the string or -1 if the given String can not be parsed. */ private static float toFloatVersion(final String value) { final int defaultReturnValue = -1; if (value.contains(".")) { final String[] toParse = value.split("\\."); if (toParse.length >= 2) { return NumberUtils.toFloat(toParse[0] + '.' + toParse[1], defaultReturnValue); } } else { return NumberUtils.toFloat(value, defaultReturnValue); } return defaultReturnValue; } } ================================================ FILE: powermock-core/src/main/java/org/powermock/utils/NumberUtils.java ================================================ package org.powermock.utils; public class NumberUtils { public static float toFloat(final String str, final float defaultValue) { if (str == null) { return defaultValue; } try { return Float.parseFloat(str); } catch (final NumberFormatException nfe) { return defaultValue; } } } ================================================ FILE: powermock-core/src/main/java/org/powermock/utils/StringJoiner.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.utils; import java.util.Arrays; import java.util.List; public class StringJoiner { private static final String LINE_SEPARATOR = System.getProperty("line.separator"); private static final String EMPTY_STRING = ""; public static String join(Object... linesToBreak) { StringBuilder out = new StringBuilder(LINE_SEPARATOR); return join(out, Arrays.asList(linesToBreak), LINE_SEPARATOR); } public static String join(List list) { StringBuilder out = new StringBuilder(LINE_SEPARATOR); return join(out, list, LINE_SEPARATOR); } public static String join(String separator, Object... linesToBreak) { StringBuilder out = new StringBuilder(); return join(out, linesToBreak, separator); } private static String join(StringBuilder out, Iterable linesToBreak, final String separator) { for (Object line : linesToBreak) { out.append(line.toString()).append(separator); } int lastBreak = out.lastIndexOf(separator); return out.replace(lastBreak, lastBreak + 1, EMPTY_STRING).toString(); } } ================================================ FILE: powermock-core/src/main/resources/org/powermock/default.properties ================================================ # suppress inspection "UnusedProperty" for whole file powermock.global-ignore=org.powermock.core* powermock.byte-code-framework=Javassist ================================================ FILE: powermock-core/src/test/java/org/powermock/WildcardMatcherTest.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock; import org.junit.Test; import org.powermock.core.WildcardMatcher; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class WildcardMatcherTest { @Test public void matchesWildcardOnBothEnds() throws Exception { assertTrue(WildcardMatcher.matches("org.mytest.java", "*.java*")); } @Test public void matchesWildcardSuffix() throws Exception { assertTrue(WildcardMatcher.matches("org.mytest.java", "*.java")); } @Test public void doesntMatchWildcardPrefix() throws Exception { assertFalse(WildcardMatcher.matches("org.mytest.java", ".java*")); } @Test public void convertsDotsAndWildcardsToRegExp() throws Exception { assertFalse(WildcardMatcher.matches("javassist.runtime.Desc", "java.*")); } @Test public void noWildcardCardPrefix() throws Exception { assertFalse(WildcardMatcher.matches("org.mytest.java", ".java")); } @Test public void exactMatch() throws Exception { assertTrue(WildcardMatcher.matches("org.mytest.java", "org.mytest.java")); } } ================================================ FILE: powermock-core/src/test/java/org/powermock/configuration/support/ConfigurationBuilderTest.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.configuration.support; import org.junit.Test; import org.powermock.configuration.Configuration; import org.powermock.configuration.MockitoConfiguration; import org.powermock.configuration.PowerMockConfiguration; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.powermock.configuration.support.ConfigurationBuilder.createConfigurationFor; public class ConfigurationBuilderTest { private static final String CONF_PATH = "org/powermock/extensions"; private static final String CONFIGURATION_FILE = CONF_PATH + "/test.properties"; @Test public void should_create_configuration_from_file() { final Configuration configuration = createConfigurationFor(MockitoConfiguration.class) .fromFile(CONFIGURATION_FILE); assertThat(configuration) .as("Configuration is map") .isNotNull(); } @Test public void should_read_mock_maker_class_from_configuration() { final MockitoConfiguration configuration = createConfigurationFor(MockitoConfiguration.class) .fromFile(CONFIGURATION_FILE); assertThat(configuration.getMockMakerClass()) .as("Configuration is map") .isEqualTo("TestMockMaker"); } @Test public void should_not_read_mock_maker_class_from_configuration_without_prefix() { final MockitoConfiguration configuration = createConfigurationFor(MockitoConfiguration.class) .fromFile(CONF_PATH + "/test_without_prefix.properties"); assertThat(configuration.getMockMakerClass()) .as("Configuration is map") .isNull(); } @Test public void should_return_empty_configuration__when_configuration_file_non_exist() { final MockitoConfiguration configuration = createConfigurationFor(MockitoConfiguration.class) .fromFile(CONF_PATH + "/test_without_prefix"); assertThat(configuration.getMockMakerClass()) .as("Configuration is null.") .isNull(); } @Test public void should_return_real_value_instead_alias() { final String value = "value"; final MockitoConfiguration configuration = createConfigurationFor(MockitoConfiguration.class) .withValueAlias("alias", value) .fromFile(CONF_PATH + "/test_with_alias.properties"); assertThat(configuration.getMockMakerClass()) .as("Configuration is map") .isEqualTo(value); } @Test public void should_read_powermock_global_ignore_as_array() { PowerMockConfiguration configuration = createConfigurationFor(PowerMockConfiguration.class) .fromFile(CONFIGURATION_FILE); assertThat(configuration.getGlobalIgnore()) .as("Configuration is map") .containsExactly("org.somepacckage.*","org.other.Class"); } } ================================================ FILE: powermock-core/src/test/java/org/powermock/configuration/support/ConfigurationFactoryImplTest.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.configuration.support; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.contrib.java.lang.system.EnvironmentVariables; import org.junit.experimental.runners.Enclosed; import org.junit.runner.RunWith; import org.powermock.configuration.ConfigurationFactory; import org.powermock.configuration.PowerMockConfiguration; import org.powermock.core.classloader.ByteCodeFramework; import static org.assertj.core.api.Java6Assertions.assertThat; @RunWith(Enclosed.class) public class ConfigurationFactoryImplTest { public static class SystemPropertiesCases { @Rule public final EnvironmentVariables environmentVariables = new EnvironmentVariables(); private ConfigurationFactory configurationFactory; @Before public void setUp() { configurationFactory = new ConfigurationFactoryImpl( "org/powermock/extensions/test.properties", "org/powermock/test_default_configuration.properties" ); } @Test public void should_read_byte_code_framework_from_environment_variable_if_defined() { environmentVariables.set("powermock.byte-code-framework", ByteCodeFramework.Javassist.name()); PowerMockConfiguration configuration = configurationFactory.create(PowerMockConfiguration.class); assertThat(configuration) .as("Configuration is created") .isNotNull(); assertThat(configuration.getByteCodeFramework()) .as("Enum from configuration is read correctly") .isEqualTo(ByteCodeFramework.Javassist); } } public static class FileCases { private ConfigurationFactory configurationFactory; @Before public void setUp() { configurationFactory = new ConfigurationFactoryImpl( "org/powermock/extensions/test_configuration.properties", "org/powermock/test_default_configuration.properties" ); } @Test public void should_return_configuration_from_file_if_configuration_file_exist() { PowerMockConfiguration configuration = configurationFactory.create(PowerMockConfiguration.class); assertThat(configuration) .as("Configuration is created") .isNotNull(); assertThat(configuration.getGlobalIgnore()) .as("Configuration is read correctly") .contains("org.somepackage"); assertThat(configuration.getByteCodeFramework()) .as("Enum from configuration is read correctly") .isEqualTo(ByteCodeFramework.Javassist); } @Test public void should_return_default_configuration_if_configuration_file_not_exist() { configurationFactory = new ConfigurationFactoryImpl( "org/powermock/test_default_configuration.properties" ); PowerMockConfiguration configuration = configurationFactory.create(PowerMockConfiguration.class); assertThat(configuration) .as("Configuration is created") .isNotNull(); assertThat(configuration.getGlobalIgnore()) .as("Configuration is read correctly") .contains("org.powermock.core*"); } @Test public void should_return_default_value_for_configuration_if_value_in_user_configuration_is_not_defined() { configurationFactory = new ConfigurationFactoryImpl( "org/powermock/extensions/test.properties", "org/powermock/test_default_configuration.properties" ); PowerMockConfiguration configuration = configurationFactory.create(PowerMockConfiguration.class); assertThat(configuration) .as("Configuration is created") .isNotNull(); assertThat(configuration.getByteCodeFramework()) .as("Enum from configuration is read correctly") .isEqualTo(ByteCodeFramework.Javassist); } } } ================================================ FILE: powermock-core/src/test/java/org/powermock/core/classloader/Collaborator.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.core.classloader; public class Collaborator { private int count; public void doStuff(int indx) { count += indx; } } ================================================ FILE: powermock-core/src/test/java/org/powermock/core/classloader/HardToTransform.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.core.classloader; public class HardToTransform { public void run() { Collaborator collaborator = new Collaborator(); for (int indx=0; indx<10; indx++) { collaborator.doStuff(indx); } } public int testInt() { return 5; } public double testDouble() { return 5; } public float testFloat() { return 5; } public long testLong() { return 5; } public short testShort() { return 5; } public byte testByte() { return 5; } public boolean testBoolean() { return true; } public char testChar() { return '5'; } public String testString() { return "5"; } } ================================================ FILE: powermock-core/src/test/java/org/powermock/core/classloader/MockClassLoaderBuilderTest.java ================================================ package org.powermock.core.classloader; import javassist.CtClass; import org.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.junit.Test; import org.powermock.PowerMockInternalException; import org.powermock.core.classloader.javassist.JavassistMockClassLoader; import org.powermock.core.transformers.ClassWrapper; import org.powermock.core.transformers.MockTransformer; import org.powermock.core.transformers.MockTransformerChain.FilterPredicate; import org.powermock.core.transformers.TestClassAwareTransformer; import org.powermock.core.transformers.support.DefaultMockTransformerChain; import org.powermock.reflect.internal.WhiteboxImpl; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class MockClassLoaderBuilderTest { @Test public void should_create_instance_of_MockClassLoader_depends_on_provided_bytecode_framework() { MockClassLoader classLoader = MockClassLoaderBuilder .create(ByteCodeFramework.Javassist) .forTestClass(getClass()) .build(); assertThat(classLoader).isExactlyInstanceOf(JavassistMockClassLoader.class); } @Test public void should_create_transformer_chain_depends_on_provided_bytecode_framework() { MockClassLoader classLoader = MockClassLoaderBuilder .create(ByteCodeFramework.Javassist) .forTestClass(getClass()) .build(); assertThatJavassistMockTransformerChainCreated(classLoader); } @Test public void should_set_test_class_to_TestClassAwareTransformers() { final SpyMockTransformer extraMockTransformer = new SpyMockTransformer(); MockClassLoaderBuilder .create(ByteCodeFramework.Javassist) .forTestClass(MockClassLoaderBuilderTest.class) .addExtraMockTransformers(extraMockTransformer) .build(); assertThat(extraMockTransformer.testClass) .as("Test class is set ") .isEqualTo(MockClassLoaderBuilderTest.class); } @Test public void should_throw_internal_exception_if_test_class_is_null() { assertThatThrownBy(new ThrowingCallable() { @Override public void call() { MockClassLoaderBuilder .create(ByteCodeFramework.Javassist) .build(); } }).as("Internal exception has been thrown.") .isExactlyInstanceOf(PowerMockInternalException.class); } private void assertThatJavassistMockTransformerChainCreated(final MockClassLoader classLoader) { final DefaultMockTransformerChain mockTransformerChain = (DefaultMockTransformerChain) classLoader.getMockTransformerChain(); assertThatMockTransformerChainWorksWithExpectedClassRepresentation(CtClass.class, mockTransformerChain); } private void assertThatMockTransformerChainWorksWithExpectedClassRepresentation(final Class expectedParameterClass, final DefaultMockTransformerChain mockTransformerChain) { final Method method = WhiteboxImpl.findMethod( mockTransformerChain.filter(new FilterPredicate() { @Override public boolean test(final MockTransformer mockTransformer) { return true; } }).iterator().next().getClass(), "transform", ClassWrapper.class ); final ParameterizedType returnType = (ParameterizedType) method.getGenericReturnType(); assertThat(returnType.getActualTypeArguments()) .withFailMessage( "Expected that transformer chain works with %s, however actually it works with %s", expectedParameterClass, ((Class) returnType.getActualTypeArguments()[0]).getName() ) .containsExactly(expectedParameterClass); } private static class SpyMockTransformer implements MockTransformer, TestClassAwareTransformer { private Class testClass; @Override public ClassWrapper transform(final ClassWrapper clazz) { return null; } @Override public void setTestClass(final Class testClass) { this.testClass = testClass; } } } ================================================ FILE: powermock-core/src/test/java/org/powermock/core/classloader/MockClassLoaderConfigurationTest.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.classloader; import org.junit.Before; import org.junit.Test; import static org.assertj.core.api.Java6Assertions.assertThat; public class MockClassLoaderConfigurationTest { private MockClassLoaderConfiguration configuration; @Before public void setUp() throws Exception { configuration = new MockClassLoaderConfiguration(); } @Test public void should_add_ignoredPackage_to_defer() { final String packageToIgnore = "test*"; configuration.addIgnorePackage(packageToIgnore); String[] deferPackages = configuration.getDeferPackages(); assertThat(deferPackages) .hasSize(MockClassLoaderConfiguration.PACKAGES_TO_BE_DEFERRED.length + 1) .contains(packageToIgnore); } @Test public void classes_to_modify_should_have_precedence_over_package_to_ignore() throws Exception { configuration.addClassesToModify("org.mytest.myclass"); configuration.addIgnorePackage("*mytest*"); assertThat(configuration.shouldModify("org.mytest.myclass")).isTrue(); } @Test public void classes_from_packages_to_modify_should_modify() throws Exception { configuration.addClassesToModify("*mytest*"); assertThat(configuration.shouldModify("org.mytest.myclass.SomeClass")).isTrue(); } } ================================================ FILE: powermock-core/src/test/java/org/powermock/core/classloader/MockClassLoaderFactoryTest.java ================================================ package org.powermock.core.classloader; import org.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.junit.Before; import org.junit.Test; import org.junit.experimental.runners.Enclosed; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import org.powermock.core.classloader.MockClassLoaderFactoryTest.TestContainer.ExceptionTestClass; import org.powermock.core.classloader.MockClassLoaderFactoryTest.TestContainer.JavassistTestClass; import org.powermock.core.classloader.MockClassLoaderFactoryTest.TestContainer.PrepareEverythingForTestTestClass; import org.powermock.core.classloader.MockClassLoaderFactoryTest.TestContainer.SuppressStaticInitializationForTestClass; import org.powermock.core.classloader.annotations.PrepareEverythingForTest; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor; import org.powermock.core.classloader.javassist.JavassistMockClassLoader; import org.powermock.reflect.Whitebox; import powermock.test.support.MainMockTransformerTestSupport.SupportClasses; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.assertj.core.api.Java6Assertions.assertThatThrownBy; import static org.powermock.core.test.ContainsCondition.contains; @RunWith(Enclosed.class) public class MockClassLoaderFactoryTest { @RunWith(Parameterized.class) public static class AnnotationTestOnClassLevelCases extends BasePrepareForTestCases { public AnnotationTestOnClassLevelCases(final Class testClass, String expectedClassToModify) { super(testClass, expectedClassToModify); } @Test public void should_extract_classes_to_modify_from_class_level_annotation() { final ClassLoader classLoader = objectUnderTest.createForClass(); assertThat(classLoader) .as("An instance of MockClassLoader is created") .isInstanceOf(MockClassLoader.class); assertThat(((MockClassLoader) classLoader).getConfiguration()) .as("MockClassLoader configuration contains expected class: %s", expectedClassToModify) .extracting("modify") .are(contains(expectedClassToModify)); } } @RunWith(Parameterized.class) public static class AnnotationOnMethodLevelCases extends BasePrepareForTestCases { @Parameters(name = "Test parameter: {0}") public static Collection parameters() { final ArrayList parameters = new ArrayList(); parameters.add(new Object[]{JavassistTestClass.class, "powermock.test.support.MainMockTransformerTestSupport$SupportClasses$FinalInnerClass"}); parameters.add(new Object[]{SuppressStaticInitializationForTestClass.class, "SupportClasses.FinalInnerClass"}); parameters.add(new Object[]{PrepareEverythingForTestTestClass.class, "*"}); return parameters; } public AnnotationOnMethodLevelCases(final Class testClass, String expectedClassToModify) { super(testClass, expectedClassToModify); } @Test public void should_extract_classes_to_modify_method_level_annotation_if_exist() { final Method method = Whitebox.getMethod(testClass, "someTestWithPrepareForTest"); final ClassLoader classLoader = objectUnderTest.createForMethod(method); assertThat(classLoader) .as("An instance of MockClassLoader is created") .isInstanceOf(MockClassLoader.class); assertThat(((MockClassLoader) classLoader).getConfiguration()) .as("MockClassLoader configuration contains expected class: %s", expectedClassToModify) .extracting("modify") .are(contains(expectedClassToModify)); } } @RunWith(Parameterized.class) public static class DifferentByteCodeFrameworkCases { @Parameters(name = "Test parameter: {0}") public static Collection parameters() { final ArrayList parameters = new ArrayList(); parameters.add(new Object[]{JavassistTestClass.class, JavassistMockClassLoader.class}); return parameters; } private final Class testClass; private final Class expectedClassLoaderClass; private MockClassLoaderFactory objectUnderTest; public DifferentByteCodeFrameworkCases(final Class testClass, final Class expectedClassLoaderClass) { this.testClass = testClass; this.expectedClassLoaderClass = expectedClassLoaderClass; } @Before public void setUp() { objectUnderTest = new MockClassLoaderFactory(testClass); } @Test public void should_create_a_correct_instance_of_class_loader_depends_on_PrepareForTest_parameter_of_class() { assertThat(objectUnderTest.createForClass()) .as("A classloader of the expected classes %s is created.", expectedClassLoaderClass.getName()) .isExactlyInstanceOf(expectedClassLoaderClass); } @Test public void should_create_a_correct_instance_of_class_loader_depends_on_PrepareForTest_parameter_of_method() { final Method method = Whitebox.getMethod(testClass, "someTestWithPrepareForTest"); assertThat(objectUnderTest.createForMethod(method)) .as("A classloader of the expected classes %s is created.", expectedClassLoaderClass.getName()) .isExactlyInstanceOf(expectedClassLoaderClass); } @Test public void should_create_a_correct_instance_of_class_loader_depends_and_use_PrepareForTest_from_class_if_method_does_not_have_annotation() { final Method method = Whitebox.getMethod(testClass, "someTestWithoutPrepareForTest"); assertThat(objectUnderTest.createForMethod(method)) .as("A classloader of the expected classes %s is created.", expectedClassLoaderClass.getName()) .isExactlyInstanceOf(expectedClassLoaderClass); } } public static class ExceptionCases{ MockClassLoaderFactory objectUnderTest; private Class testClass; @Before public void setUp() { testClass = ExceptionTestClass.class; objectUnderTest = new MockClassLoaderFactory(testClass); } @Test public void should_throw_exception_if_trying_to_create_an_instance_of_class_loader_for_method_without_annotations_and_class_without_annotation() { final Method method = Whitebox.getMethod(testClass, "someTestWithoutPrepareForTest"); assertThatThrownBy(new ThrowingCallable() { @Override public void call() { objectUnderTest.createForMethod(method); } }).as("Exception is thrown.") .isExactlyInstanceOf(IllegalArgumentException.class); } } public abstract static class BasePrepareForTestCases { @Parameters(name = "Test parameter: {0}") public static Collection parameters() { final ArrayList parameters = new ArrayList(); parameters.add(new Object[]{JavassistTestClass.class, "powermock.test.support.MainMockTransformerTestSupport$SupportClasses"}); parameters.add(new Object[]{SuppressStaticInitializationForTestClass.class, "SupportClasses.FinalInnerClass"}); parameters.add(new Object[]{PrepareEverythingForTestTestClass.class, "*"}); return parameters; } MockClassLoaderFactory objectUnderTest; final String expectedClassToModify; final Class testClass; BasePrepareForTestCases(final Class testClass, String expectedClassToModify) { this.testClass = testClass; this.expectedClassToModify = expectedClassToModify; } @Before public void setUp() { objectUnderTest = new MockClassLoaderFactory(testClass); } } @SuppressWarnings("WeakerAccess") public abstract static class TestContainer { @PrepareForTest(SupportClasses.class) public static class JavassistTestClass { @Test @PrepareForTest(SupportClasses.FinalInnerClass.class) public void someTestWithPrepareForTest() { } @Test public void someTestWithoutPrepareForTest() { } } @PrepareEverythingForTest public static class PrepareEverythingForTestTestClass { @Test @PrepareEverythingForTest public void someTestWithPrepareForTest() { } @Test public void someTestWithoutPrepareForTest() { } } @SuppressStaticInitializationFor("SupportClasses.FinalInnerClass") public static class SuppressStaticInitializationForTestClass { @Test @SuppressStaticInitializationFor("SupportClasses.FinalInnerClass") public void someTestWithPrepareForTest() { } @Test public void someTestWithoutPrepareForTest() { } } public static class ExceptionTestClass { @Test public void someTestWithoutPrepareForTest() { } } } } ================================================ FILE: powermock-core/src/test/java/org/powermock/core/classloader/MockClassLoaderTest.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.core.classloader; import javassist.ByteArrayClassPath; import javassist.ClassPool; import javassist.CtClass; import javassist.CtMethod; import net.bytebuddy.description.type.TypeDescription; import net.bytebuddy.dynamic.DynamicType.Builder; import net.bytebuddy.implementation.FixedValue; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.powermock.core.classloader.annotations.UseClassPathAdjuster; import org.powermock.core.classloader.javassist.ClassPathAdjuster; import org.powermock.core.classloader.javassist.JavassistMockClassLoader; import org.powermock.core.test.MockClassLoaderFactory; import org.powermock.core.transformers.ClassWrapper; import org.powermock.core.transformers.MockTransformer; import org.powermock.core.transformers.MockTransformerChain; import org.powermock.core.transformers.support.DefaultMockTransformerChain; import org.powermock.reflect.Whitebox; import java.lang.annotation.Annotation; import java.net.URL; import java.util.Enumeration; import java.util.List; import static org.assertj.core.api.Java6Assertions.assertThat; import static java.util.Arrays.asList; import static net.bytebuddy.matcher.ElementMatchers.isDeclaredBy; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertFalse; import static org.junit.Assume.assumeThat; import static org.powermock.core.classloader.MockClassLoader.MODIFY_ALL_CLASSES; @RunWith(Parameterized.class) public class MockClassLoaderTest { @Parameterized.Parameters(name = "ClassLoader: {0}") public static List data() { final Object[] objects = { JavassistMockClassLoader.class, new JavassistMockTransformer() }; return asList(new Object[][]{objects}); } private final MockClassLoaderFactory mockClassLoaderFactory; private final Class clazz; private final MockTransformerChain mockTransformerChain; public MockClassLoaderTest(Class clazz, MockTransformer transformer) { this.mockClassLoaderFactory = new MockClassLoaderFactory(clazz); this.clazz = clazz; this.mockTransformerChain = DefaultMockTransformerChain.newBuilder() .append(transformer) .build(); } @Test public void should_load_and_modify_class_from_package_which_specified() throws Exception { String className = "powermock.test.support.ClassForMockClassLoaderTestCase"; MockClassLoader mockClassLoader = mockClassLoaderFactory.getInstance(new String[]{ className }); mockClassLoader.setMockTransformerChain(mockTransformerChain); Class clazz = Class.forName(className, false, mockClassLoader); assertClassIsLoaded(clazz, mockClassLoader); assertThatInstanceCouldBeCreateAndMethodReturnMockedValue(clazz); } @Test public void should_load_and_not_modify_class_from_package_which_are_not_specified_as_ignored_or_class_to_mock() throws Exception { String className = "powermock.test.support.ClassForMockClassLoaderTestCase"; MockClassLoader mockClassLoader = mockClassLoaderFactory.getInstance(new String[0]); mockClassLoader.setMockTransformerChain(mockTransformerChain); Class clazz = Class.forName(className, false, mockClassLoader); assertClassIsLoaded(clazz, mockClassLoader); assertThatInstanceCouldBeCreateAndMethodReturnNotMockedValue(clazz); } @Test public void should_load_system_classes() throws Exception { MockClassLoader mockClassLoader = mockClassLoaderFactory.getInstance(new String[]{"org.mytest.myclass"}); Class clazz = Class.forName("java.lang.String", false, mockClassLoader); assertThat(clazz) .as("System class is loaded") .isEqualTo(String.class); } @Test public void should_load_defined_class() throws Exception { final String className = "my.ABCTestClass"; final MockClassLoader mockClassLoader = mockClassLoaderFactory.getInstance(new String[]{className}); Whitebox.invokeMethod(mockClassLoader, "defineClass", className, DynamicClassHolder.classBytes, 0, DynamicClassHolder.classBytes.length, this.getClass().getProtectionDomain()); Class clazz = Class.forName(className, false, mockClassLoader); assertThat(clazz) .as("Defined class is loaded") .isNotNull(); } @Test public void should_ignore_pagackage_added_powerMockIgnore_Annotated() throws Exception { MockClassLoader mockClassLoader = mockClassLoaderFactory.getInstance(new String[]{"org.ikk.Jux"}); MockClassLoaderConfiguration configuration = mockClassLoader.getConfiguration(); Whitebox.setInternalState(configuration, "deferPackages", new String[]{"*mytest*"}, MockClassLoaderConfiguration.class); assertFalse(configuration.shouldModify("org.mytest.myclass")); } @Test public void powerMockIgnoreAnnotatedPackagesHavePrecedenceOverPrepareEverythingForTest() throws Exception { MockClassLoader mockClassLoader = mockClassLoaderFactory.getInstance(new String[]{MODIFY_ALL_CLASSES}); MockClassLoaderConfiguration configuration = mockClassLoader.getConfiguration(); Whitebox.setInternalState(configuration, "deferPackages", new String[]{"*mytest*"}, MockClassLoaderConfiguration.class); assertFalse(configuration.shouldModify("org.mytest.myclass")); } @Test public void should_find_and_return_a_one_resource_which_exist() throws Exception { final MockClassLoader mockClassLoader = mockClassLoaderFactory.getInstance(new String[0]); // Force a ClassLoader that can find 'foo/bar/baz/test.txt' into // mockClassLoader.deferTo. mockClassLoader.deferTo = new ResourcePrefixClassLoader(getClass().getClassLoader(), "org/powermock/core/classloader/"); // MockClassLoader will only be able to find 'foo/bar/baz/test.txt' if it // properly defers the resource lookup to its deferTo ClassLoader. URL resource = mockClassLoader.getResource("foo/bar/baz/test.txt"); assertThat(resource).isNotNull(); assertThat(resource.getPath()).endsWith("test.txt"); } @Test public void should_find_and_return_resources_which_exist() throws Exception { final MockClassLoader mockClassLoader = mockClassLoaderFactory.getInstance(new String[0]); // Force a ClassLoader that can find 'foo/bar/baz/test.txt' into // mockClassLoader.deferTo. mockClassLoader.deferTo = new ResourcePrefixClassLoader(getClass().getClassLoader(), "org/powermock/core/classloader/"); // MockClassLoader will only be able to find 'foo/bar/baz/test.txt' if it // properly defers the resources lookup to its deferTo ClassLoader. Enumeration resources = mockClassLoader.getResources("foo/bar/baz/test.txt"); assertThat(resources.nextElement().getPath()).endsWith("test.txt"); } @Test public void resourcesNotDoubled() throws Exception { final MockClassLoader mockClassLoader = mockClassLoaderFactory.getInstance(new String[0]); //mockClassLoader.setMockTransformerChain(transformerChain); // MockClassLoader will only be able to find 'foo/bar/baz/test.txt' if it // properly defers the resources lookup to its deferTo ClassLoader. Enumeration resources = mockClassLoader.getResources("org/powermock/core/classloader/foo/bar/baz/test.txt"); assertThat(resources.nextElement().getPath()).endsWith("test.txt"); assertThat(resources.hasMoreElements()).isFalse(); } @Test public void canFindDynamicClassFromAdjustedClasspath() throws Exception { assumeThat(clazz.getName(), equalTo(JavassistMockClassLoader.class.getName())); // Construct MockClassLoader with @UseClassPathAdjuster annotation. // It activates our MyClassPathAdjuster class which appends our dynamic // class to the MockClassLoader's classpool. UseClassPathAdjuster useClassPathAdjuster = new TestUseClassPathAdjuster(); final MockClassLoader mockClassLoader = mockClassLoaderFactory.getInstance(new String[0], useClassPathAdjuster); // setup custom classloader providing our dynamic class, for MockClassLoader to defer to mockClassLoader.deferTo = new ClassLoader(getClass().getClassLoader()) { @Override public Class loadClass(String name) throws ClassNotFoundException { if (name.equals(DynamicClassHolder.clazz.getName())) { return DynamicClassHolder.clazz; } return super.loadClass(name); } }; // verify that MockClassLoader can successfully load the class Class dynamicTestClass = Class.forName(DynamicClassHolder.clazz.getName(), false, mockClassLoader); assertThat(dynamicTestClass).isNotSameAs(DynamicClassHolder.clazz); } @Test(expected = ClassNotFoundException.class) @Ignore("Has to be decided desirable behaviour in this case") public void should_throw_ClassNotFoundException_if_cannot_find_dynamic_class_in_deferred_class_loader() throws Exception { MockClassLoader mockClassLoader = mockClassLoaderFactory.getInstance(new String[0]); // setup custom classloader providing our dynamic class, for MockClassLoader to defer to mockClassLoader.deferTo = new ClassLoader(getClass().getClassLoader()) { @Override public Class loadClass(String name) throws ClassNotFoundException { return super.loadClass(name); } }; //Try to locate and load a class that is not in MockClassLoader. Class.forName(DynamicClassHolder.clazz.getName(), false, mockClassLoader); } @Test public void should_autobox_primitive_values() throws Exception { String name = this.getClass().getPackage().getName() + ".HardToTransform"; final MockClassLoader mockClassLoader = mockClassLoaderFactory.getInstance(new String[]{name}); Class c = mockClassLoader.loadClass(name); Object object = c.newInstance(); Whitebox.invokeMethod(object, "run"); assertThat(5).isEqualTo(Whitebox.invokeMethod(object, "testInt")); assertThat(5L).isEqualTo(Whitebox.invokeMethod(object, "testLong")); assertThat(5f).isEqualTo(Whitebox.invokeMethod(object, "testFloat")); assertThat(5.0).isEqualTo(Whitebox.invokeMethod(object, "testDouble")); assertThat(new Short("5")).isEqualTo(Whitebox.invokeMethod(object, "testShort")); assertThat(new Byte("5")).isEqualTo(Whitebox.invokeMethod(object, "testByte")); assertThat(true).isEqualTo(Whitebox.invokeMethod(object, "testBoolean")); assertThat('5').isEqualTo(Whitebox.invokeMethod(object, "testChar")); assertThat("5").isEqualTo(Whitebox.invokeMethod(object, "testString")); } private void assertThatInstanceCouldBeCreateAndMethodReturnMockedValue(final Class clazz) throws Exception { Object instance = Whitebox.newInstance(clazz); assertThat(instance) .as("Instance of class is created.") .isNotNull(); assertThat((String) Whitebox.invokeMethod(instance, "description")) .as("Method of instance of loaded class returns mocked value.") .isNull(); } private void assertThatInstanceCouldBeCreateAndMethodReturnNotMockedValue(final Class clazz) throws Exception { Object instance = Whitebox.newInstance(clazz); assertThat(instance) .as("Instance of class is created.") .isNotNull(); assertThat((String) Whitebox.invokeMethod(instance, "description")) .as("Method of instance of loaded class returns not mocked value.") .isNotNull(); } private void assertClassIsLoaded(final Class clazz, final MockClassLoader mockClassLoader) { assertThat(clazz) .as("Test class is loaded.") .isNotNull(); assertThat(clazz.getClassLoader()) .as("Class is loaded by mock classloader") .isSameAs(mockClassLoader); } // helper class for canFindDynamicClassFromAdjustedClasspath() public static class MyClassPathAdjuster implements ClassPathAdjuster { public void adjustClassPath(ClassPool classPool) { classPool.appendClassPath(new ByteArrayClassPath(DynamicClassHolder.clazz.getName(), DynamicClassHolder.classBytes)); } } // helper class for canFindDynamicClassFromAdjustedClasspath() static class DynamicClassHolder { final static byte[] classBytes; final static Class clazz; static { try { // construct a new class dynamically ClassPool cp = ClassPool.getDefault(); final CtClass ctClass = cp.makeClass("my.ABCTestClass"); classBytes = ctClass.toBytecode(); clazz = ctClass.toClass(); } catch (Exception e) { throw new RuntimeException("Problem constructing custom class", e); } } } public static class TestUseClassPathAdjuster implements UseClassPathAdjuster { public Class annotationType() { return UseClassPathAdjuster.class; } public Class value() { return MyClassPathAdjuster.class; } } private static class JavassistMockTransformer implements MockTransformer { @Override public ClassWrapper transform(final ClassWrapper clazz) throws Exception { CtClass ctClass = clazz.unwrap(); for (CtMethod ctMethod : ctClass.getMethods()) { CtClass returnType = ctMethod.getReturnType(); if (returnType.getName().equals(String.class.getName())) { ctMethod.setBody("return null;"); } } return clazz; } } } ================================================ FILE: powermock-core/src/test/java/org/powermock/core/classloader/ResourcePrefixClassLoader.java ================================================ package org.powermock.core.classloader; import java.io.IOException; import java.net.URL; import java.util.Enumeration; @SuppressWarnings("SameParameterValue") public class ResourcePrefixClassLoader extends ClassLoader { private final String prefix; public ResourcePrefixClassLoader(ClassLoader parent, String prefix) { super(parent); this.prefix = prefix; } @Override protected Enumeration findResources(String name) throws IOException { // default super behaviour returns null, we want to delegate to our parent, with a prefix return getParent().getResources(this.prefix + name); } @Override protected URL findResource(String name) { return getParent().getResource(this.prefix + name); } } ================================================ FILE: powermock-core/src/test/java/org/powermock/core/test/ClassLoaderTestHelper.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.test; import javassist.ClassPool; import javassist.Loader; import org.powermock.configuration.GlobalConfiguration; import org.powermock.configuration.PowerMockConfiguration; import org.powermock.core.classloader.MockClassLoader; import org.powermock.core.transformers.MockTransformerChain; import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.assertNotNull; public class ClassLoaderTestHelper { public static Map> cache; static { cache = new HashMap>(); } public static Class loadWithMockClassLoader(final String className, final MockTransformerChain mockTransformerChain, final MockClassLoaderFactory mockClassloaderFactory) throws Exception { MockClassLoader loader = getMockClassLoader(mockTransformerChain, mockClassloaderFactory); Class clazz = Class.forName(className, true, loader); assertNotNull("Class has been loaded", clazz); return clazz; } public static Class loadWithMockClassLoader(final String className, final byte[] klass, final MockTransformerChain mockTransformerChain, final MockClassLoaderFactory mockClassloaderFactory) throws Exception { MockClassLoader loader = getMockClassLoader(mockTransformerChain, mockClassloaderFactory); final Class definedClass = loader.defineClass(className, ClassLoaderTestHelper.class.getProtectionDomain(), klass); assertNotNull("Class has been loaded", definedClass); return definedClass; } private static MockClassLoader getMockClassLoader(final MockTransformerChain mockTransformerChain, final MockClassLoaderFactory mockClassloaderFactory) throws IllegalAccessException, InvocationTargetException, InstantiationException { MockClassLoader loader = null; Map classloaders = cache.get(mockClassloaderFactory); if (classloaders != null){ loader = classloaders.get(mockTransformerChain); }else{ classloaders = new HashMap(); cache.put(mockClassloaderFactory, classloaders); } if (loader == null) { loader = mockClassloaderFactory.getInstance(new String[]{MockClassLoader.MODIFY_ALL_CLASSES}); loader.setMockTransformerChain(mockTransformerChain); classloaders.put(mockTransformerChain, loader); } return loader; } public static void runTestWithNewClassLoader(ClassPool classPool, String name) throws Throwable { Loader loader = new Loader(classPool); loader.run(name, new String[0]); } public static void clearCache() { cache.clear(); } } ================================================ FILE: powermock-core/src/test/java/org/powermock/core/test/ContainsCondition.java ================================================ package org.powermock.core.test; import org.assertj.core.api.Condition; import org.assertj.core.description.Description; import org.powermock.core.classloader.MockClassLoaderFactoryTest; import java.util.Collection; public class ContainsCondition extends Condition { public static ContainsCondition contains(final String expectedClassToModify) { return new ContainsCondition(expectedClassToModify); } private final String expectedClassToModify; private ContainsCondition(final String expectedClassToModify) { super(String.format("contains value `%s`", expectedClassToModify)); this.expectedClassToModify = expectedClassToModify; } @Override public boolean matches(final Object value) { Collection strings = (Collection) value; return strings.contains(expectedClassToModify); } } ================================================ FILE: powermock-core/src/test/java/org/powermock/core/test/MockClassLoaderFactory.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.test; import org.powermock.core.classloader.MockClassLoader; import org.powermock.core.classloader.MockClassLoaderConfiguration; import org.powermock.core.classloader.annotations.UseClassPathAdjuster; import org.powermock.reflect.internal.WhiteboxImpl; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; public class MockClassLoaderFactory { private final Class classLoaderClass; public MockClassLoaderFactory(Class classLoaderClass) { this.classLoaderClass = classLoaderClass; } public MockClassLoader getInstance(String[] classesToMock, UseClassPathAdjuster useClassPathAdjuster) throws IllegalAccessException, InvocationTargetException, InstantiationException { Constructor constructor = WhiteboxImpl.getConstructor(classLoaderClass, classesToMock.getClass(), classesToMock.getClass(), UseClassPathAdjuster.class); return (MockClassLoader) constructor.newInstance(classesToMock, new String[0], useClassPathAdjuster); } public MockClassLoader getInstance(String[] classesToMock) throws IllegalAccessException, InvocationTargetException, InstantiationException { MockClassLoaderConfiguration configuration = new MockClassLoaderConfiguration(classesToMock, new String[0]); return getInstance(configuration); } private MockClassLoader getInstance(MockClassLoaderConfiguration configuration) throws IllegalAccessException, InvocationTargetException, InstantiationException { Constructor constructor = WhiteboxImpl.getConstructor(classLoaderClass, configuration.getClass()); return (MockClassLoader) constructor.newInstance(new Object[]{configuration}); } public boolean isByteBuddy(){ return false; } @Override public String toString() { return classLoaderClass.getSimpleName(); } } ================================================ FILE: powermock-core/src/test/java/org/powermock/core/testlisteners/GlobalNotificationBuildSupportTest.java ================================================ /* * Copyright 2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.core.testlisteners; import org.junit.AfterClass; import org.junit.Test; import org.powermock.core.testlisteners.GlobalNotificationBuildSupport.Callback; import java.util.Collection; import java.util.concurrent.ConcurrentHashMap; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; /** * The design of this test-class does only allow it to be run once per JVM * (or more accurately "per classloader", in case the test-class is redefined * by different classloaders in some sort of test suite), * because it will test some class instantiation, which can only occur one per * class. */ @SuppressWarnings({"SameParameterValue", "ResultOfMethodCallIgnored"}) public class GlobalNotificationBuildSupportTest { static boolean initiationOfNormalClassIsUnderWay; static final Callback mockCallback = mock(Callback.class); @SuppressWarnings("SameParameterValue") static class NormalClass { static { initiationOfNormalClassIsUnderWay = true; GlobalNotificationBuildSupport.testClassInitiated(NormalClass.class); } NormalClass(String dummy) { GlobalNotificationBuildSupport.testInstanceCreated(this); } public NormalClass() { this("dummy"); GlobalNotificationBuildSupport.testInstanceCreated(this); } } @SuppressWarnings("SameParameterValue") static class SubClass extends NormalClass { public SubClass() { super("dummy"); } public SubClass(String dummy) { } } private String nestedClassName(String localName) { return GlobalNotificationBuildSupportTest.class.getName() + "$" + localName; } private void assertNotificationOf(NormalClass normalInstance) { verify(mockCallback).testInstanceCreated(normalInstance); verifyNoMoreInteractions(mockCallback); } @Test public void normalClassCreation() { // Given assertFalse("Initiation of NormalClass must not yet have commenced", initiationOfNormalClassIsUnderWay); GlobalNotificationBuildSupport.prepareTestSuite( nestedClassName("NormalClass"), mockCallback); /* Nothing must have happened so far ... */ verifyNoMoreInteractions(mockCallback); // When final NormalClass normalInstance = new NormalClass(); // Then verify life-cycle callbacks on NormalClass verify(mockCallback).suiteClassInitiated(NormalClass.class); // Then notifications of created instances are expected ... assertNotificationOf(normalInstance); assertNotificationOf(new NormalClass()); assertNotificationOf(new NormalClass()); assertNotificationOf(new NormalClass("dummy")); assertNotificationOf(new SubClass("dummy")); assertNotificationOf(new NormalClass("dummy")); assertNotificationOf(new SubClass("dummy")); assertNotificationOf(new NormalClass()); // Tear-down GlobalNotificationBuildSupport.closeTestSuite(NormalClass.class); new NormalClass("dummy").toString(); new SubClass().hashCode(); verifyNoMoreInteractions(mockCallback); // Creation should no longer have any affect } /** * Tests some ConcurrentHashMap functionality that * {@link GlobalNotificationBuildSupport#closePendingTestSuites(Callback)} * depends on. */ @Test public void removeAllFromConcurrentHashMap() { ConcurrentHashMap map = new ConcurrentHashMap(); final Object value = new Object(); map.put("foo", value); map.put("bar", value); assertEquals("Size of concurrent hashmap", 2, map.size()); Collection valueToRemove = java.util.Collections.singleton(value); map.values().removeAll(valueToRemove); assertEquals("Size of concurrent hashmap after removal of values", 0, map.size()); } @AfterClass public static void closeTestSuite() { GlobalNotificationBuildSupport.closeTestSuite(NormalClass.class); GlobalNotificationBuildSupport.closePendingTestSuites(mockCallback); } } ================================================ FILE: powermock-core/src/test/java/org/powermock/core/transformers/AbstractBaseMockTransformerTest.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.transformers; import javassist.CtClass; import org.junit.Before; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.powermock.core.MockGateway; import org.powermock.core.test.ClassLoaderTestHelper; import org.powermock.core.test.MockClassLoaderFactory; import org.powermock.core.transformers.javassist.support.JavaAssistClassWrapperFactory; import org.powermock.core.transformers.mock.MockGatewaySpy; import org.powermock.core.transformers.support.FilterPredicates; import static org.junit.Assume.assumeTrue; @RunWith(Parameterized.class) abstract class AbstractBaseMockTransformerTest { static final String SYNTHETIC_METHOD_NAME = "$synth"; static final String SYNTH_FIELD = "$_synthField"; protected final TransformStrategy strategy; protected final MockTransformerChain mockTransformerChain; protected final MockClassLoaderFactory mockClassloaderFactory; AbstractBaseMockTransformerTest(final TransformStrategy strategy, final MockTransformerChain mockTransformerChain, final MockClassLoaderFactory mockClassloaderFactory){ this.strategy = strategy; this.mockTransformerChain = mockTransformerChain; this.mockClassloaderFactory = mockClassloaderFactory; } @Before public void setUp() throws Exception { ClassLoaderTestHelper.clearCache(); MockGatewaySpy.clear(); MockGatewaySpy.returnOnMethodCall(MockGateway.PROCEED); } protected Class loadWithMockClassLoader(final String name) throws Exception { return ClassLoaderTestHelper.loadWithMockClassLoader(name, mockTransformerChain, mockClassloaderFactory); } protected Class loadWithMockClassLoader(final CtClass ctClass) throws Exception { return ClassLoaderTestHelper.loadWithMockClassLoader(ctClass.getName(), ctClass.toBytecode(), mockTransformerChain, mockClassloaderFactory); } ClassWrapper wrap(final CtClass ctClass) { return new JavaAssistClassWrapperFactory().wrap(ctClass); } protected void assumeClassLoaderMode() { assumeTrue("Supported only by class loader mode.", strategy.isClassloaderMode()); } protected void assumeAgentMode() { assumeTrue("Supported only by class loader mode.", strategy.isAgentMode()); } protected void assumeClassLoaderIsByteBuddy() { assumeTrue( "ByteBuddy implantation MockClassLoader should always add defer constructor," + " because ByteBuddy cannot add constructor to super class ad-hoc.", mockClassloaderFactory.isByteBuddy() ); } protected void setTestClassToTransformers(final Class testClass) { for (MockTransformer transformer : mockTransformerChain.filter(FilterPredicates.isInstanceOf(TestClassAwareTransformer.class))) { ((TestClassAwareTransformer) transformer).setTestClass(testClass); } } } ================================================ FILE: powermock-core/src/test/java/org/powermock/core/transformers/ClassFinalModifierMockTransformerTest.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.transformers; import org.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.junit.Test; import org.junit.runners.Parameterized; import org.powermock.core.test.MockClassLoaderFactory; import powermock.test.support.MainMockTransformerTestSupport.SomeInterface; import powermock.test.support.MainMockTransformerTestSupport.SupportClasses; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import static java.lang.reflect.Modifier.isFinal; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.assertj.core.api.Java6Assertions.catchThrowable; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.not; import static org.junit.Assert.assertFalse; import static org.junit.Assume.assumeThat; public class ClassFinalModifierMockTransformerTest extends AbstractBaseMockTransformerTest { @Parameterized.Parameters(name = "strategy: {0}, transformerType: {2}") public static Iterable data() { Collection data = new ArrayList(); data.addAll(MockTransformerTestHelper.createTransformerTestData(org.powermock.core.transformers.javassist.ClassFinalModifierMockTransformer.class)); return data; } public ClassFinalModifierMockTransformerTest( final TransformStrategy strategy, final MockTransformerChain mockTransformerChain, final MockClassLoaderFactory mockClassloaderFactory ) { super(strategy, mockTransformerChain, mockClassloaderFactory); } @Test public void should_remove_final_modifier_from_static_final_inner_classes_strategy_not_equals_to_inst_redefine() throws Exception { assumeThat(strategy, not(equalTo(TransformStrategy.INST_REDEFINE))); Class clazz = loadWithMockClassLoader(SupportClasses.StaticFinalInnerClass.class.getName()); assertFalse(Modifier.isFinal(clazz.getModifiers())); } @Test public void should_nit_remove_final_modifier_from_static_final_inner_classes_equals_to_inst_redefine() throws Exception { assumeThat(strategy, equalTo(TransformStrategy.INST_REDEFINE)); Class clazz = loadWithMockClassLoader(SupportClasses.StaticFinalInnerClass.class.getName()); assertThat(isFinal(clazz.getModifiers())).isTrue(); } @Test public void should_remove_final_modifier_from_final_inner_classes() throws Exception { assumeThat(strategy, not(equalTo(TransformStrategy.INST_REDEFINE))); Class clazz = loadWithMockClassLoader(SupportClasses.FinalInnerClass.class.getName()); assertFalse(Modifier.isFinal(clazz.getModifiers())); } @Test public void should_remove_final_modifier_from_enums() throws Exception { assumeThat(strategy, not(equalTo(TransformStrategy.INST_REDEFINE))); Class clazz = loadWithMockClassLoader(SupportClasses.EnumClass.class.getName()); assertFalse(Modifier.isFinal(clazz.getModifiers())); } @Test public void should_remove_final_modifier_from_private_static_final_inner_classes() throws Exception { assumeThat(strategy, not(equalTo(TransformStrategy.INST_REDEFINE))); Class clazz = loadWithMockClassLoader(SupportClasses.class.getName() + "$PrivateStaticFinalInnerClass"); assertFalse(Modifier.isFinal(clazz.getModifiers())); } @Test public void should_ignore_interfaces() throws Exception { Throwable throwable = catchThrowable(new ThrowingCallable() { @Override public void call() throws Throwable { loadWithMockClassLoader(SomeInterface.class.getName()); } }); assertThat(throwable).isNull(); } } ================================================ FILE: powermock-core/src/test/java/org/powermock/core/transformers/ConstructorCallMockTransformerTest.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.transformers; import org.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.assertj.core.api.iterable.Extractor; import org.junit.Test; import org.junit.runners.Parameterized; import org.powermock.core.IndicateReloadClass; import org.powermock.core.test.MockClassLoaderFactory; import org.powermock.core.transformers.javassist.InstrumentMockTransformer; import org.powermock.core.transformers.mock.MockGatewaySpy; import org.powermock.core.transformers.mock.MockGatewaySpy.MethodCall; import powermock.test.support.MainMockTransformerTestSupport.ConstructorCall.SupperClassThrowsException; import powermock.test.support.MainMockTransformerTestSupport.ParameterImpl; import powermock.test.support.MainMockTransformerTestSupport.ParameterInterface; import powermock.test.support.MainMockTransformerTestSupport.ParentTestClass; import powermock.test.support.MainMockTransformerTestSupport.ParentTestClass.NestedTestClass; import powermock.test.support.MainMockTransformerTestSupport.SomeInterface; import powermock.test.support.MainMockTransformerTestSupport.SuperClassCallSuperConstructor; import powermock.test.support.MainMockTransformerTestSupport.SuperClassCallSuperConstructorWithCast; import powermock.test.support.MainMockTransformerTestSupport.SuperClassCallSuperConstructorWithVararg; import powermock.test.support.MainMockTransformerTestSupport.SupportClasses; import powermock.test.support.MainMockTransformerTestSupport.SupportClasses.EnumClass; import powermock.test.support.MainMockTransformerTestSupport.SupportClasses.MultipleConstructors; import powermock.test.support.MainMockTransformerTestSupport.SupportClasses.PublicSuperClass; import powermock.test.support.MainMockTransformerTestSupport.SupportClasses.SubClass; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.Collection; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.assertj.core.api.Java6Assertions.assertThatThrownBy; import static org.assertj.core.api.Java6Assertions.catchThrowable; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assume.assumeThat; import static org.powermock.core.MockGateway.PROCEED; import static org.powermock.core.MockGateway.SUPPRESS; import static org.powermock.core.transformers.MockTransformerTestHelper.createTransformerTestDataWithMockGateway; public class ConstructorCallMockTransformerTest extends AbstractBaseMockTransformerTest { @Parameterized.Parameters(name = "strategy: {0}, transformerType: {2}") public static Iterable data() { Collection data = new ArrayList(); data.addAll(createTransformerTestDataWithMockGateway(MockGatewaySpy.class, InstrumentMockTransformer.class)); return data; } public ConstructorCallMockTransformerTest(final TransformStrategy strategy, final MockTransformerChain mockTransformerChain, final MockClassLoaderFactory mockClassloaderFactory) { super(strategy, mockTransformerChain, mockClassloaderFactory); } @Test public void should_not_change_constructors_of_test_class() throws Exception { assumeClassLoaderMode(); final Class testClass = MultipleConstructors.class; setTestClassToTransformers(testClass); final Class modifiedClass = reloadClass(testClass); assertThat(modifiedClass.getConstructors()) .hasSameSizeAs(testClass.getConstructors()); assertThatThrownBy( new ThrowingCallable() { @Override public void call() throws Throwable { modifiedClass.getConstructor(IndicateReloadClass.class); } } ).withFailMessage("A public defer-constructor is added.") .isExactlyInstanceOf(NoSuchMethodException.class); } @Test public void should_not_change_constructors_of_nested_test_classes() throws Exception { assumeClassLoaderMode(); setTestClassToTransformers(ParentTestClass.class); final Class originalClazz = NestedTestClass.class; final Class modifiedClass = reloadClass(originalClazz); assertThat(modifiedClass.getConstructors()) .hasSameSizeAs(originalClazz.getConstructors()); assertThatThrownBy( new ThrowingCallable() { @Override public void call() throws Throwable { modifiedClass.getConstructor(IndicateReloadClass.class); } } ).withFailMessage("A public defer-constructor is added.") .isExactlyInstanceOf(NoSuchMethodException.class); } @Test public void should_add_additional_defer_constructor_which_call_default_if_parent_Object_and_strategy_classloader() throws Exception { assumeClassLoaderMode(); assumeClassLoaderIsByteBuddy(); Class clazz = reloadClass(PublicSuperClass.class); assertThat(clazz.getConstructors()) .as("Number of constructors in modified class") .hasSize(2); assertThat(clazz.getConstructor(IndicateReloadClass.class)) .as("Defer-constructor returnOnMethodCall") .isNotNull(); } @Test public void should_add_additional_defer_constructor_which_call_default_if_parent_not_Object_and_strategy_classloader() throws Exception { assumeClassLoaderMode(); Class clazz = reloadClass(SubClass.class); assertThat(clazz.getConstructors()) .as("Number of constructors in modified class") .hasSize(2); assertThat(clazz.getConstructor(IndicateReloadClass.class)) .as("Defer-constructor returnOnMethodCall") .isNotNull(); } @Test public void should_not_add_additional_defer_constructor_if_strategy_is_not_classloader() throws Exception { assumeAgentMode(); Class clazz = loadWithMockClassLoader(SupportClasses.SubClass.class.getName()); assertThat(clazz.getConstructors()) .as("Number of constructors in modified class") .hasSameSizeAs(SupportClasses.SubClass.class.getConstructors()); } @Test public void should_not_add_defer_constructor_to_interface() throws Exception { Class clazz = loadWithMockClassLoader(SomeInterface.class.getName()); assertThat(clazz.getConstructors()) .as("Number of constructors in modified interface same as in original") .hasSameSizeAs(SomeInterface.class.getConstructors()); } @Test public void should_not_add_defer_constructor_to_enum() throws Exception { Class clazz = loadWithMockClassLoader(EnumClass.class.getName()); assertThat(clazz.getConstructors()) .as("Number of constructors in modified class same as in original") .hasSameSizeAs(EnumClass.class.getConstructors()); } @Test public void should_suppress_call_to_super_constructor_if_getaway_return_SUPPRESS() throws Exception { assumeClassLoaderMode(); MockGatewaySpy.returnOnMethodCall(SUPPRESS); Class clazz = loadWithMockClassLoader(SuperClassCallSuperConstructor.class.getName()); final Constructor constructor = clazz.getConstructor(String.class, String.class, double.class); Throwable throwable = catchThrowable(new ThrowingCallable() { @Override public void call() throws Throwable { try { constructor.newInstance("name", "field", 100); } catch (Exception e) { throw e.getCause() == null ? e : e.getCause(); } } }); assertThat(throwable) .as("Call to super is suppressed") .isNull(); } @Test public void should_not_suppress_call_to_super_constructor_if_getaway_return_PROCEED() throws Exception { assumeClassLoaderMode(); MockGatewaySpy.returnOnMethodCall(PROCEED); Class clazz = loadWithMockClassLoader(SuperClassCallSuperConstructor.class.getName()); final Constructor constructor = clazz.getConstructor(String.class, String.class, double.class); Throwable throwable = catchThrowable(new ThrowingCallable() { @Override public void call() throws Throwable { try { constructor.newInstance("name", "field", 100); } catch (Exception e) { throw e.getCause() == null ? e : e.getCause(); } } }); assertThat(throwable) .as("Call to super is not suppressed") .isInstanceOf(IllegalArgumentException.class) .hasMessage(SupperClassThrowsException.MESSAGE); } @Test public void should_provide_correct_constructor_param_and_arguments() throws Exception { assumeClassLoaderMode(); MockGatewaySpy.returnOnMethodCall(SUPPRESS); Class clazz = loadWithMockClassLoader(SuperClassCallSuperConstructor.class.getName()); final Constructor constructor = clazz.getConstructor(String.class, String.class, double.class); constructor.newInstance("name", "field", 100); assertThatCorrectConstructorTypeProvided(); final MethodCall methodCall = MockGatewaySpy.constructorCalls().get(0); assertThat(methodCall.args) .as("Correct constructor arguments are provided") .containsExactly("name", 100.0); assertThat(methodCall.sig) .as("Correct constructor signature is provided") .containsExactly(String.class, double.class); } @Test public void should_provide_correct_constructor_param_and_arguments_when_cast_required() throws Exception { assumeClassLoaderMode(); MockGatewaySpy.returnOnMethodCall(SUPPRESS); final Class clazz = loadWithMockClassLoader(SuperClassCallSuperConstructorWithCast.class.getName()); final Class paramClass = loadWithMockClassLoader(ParameterInterface.class.getName()); final Object param = loadWithMockClassLoader(ParameterImpl.class.getName()).newInstance(); final Constructor constructor = clazz.getConstructor(paramClass); constructor.newInstance(param); assertThatCorrectConstructorTypeProvided(); final MethodCall methodCall = MockGatewaySpy.constructorCalls().get(0); assertThat(methodCall.args) .as("Correct constructor arguments are provided") .containsExactly(param); assertThat(methodCall.sig) .as("Correct constructor signature is provided") .hasSize(1) .extracting(new Extractor, Object>() { @Override public Object extract(final Class input) { return input.getName(); } }) .containsExactly(ParameterImpl.class.getName()); } @Test public void should_provide_correct_constructor_param_and_arguments_when_parameters_vararg() throws Exception { assumeClassLoaderMode(); MockGatewaySpy.returnOnMethodCall(SUPPRESS); final Class clazz = loadWithMockClassLoader(SuperClassCallSuperConstructorWithVararg.class.getName()); final Class paramClass = long[].class; final Constructor constructor = clazz.getConstructor(paramClass); long[] params = {1, 5, 6}; constructor.newInstance(new Object[]{ params }); assertThatCorrectConstructorTypeProvided(); final MethodCall methodCall = MockGatewaySpy.constructorCalls().get(0); assertThat(methodCall.args) .as("Constructor arguments have correct size") .hasSize(1); assertThat((long[]) methodCall.args[0]) .as("Correct constructor arguments are provided") .containsExactly(params); assertThat(methodCall.sig) .as("Correct constructor signature is provided") .hasSize(1) .containsExactly(long[].class); } private void assertThatCorrectConstructorTypeProvided() { final MethodCall methodCall = MockGatewaySpy.constructorCalls().get(0); assertThat(methodCall.type.getName()) .as("Correct constructor type is provided") .isEqualTo(SupperClassThrowsException.class.getName()); } private Class reloadClass(final Class originalClazz) throws Exception { assumeThat("Original number of constructors equals to 1", originalClazz.getConstructors().length, equalTo(1)); return loadWithMockClassLoader(originalClazz.getName()); } } ================================================ FILE: powermock-core/src/test/java/org/powermock/core/transformers/ConstructorModifiersMockTransformerTest.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.transformers; import org.junit.Test; import org.junit.runners.Parameterized; import org.powermock.core.test.MockClassLoaderFactory; import org.powermock.core.transformers.javassist.ConstructorsMockTransformer; import powermock.test.support.MainMockTransformerTestSupport.ParentTestClass; import powermock.test.support.MainMockTransformerTestSupport.ParentTestClass.NestedTestClass; import powermock.test.support.MainMockTransformerTestSupport.SupportClasses; import powermock.test.support.MainMockTransformerTestSupport.SupportClasses.MultipleConstructors; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.not; import static org.junit.Assume.assumeThat; public class ConstructorModifiersMockTransformerTest extends AbstractBaseMockTransformerTest { @Parameterized.Parameters(name = "strategy: {0}, transformerType: {2}") public static Iterable data() { Collection data = new ArrayList(); data.addAll(MockTransformerTestHelper.createTransformerTestData(ConstructorsMockTransformer.class)); return data; } public ConstructorModifiersMockTransformerTest(final TransformStrategy strategy, final MockTransformerChain mockTransformerChain, final MockClassLoaderFactory mockClassloaderFactory ) { super(strategy, mockTransformerChain, mockClassloaderFactory); } @Test public void should_make_all_constructor_public_if_strategy_is_classloader() throws Exception { assumeThat(strategy, equalTo(TransformStrategy.CLASSLOADER)); Class clazz = loadWithMockClassLoader(SupportClasses.MultipleConstructors.class.getName()); assertThat(clazz.getConstructors()) .as("All constructor must be public") .hasSize(5) .extracting("modifiers") .contains(Modifier.PUBLIC); } @Test public void should_leave_constructor_unchanged_if_strategy_is_not_classloader() throws Exception { assumeThat(strategy, not(equalTo(TransformStrategy.CLASSLOADER))); Class clazz = SupportClasses.MultipleConstructors.class; Class modifiedClass = loadWithMockClassLoader(SupportClasses.MultipleConstructors.class.getName()); assertThatAllConstructorsHaveSameModifier(clazz, modifiedClass); } @Test public void should_not_change_constructors_of_test_class() throws Exception { assumeClassLoaderMode(); assumeClassLoaderIsByteBuddy(); final Class testClass = MultipleConstructors.class; setTestClassToTransformers(testClass); Class modifiedClass = loadWithMockClassLoader(testClass.getName()); assertThatAllConstructorsHaveSameModifier(testClass, modifiedClass); } @Test public void should_not_change_constructors_of_nested_test_classes() throws Exception { assumeClassLoaderMode(); assumeClassLoaderIsByteBuddy(); setTestClassToTransformers(ParentTestClass.class); final Class originalClazz = NestedTestClass.class; Class modifiedClass = loadWithMockClassLoader(originalClazz.getName()); assertThatAllConstructorsHaveSameModifier(originalClazz, modifiedClass); } private void assertThatAllConstructorsHaveSameModifier(final Class clazz, final Class modifiedClass) { assertThat(modifiedClass.getConstructors()) .as("All constructor has same modifiers") .hasSameSizeAs(clazz.getConstructors()) .usingElementComparator(new Comparator>() { @Override public int compare(final Constructor o1, final Constructor o2) { return o1.getModifiers() == o2.getModifiers() ? o1.getParameterTypes().length - o2.getParameterTypes().length : o1.getModifiers() - o2.getModifiers(); } }) .contains(clazz.getConstructors()); } } ================================================ FILE: powermock-core/src/test/java/org/powermock/core/transformers/InstrumentMockTransformerTest.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.transformers; import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; import javassist.CtField; import javassist.CtMethod; import javassist.NotFoundException; import javassist.bytecode.AccessFlag; import org.junit.Test; import org.junit.runners.Parameterized; import org.powermock.core.test.MockClassLoaderFactory; import org.powermock.core.transformers.javassist.InstrumentMockTransformer; import org.powermock.core.transformers.mock.MockGatewaySpy; import powermock.test.support.MainMockTransformerTestSupport.SuperClassWithObjectMethod; import java.lang.reflect.Field; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.powermock.core.test.ClassLoaderTestHelper.runTestWithNewClassLoader; public class InstrumentMockTransformerTest extends AbstractBaseMockTransformerTest { private static final String SYNTHETIC_FIELD_VALUE = "Synthetic Field Value"; @Parameterized.Parameters(name = "strategy: {0}, transformer: {1}") public static Iterable data() { return MockTransformerTestHelper.createTransformerTestData( InstrumentMockTransformer.class ); } public InstrumentMockTransformerTest(final TransformStrategy strategy, final MockTransformerChain mockTransformerChain, final MockClassLoaderFactory mockClassloaderFactory) { super(strategy, mockTransformerChain, mockClassloaderFactory); } @Test public void should_ignore_call_to_synthetic_field_when_instrument_call_to_method() throws Throwable { final ClassPool classPool = new ClassPool(true); CtClass ctClass = prepareClassesForFieldTests(classPool); mockTransformerChain.transform(wrap(ctClass)); runTestWithNewClassLoader(classPool, ShouldIgnoreCallToSyntheticField.class.getName()); } private CtClass prepareClassesForFieldTests(ClassPool classPool) throws NotFoundException, CannotCompileException { CtClass ctClass = classPool.getCtClass(SuperClassWithObjectMethod.class.getName()); addSyntheticField(classPool, ctClass); insertCallSyntheticField(ctClass); return ctClass; } private void insertCallSyntheticField(CtClass ctClass) throws CannotCompileException { for (CtMethod method : ctClass.getDeclaredMethods()) { method.insertBefore( "String v = " + SYNTH_FIELD + ";" + SYNTH_FIELD + " = \"" + method.getName() + "\";" ); } } private void addSyntheticField(ClassPool classPool, CtClass ctClass) throws CannotCompileException, NotFoundException { CtField field = new CtField(classPool.get(String.class.getName()), SYNTH_FIELD, ctClass); field.setModifiers(AccessFlag.SYNTHETIC); ctClass.addField(field, CtField.Initializer.constant(SYNTHETIC_FIELD_VALUE)); } public static class ShouldIgnoreCallToSyntheticField { public static void main(String[] args) throws Exception { Class clazz = SuperClassWithObjectMethod.class; Object instance = clazz.newInstance(); clazz.getMethod("doSomething", Object.class).invoke(instance, new Object()); assertThat(MockGatewaySpy.getFieldCalls()) .doesNotContain(SYNTH_FIELD); Field field = clazz.getDeclaredField(SYNTH_FIELD); field.setAccessible(true); String fieldValue = (String) field.get(instance); assertThat(fieldValue).isEqualTo("doSomething"); } } } ================================================ FILE: powermock-core/src/test/java/org/powermock/core/transformers/MethodSizeMockTransformerTest.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.transformers; import org.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.junit.Test; import org.junit.runners.Parameterized; import org.powermock.core.classloader.javassist.JavassistMockClassLoader; import org.powermock.core.test.MockClassLoaderFactory; import org.powermock.core.transformers.javassist.JavassistMockTransformerChainFactory; import powermock.test.support.ClassWithLargeMethods; import java.util.ArrayList; import java.util.Collections; import java.util.List; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowable; import static org.junit.Assert.assertNotNull; public class MethodSizeMockTransformerTest extends AbstractBaseMockTransformerTest { @Parameterized.Parameters(name = "strategy: {0}, transformer: {1}") public static Iterable data() { List data = new ArrayList(); for (TransformStrategy strategy : TransformStrategy.values()) { data.add(new Object[]{ strategy, new JavassistMockTransformerChainFactory().createDefaultChain(Collections.emptyList()), new MockClassLoaderFactory(JavassistMockClassLoader.class) }); } return data; } public MethodSizeMockTransformerTest(final TransformStrategy strategy, final MockTransformerChain mockTransformerChain, final MockClassLoaderFactory mockClassloaderFactory) { super(strategy, mockTransformerChain, mockClassloaderFactory); } @Test public void should_load_class_with_method_lower_than_jvm_limit() throws Exception { Class clazz = loadWithMockClassLoader(ClassWithLargeMethods.MethodLowerThanLimit.class.getName()); assertNotNull("Class has been loaded", clazz); // There should be no exception since method was not overridden clazz.getMethod("init").invoke(clazz); } @Test public void should_load_class_and_override_method_greater_than_jvm_limit() throws Exception { final Class clazz = loadWithMockClassLoader(ClassWithLargeMethods.MethodGreaterThanLimit.class.getName()); Throwable throwable = catchThrowable(new ThrowingCallable() { @Override public void call() throws Throwable { clazz.getMethod("init").invoke(clazz); } }); assertThat(throwable) .as("Overridden method should throw exception") .isNotNull(); assertThat(throwable.getCause()) .as("Clause of exception should be IllegalAccessException") .isInstanceOf(IllegalAccessException.class) .hasMessageContaining("Method was too large and after instrumentation exceeded JVM limit"); } } ================================================ FILE: powermock-core/src/test/java/org/powermock/core/transformers/MethodsMockTransformerTest.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.transformers; import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; import javassist.CtMethod; import javassist.CtNewMethod; import javassist.NotFoundException; import javassist.bytecode.AccessFlag; import net.bytebuddy.utility.RandomString; import org.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.junit.Test; import org.junit.runners.Parameterized; import org.powermock.core.MockGateway; import org.powermock.core.test.MockClassLoaderFactory; import org.powermock.core.transformers.javassist.StaticFinalNativeMethodMockTransformer; import org.powermock.core.transformers.mock.MockGatewaySpy; import org.powermock.core.transformers.support.DefaultMockTransformerChain; import org.powermock.reflect.internal.WhiteboxImpl; import powermock.test.support.MainMockTransformerTestSupport.AbstractMethodTestClass; import powermock.test.support.MainMockTransformerTestSupport.ReturnMethodsTestClass; import powermock.test.support.MainMockTransformerTestSupport.SubclassWithBridgeMethod; import powermock.test.support.MainMockTransformerTestSupport.SuperClassWithObjectMethod; import powermock.test.support.MainMockTransformerTestSupport.VoidMethodsTestClass; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.assertj.core.api.Java6Assertions.catchThrowable; import static org.powermock.core.transformers.mock.MockGatewaySpy.ConditionBuilder.registered; import static org.powermock.core.transformers.mock.MockGatewaySpy.methodCalls; public class MethodsMockTransformerTest extends AbstractBaseMockTransformerTest { @Parameterized.Parameters(name = "strategy: {0}, transformer: {1}") public static Iterable data() { Collection data = new ArrayList(); data.addAll(MockTransformerTestHelper.createOneTransformerTestData(MockGatewaySpy.class, StaticFinalNativeMethodMockTransformer.class)); return data; } public MethodsMockTransformerTest(final TransformStrategy strategy, final MockTransformer transformer, final MockClassLoaderFactory mockClassloaderFactory) { super(strategy, DefaultMockTransformerChain.newBuilder().append(transformer).build(), mockClassloaderFactory); } @Test public void should_skip_call_to_void_private_method_if_getaway_return_not_PROCEED() throws Exception { MockGatewaySpy.returnOnMethodCall("voidPrivateMethod", ""); final Class clazz = loadWithMockClassLoader(VoidMethodsTestClass.class.getName()); final Object instance = WhiteboxImpl.newInstance(clazz); WhiteboxImpl.invokeMethod(instance, "voidPrivateMethod", "name"); assertThat(WhiteboxImpl.getInternalState(instance, "lname")) .as("Field name is not set") .isNull(); assertThat(methodCalls()) .is(registered().forMethod("voidPrivateMethod")); } @Test public void should_skip_call_to_void_public_method_if_getaway_return_not_PROCEED() throws Exception { MockGatewaySpy.returnOnMethodCall("voidMethod", ""); final Class clazz = loadWithMockClassLoader(VoidMethodsTestClass.class.getName()); final Object instance = WhiteboxImpl.newInstance(clazz); WhiteboxImpl.invokeMethod(instance, "voidMethod", "name", "field", 100d); assertThat(WhiteboxImpl.getInternalState(instance, "field")) .as("Field name is not set") .isNull(); assertThat(methodCalls()) .is(registered().forMethod("voidMethod")); assertThat(methodCalls()) .isNot(registered().forMethod("voidPrivateMethod")); } @Test public void should_skip_call_to_final_void_public_method_if_getaway_return_not_PROCEED() throws Exception { MockGatewaySpy.returnOnMethodCall("finalVoidMethod", ""); final Class clazz = loadWithMockClassLoader(VoidMethodsTestClass.class.getName()); final Object instance = WhiteboxImpl.newInstance(clazz); WhiteboxImpl.invokeMethod(instance, "finalVoidMethod", "name", "field", 100d); assertThat(WhiteboxImpl.getInternalState(instance, "field")) .as("Field name is not set") .isNull(); assertThat(methodCalls()) .is(registered().forMethod("finalVoidMethod")); } @Test public void should_invoke_real_final_void_public_method_if_getaway_return_PROCEED() throws Exception { MockGatewaySpy.returnOnMethodCall("finalVoidMethod", MockGateway.PROCEED); final Class clazz = loadWithMockClassLoader(VoidMethodsTestClass.class.getName()); final Object instance = WhiteboxImpl.newInstance(clazz); final String fieldValue = RandomString.make(10); WhiteboxImpl.invokeMethod(instance, "finalVoidMethod", "name", fieldValue, 100d); assertThat(WhiteboxImpl.getInternalState(instance, "field")) .as("Field name is not set") .isEqualTo(fieldValue); assertThat(methodCalls()) .is(registered().forMethod("finalVoidMethod")); } @Test public void should_return_value_from_getaway_for_non_void_methods_is_it_is_not_PROCEED() throws Exception { final String expected = "mocked"; MockGatewaySpy.returnOnMethodCall("returnMethod", expected); final Class clazz = loadWithMockClassLoader(ReturnMethodsTestClass.class.getName()); final Object instance = WhiteboxImpl.newInstance(clazz); final Object result = WhiteboxImpl.invokeMethod(instance, "returnMethod", "name", "field", 100d); assertThat(result) .isEqualTo(expected); assertThat(methodCalls()) .is(registered().forMethod("returnMethod")); } @Test public void should_return_value_from_getaway_for_final_non_void_methods_is_it_is_not_PROCEED() throws Exception { final String expected = "mocked"; MockGatewaySpy.returnOnMethodCall("finalReturnMethod", expected); final Class clazz = loadWithMockClassLoader(ReturnMethodsTestClass.class.getName()); final Object instance = WhiteboxImpl.newInstance(clazz); final Object result = WhiteboxImpl.invokeMethod(instance, "finalReturnMethod", "name", "field", 100d); assertThat(result) .isEqualTo(expected); assertThat(methodCalls()) .is(registered().forMethod("finalReturnMethod")); } @Test public void should_return_value_from_getaway_for_final_private_non_void_methods_is_it_is_not_PROCEED() throws Exception { final String expected = "mocked"; MockGatewaySpy.returnOnMethodCall("privateReturnMethod", expected); final Class clazz = loadWithMockClassLoader(ReturnMethodsTestClass.class.getName()); final Object instance = WhiteboxImpl.newInstance(clazz); final Object result = WhiteboxImpl.invokeMethod(instance, "privateReturnMethod", "name"); assertThat(result) .isEqualTo(expected); assertThat(methodCalls()) .is(registered().forMethod("privateReturnMethod")); } @Test public void should_return_real_method_return_value_for_non_void_methods_if_getaway_returns_PROCEED() throws Exception { MockGatewaySpy.returnOnMethodCall("returnMethod", MockGateway.PROCEED); final Class clazz = loadWithMockClassLoader(ReturnMethodsTestClass.class.getName()); final Object instance = WhiteboxImpl.newInstance(clazz); final String name = "name"; final Object result = WhiteboxImpl.invokeMethod(instance, "returnMethod", name, "field", 100d); String expected = name + "(a)"; assertThat(result) .isEqualTo(expected); assertThat(methodCalls()) .is(registered().forMethod("returnMethod")); } @Test public void should_return_real_method_return_value_for_final_non_void_methods_if_getaway_returns_PROCEED() throws Exception { MockGatewaySpy.returnOnMethodCall("finalReturnMethod", MockGateway.PROCEED); final Class clazz = loadWithMockClassLoader(ReturnMethodsTestClass.class.getName()); final Object instance = WhiteboxImpl.newInstance(clazz); final String name = "name"; final Object result = WhiteboxImpl.invokeMethod(instance, "finalReturnMethod", name, "field", 100d); String expected = name + "(a)"; assertThat(result) .isEqualTo(expected); assertThat(methodCalls()) .is(registered().forMethod("finalReturnMethod")); } @Test public void should_ignore_abstract_methods() throws Exception { final Throwable throwable = catchThrowable(new ThrowingCallable() { @Override public void call() throws Throwable { loadWithMockClassLoader(AbstractMethodTestClass.class.getName()); } }); assertThat(throwable) .as("Abstract class is transformed") .isNull(); } @Test public void should_modify_bridge_methods() throws Throwable { final Class clazz = loadWithMockClassLoader(SubclassWithBridgeMethod.class.getName()); final Object instance = WhiteboxImpl.newInstance(clazz); clazz.getMethod("doSomething", String.class).invoke(instance, "value"); assertThat(methodCalls()) .is(registered().forMethod("doSomething")); } @Test public void should_ignore_synthetic_non_bridge_methods() throws Throwable { final ClassPool classPool = new ClassPool(true); CtClass ctClass = prepareClassesForTest(classPool, "return;"); final Class clazz = loadWithMockClassLoader(ctClass); Method method = null; for (Method m : clazz.getDeclaredMethods()) { if (m.getName().equals(SYNTHETIC_METHOD_NAME)) { method = m; break; } } final Object instance = WhiteboxImpl.newInstance(clazz); assertThat(method) .isNotNull(); method.setAccessible(true); method.invoke(instance, ""); assertThat(methodCalls()) .isNot(registered().forMethod(SYNTHETIC_METHOD_NAME)); } @Test public void should_ignore_call_to_synthetic_non_bridge_methods() throws Throwable { final ClassPool classPool = new ClassPool(true); CtClass ctClass = prepareClassesForTest(classPool, "syntheticMethodIsCalled = true;"); final Class clazz = loadWithMockClassLoader(ctClass); final Object instance = WhiteboxImpl.newInstance(clazz); clazz.getMethod("doSomething", Object.class).invoke(instance, new Object()); assertThat(methodCalls()) .isNot(registered().forMethod(SYNTHETIC_METHOD_NAME)); assertThat(WhiteboxImpl.getInternalState(clazz, "syntheticMethodIsCalled")) .isEqualTo(true); } private CtClass prepareClassesForTest(ClassPool classPool, String bodyOfSyntheticMethod) throws NotFoundException, CannotCompileException { CtClass ctClass = classPool.getCtClass(SuperClassWithObjectMethod.class.getName()); addSyntheticMethod(classPool, ctClass, bodyOfSyntheticMethod); return ctClass; } private void addSyntheticMethod(ClassPool classPool, CtClass ctClass, String body) throws NotFoundException, CannotCompileException { CtMethod ctMethod = CtNewMethod.make(AccessFlag.SYNTHETIC, CtClass.voidType, SYNTHETIC_METHOD_NAME, new CtClass[]{classPool.get(String.class.getName())}, null, body, ctClass); ctClass.addMethod(ctMethod); for (CtMethod method : ctClass.getDeclaredMethods()) { if (!method.getName().equals(SYNTHETIC_METHOD_NAME)) { method.insertBefore("$synth(\"" + method.getLongName() + "\");"); } } } } ================================================ FILE: powermock-core/src/test/java/org/powermock/core/transformers/MockTransformerChainTest.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.transformers; import org.junit.Test; import org.powermock.core.transformers.support.DefaultMockTransformerChain; import org.powermock.core.transformers.support.FilterPredicates; import static org.assertj.core.api.Java6Assertions.assertThat; public class MockTransformerChainTest { @Test public void should_call_all_transformer_when_chain_is_called() throws Exception { MockTransformerSpy firstTransformer = new MockTransformerSpy(); MockTransformerSpy secondTransformer = new MockTransformerSpy(); MockTransformerChain transformerChain = DefaultMockTransformerChain.newBuilder() .append(firstTransformer) .append(secondTransformer) .build(); transformerChain.transform(new DummyClassWrapper()); firstTransformer.assertIsCalled(); secondTransformer.assertIsCalled(); } @Test public void should_return_collection_of_mock_transformer_which_fit_predicate() { final FitPredicateMockTransformer expectedTransformer = new FitPredicateMockTransformer(); final MockTransformerChain transformerChain = DefaultMockTransformerChain.newBuilder() .append(new MockTransformerSpy()) .append(new MockTransformerSpy()) .append(expectedTransformer) .build(); assertThat(transformerChain.filter(FilterPredicates.isInstanceOf(TestClassAwareTransformer.class))) .as("Transformer is found.") .containsExactly(expectedTransformer); } private static class MockTransformerSpy implements MockTransformer { private boolean classTransformed = false; @Override public ClassWrapper transform(final ClassWrapper clazz) throws Exception { classTransformed = true; return clazz; } private void assertIsCalled(){ assertThat(classTransformed).as("Transformer has not been called").isTrue(); } } private static class DummyClassWrapper implements ClassWrapper { @Override public boolean isInterface() { return false; } @Override public Object unwrap() { return null; } @Override public ClassWrapper wrap(final Object original) { return null; } } private static class FitPredicateMockTransformer implements MockTransformer, TestClassAwareTransformer { @Override public ClassWrapper transform(final ClassWrapper clazz) { return null; } @Override public void setTestClass(final Class testClass) { } } } ================================================ FILE: powermock-core/src/test/java/org/powermock/core/transformers/MockTransformerTestHelper.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.transformers; import org.powermock.core.MockGateway; import org.powermock.core.classloader.javassist.JavassistMockClassLoader; import org.powermock.core.test.MockClassLoaderFactory; import org.powermock.core.transformers.javassist.AbstractJavaAssistMockTransformer; import org.powermock.core.transformers.support.DefaultMockTransformerChain; import org.powermock.reflect.internal.WhiteboxImpl; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collection; import java.util.List; class MockTransformerTestHelper { static Collection createTransformerTestData(final Class... transformerClass) { return createTransformerTestDataWithMockGateway(MockGateway.class, transformerClass); } static Collection createTransformerTestDataWithMockGateway(final Class mockGateway, final Class... transformerClass) { List data = new ArrayList(); for (TransformStrategy strategy : TransformStrategy.values()) { List transformerChains = createTransformers(mockGateway, strategy, transformerClass); for (MockTransformerChain mockTransformer : transformerChains) { data.add(new Object[]{ strategy, mockTransformer, createClassLoaderFactory(transformerClass[0]) }); } } return data; } static Collection createOneTransformerTestData(final Class transformerClass) { return createOneTransformerTestData(MockGateway.class, transformerClass); } static Collection createOneTransformerTestData(final Class mockGateway, final Class transformerClass) { List data = new ArrayList(); for (TransformStrategy strategy : TransformStrategy.values()) { MockTransformer transformer = getInstance(mockGateway, strategy, transformerClass); data.add(new Object[]{ strategy, transformer, createClassLoaderFactory(transformerClass) }); } return data; } private static MockClassLoaderFactory createClassLoaderFactory(final Class transformerClass) { if (AbstractJavaAssistMockTransformer.class.isAssignableFrom(transformerClass)){ return new MockClassLoaderFactory(JavassistMockClassLoader.class); } throw new UnsupportedOperationException(); } private static List createTransformers(final Class mockGateway, final TransformStrategy strategy, final Class... classes) { List transformers = new ArrayList(); for (Class transformerClass : classes) { MockTransformer transformer = getInstance(mockGateway, strategy, transformerClass); transformers.add(createChainFrom(transformer)); } return transformers; } private static MockTransformer getInstance(final Class mockGateway, final TransformStrategy strategy, final Class transformerClass) { try { Constructor constructor = transformerClass.getConstructor(TransformStrategy.class); Object instance = constructor.newInstance(strategy); Field mockGetawayClassField = null; try { mockGetawayClassField = WhiteboxImpl.getField(transformerClass, "mockGetawayClass"); } catch (Exception e) { // do nothing } if (mockGetawayClassField != null){ mockGetawayClassField.setAccessible(true); mockGetawayClassField.set(instance, mockGateway); } return (MockTransformer) instance; } catch (Exception e) { throw new RuntimeException("Cannot create an instance of transformer.", e); } } private static MockTransformerChain createChainFrom(final MockTransformer transformer) { return DefaultMockTransformerChain.newBuilder() .append(transformer) .build(); } } ================================================ FILE: powermock-core/src/test/java/org/powermock/core/transformers/NativeMethodsMockTransformerTest.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.transformers; import net.bytebuddy.utility.RandomString; import org.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.junit.Test; import org.junit.runners.Parameterized; import org.powermock.core.test.MockClassLoaderFactory; import org.powermock.core.transformers.javassist.StaticFinalNativeMethodMockTransformer; import org.powermock.core.transformers.mock.MockGatewaySpy; import org.powermock.core.transformers.support.DefaultMockTransformerChain; import org.powermock.reflect.internal.WhiteboxImpl; import powermock.test.support.MainMockTransformerTestSupport.ChildOfNativeMethodsTestClass; import powermock.test.support.MainMockTransformerTestSupport.ClassWithoutHashCode; import powermock.test.support.MainMockTransformerTestSupport.NativeMethodsTestClass; import java.util.ArrayList; import java.util.Collection; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.assertj.core.api.Java6Assertions.assertThatThrownBy; import static org.powermock.core.transformers.mock.MockGatewaySpy.ConditionBuilder.registered; import static org.powermock.core.transformers.mock.MockGatewaySpy.methodCalls; public class NativeMethodsMockTransformerTest extends AbstractBaseMockTransformerTest { @Parameterized.Parameters(name = "strategy: {0}, transformer: {1}") public static Iterable data() { Collection data = new ArrayList(); data.addAll(MockTransformerTestHelper.createOneTransformerTestData(MockGatewaySpy.class, StaticFinalNativeMethodMockTransformer.class)); return data; } public NativeMethodsMockTransformerTest(final TransformStrategy strategy, final MockTransformer transformer, final MockClassLoaderFactory mockClassloaderFactory) { super(strategy, DefaultMockTransformerChain.newBuilder().append(transformer).build(), mockClassloaderFactory); } @Test public void should_return_value_from_getaway_for_native_instance_methods_is_it_is_not_PROCEED() throws Exception { assumeClassLoaderMode(); final String expected = RandomString.make(10); MockGatewaySpy.returnOnMethodCall("nativeReturnMethod", expected); final Class clazz = loadWithMockClassLoader(NativeMethodsTestClass.class.getName()); final Object instance = WhiteboxImpl.newInstance(clazz); final String name = "name"; final Object result = WhiteboxImpl.invokeMethod(instance, "nativeReturnMethod", name); assertThat(result) .isEqualTo(expected); assertThat(methodCalls()) .is(registered().forMethod("nativeReturnMethod")); } @Test public void should_return_value_from_getaway_for_native_static_methods_if_it_is_not_PROCEED() throws Exception { assumeClassLoaderMode(); final String expected = RandomString.make(10); MockGatewaySpy.returnOnMethodCall("nativeStaticReturnMethod", expected); final Class clazz = loadWithMockClassLoader(NativeMethodsTestClass.class.getName()); final String name = "name"; final Object result = WhiteboxImpl.invokeMethod(clazz, "nativeStaticReturnMethod", name); assertThat(result) .isEqualTo(expected); assertThat(methodCalls()) .is(registered().forMethod("nativeStaticReturnMethod")); } @Test public void should_throw_UnsupportedOperationException_for_native_instance_if_it_is_PROCEED() throws Exception { assumeClassLoaderMode(); final Class clazz = loadWithMockClassLoader(NativeMethodsTestClass.class.getName()); final String name = "name"; assertThatThrownBy(new ThrowingCallable() { @Override public void call() throws Throwable { final Object instance = WhiteboxImpl.newInstance(clazz); WhiteboxImpl.invokeMethod(instance, "nativeReturnMethod", name); } }) .isExactlyInstanceOf(UnsupportedOperationException.class); } @Test public void should_throw_UnsupportedOperationException_for_native_static_if_it_is_PROCEED() throws Exception { assumeClassLoaderMode(); final Class clazz = loadWithMockClassLoader(NativeMethodsTestClass.class.getName()); final String name = "name"; assertThatThrownBy(new ThrowingCallable() { @Override public void call() throws Throwable { WhiteboxImpl.invokeMethod(clazz, "nativeStaticReturnMethod", name); } }) .isExactlyInstanceOf(UnsupportedOperationException.class); } @Test public void should_not_handle_hashCode_form_Object() throws Exception { assumeClassLoaderMode(); final Class clazz = loadWithMockClassLoader(ClassWithoutHashCode.class.getName()); final Object instance = WhiteboxImpl.newInstance(clazz); final Object result = WhiteboxImpl.invokeMethod(instance, "hashCode"); assertThat(result) .isEqualTo(System.identityHashCode(instance)); } @Test public void should_throw_UnsupportedOperationException_for_native_method_of_parent_instance_if_it_is_PROCEED() throws Exception { assumeClassLoaderMode(); final Class clazz = loadWithMockClassLoader(ChildOfNativeMethodsTestClass.class.getName()); final String name = "name"; assertThatThrownBy(new ThrowingCallable() { @Override public void call() throws Throwable { final Object instance = WhiteboxImpl.newInstance(clazz); WhiteboxImpl.invokeMethod(instance, "nativeReturnMethod", name); } }) .isExactlyInstanceOf(UnsupportedOperationException.class); } } ================================================ FILE: powermock-core/src/test/java/org/powermock/core/transformers/StaticFinalFieldsMockTransformerTest.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.transformers; import org.junit.Test; import org.junit.runners.Parameterized; import org.powermock.core.test.MockClassLoaderFactory; import org.powermock.core.transformers.javassist.StaticFinalFieldsMockTransformer; import org.powermock.reflect.internal.WhiteboxImpl; import powermock.test.support.MainMockTransformerTestSupport.SupportClasses; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collection; import static java.lang.reflect.Modifier.isFinal; import static java.lang.reflect.Modifier.isTransient; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.not; import static org.junit.Assume.assumeThat; public class StaticFinalFieldsMockTransformerTest extends AbstractBaseMockTransformerTest { @Parameterized.Parameters(name = "strategy: {0}, transformerType: {2}") public static Iterable data() { Collection data = new ArrayList(); data.addAll(MockTransformerTestHelper.createTransformerTestData(StaticFinalFieldsMockTransformer.class)); return data; } public StaticFinalFieldsMockTransformerTest(final TransformStrategy strategy, final MockTransformerChain mockTransformerChain, final MockClassLoaderFactory mockClassloaderFactory) { super(strategy, mockTransformerChain, mockClassloaderFactory); } @Test public void should_remove_final_modifier_from_static_final_field_if_strategy_not_redefine() throws Exception { assumeThat(strategy, not(equalTo(TransformStrategy.INST_REDEFINE))); Class clazz = loadWithMockClassLoader(SupportClasses.class.getName()); assertThatFieldIsNotFinal(clazz, "finalStaticField"); assertThatFieldIsFinal(clazz, "finalField"); } @Test public void should_not_remove_final_modifier_from_static_final_field_if_strategy_redefine() throws Exception { assumeThat(strategy, equalTo(TransformStrategy.INST_REDEFINE)); Class clazz = loadWithMockClassLoader(SupportClasses.class.getName()); assertThatFieldIsFinal(clazz, "finalStaticField"); assertThatFieldIsFinal(clazz, "finalField"); } @Test public void should_remove_only_final_modifier_but_keep_transient() throws Exception { assumeThat(strategy, not(equalTo(TransformStrategy.INST_REDEFINE))); Class clazz = loadWithMockClassLoader(SupportClasses.class.getName()); Field finalTransientStaticField = WhiteboxImpl.getField(clazz, "finalStaticTransientField"); assertThat(isFinal(finalTransientStaticField.getModifiers())).isFalse(); assertThat(isTransient(finalTransientStaticField.getModifiers())).isTrue(); } private void assertThatFieldIsFinal(final Class clazz, final String fieldName) { Field field = WhiteboxImpl.getField(clazz, fieldName); assertThat(field) .as("Final field is exist.") .isNotNull(); assertThat(isFinal(field.getModifiers())) .as("Field is final.") .isTrue(); } private void assertThatFieldIsNotFinal(final Class clazz, final String fieldName) { Field field = WhiteboxImpl.getField(clazz, fieldName); assertThat(field) .as("Final field is exist.") .isNotNull(); assertThat(isFinal(field.getModifiers())) .as("Field is not final.") .isFalse(); } } ================================================ FILE: powermock-core/src/test/java/org/powermock/core/transformers/StaticMethodsMockTransformerTest.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.transformers; import org.junit.Test; import org.junit.runners.Parameterized; import org.powermock.core.MockGateway; import org.powermock.core.test.MockClassLoaderFactory; import org.powermock.core.transformers.javassist.StaticFinalNativeMethodMockTransformer; import org.powermock.core.transformers.mock.MockGatewaySpy; import org.powermock.core.transformers.support.DefaultMockTransformerChain; import org.powermock.reflect.internal.WhiteboxImpl; import powermock.test.support.MainMockTransformerTestSupport.StaticVoidMethodsTestClass; import java.util.ArrayList; import java.util.Collection; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.powermock.core.transformers.mock.MockGatewaySpy.ConditionBuilder.registered; import static org.powermock.core.transformers.mock.MockGatewaySpy.methodCalls; public class StaticMethodsMockTransformerTest extends AbstractBaseMockTransformerTest { @Parameterized.Parameters(name = "strategy: {0}, transformer: {1}") public static Iterable data() { Collection data = new ArrayList(); data.addAll(MockTransformerTestHelper.createOneTransformerTestData(MockGatewaySpy.class, StaticFinalNativeMethodMockTransformer.class)); return data; } public StaticMethodsMockTransformerTest(final TransformStrategy strategy, final MockTransformer transformer, final MockClassLoaderFactory mockClassloaderFactory) { super(strategy, DefaultMockTransformerChain.newBuilder().append(transformer).build(), mockClassloaderFactory); } @Test public void should_skip_call_to_void_static_public_method_if_getaway_return_not_PROCEED() throws Exception { MockGatewaySpy.returnOnMethodCall("voidMethod", ""); final Class clazz = loadWithMockClassLoader(StaticVoidMethodsTestClass.class.getName()); WhiteboxImpl.invokeMethod(clazz, "voidMethod", "name", "field", 100d); assertThat(WhiteboxImpl.getInternalState(clazz, "field")) .as("Field name is not set") .isNull(); assertThat(methodCalls()) .is(registered().forMethod("voidMethod")); } @Test public void should_continue_executing_void_static_public_method_if_getaway_return_PROCEED() throws Exception { MockGatewaySpy.returnOnMethodCall("voidMethod", MockGateway.PROCEED); final Class clazz = loadWithMockClassLoader(StaticVoidMethodsTestClass.class.getName()); final String expectedFieldValue = "field"; WhiteboxImpl.invokeMethod(clazz, "voidMethod", "name", expectedFieldValue, 100d); assertThat(WhiteboxImpl.getInternalState(clazz, "field")) .as("Field name is not set") .isEqualTo(expectedFieldValue); assertThat(methodCalls()) .is(registered().forMethod("voidMethod")); } } ================================================ FILE: powermock-core/src/test/java/org/powermock/core/transformers/SuppressStaticInitializerMockTransformerTest.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.core.transformers; import org.junit.Before; import org.junit.Test; import org.junit.runners.Parameterized; import org.powermock.core.MockRepository; import org.powermock.core.test.MockClassLoaderFactory; import org.powermock.core.transformers.javassist.SuppressStaticInitializerMockTransformer; import org.powermock.reflect.Whitebox; import powermock.test.support.MainMockTransformerTestSupport.StaticInitialization; import java.util.ArrayList; import java.util.Collection; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.not; import static org.junit.Assume.assumeThat; public class SuppressStaticInitializerMockTransformerTest extends AbstractBaseMockTransformerTest { @Parameterized.Parameters(name = "strategy: {0}, transformerType: {2}") public static Iterable data() { Collection data = new ArrayList(); data.addAll(MockTransformerTestHelper.createTransformerTestData(SuppressStaticInitializerMockTransformer.class)); return data; } public SuppressStaticInitializerMockTransformerTest( final TransformStrategy strategy, final MockTransformerChain mockTransformerChain, final MockClassLoaderFactory mockClassloaderFactory ) { super(strategy, mockTransformerChain, mockClassloaderFactory); } @Before public void setUp() throws Exception { super.setUp(); MockRepository.removeSuppressStaticInitializer(StaticInitialization.class.getName()); } @Test public void should_suppress_static_initialization_if_class_is_added_to_mock_repository() throws Exception { assumeThat(strategy, equalTo(TransformStrategy.CLASSLOADER)); String className = StaticInitialization.class.getName(); MockRepository.addSuppressStaticInitializer(className); Class clazz = loadWithMockClassLoader(className); Object value = Whitebox.getInternalState(clazz, "value"); assertThat(value) .as("Value not initialized") .isNull(); } @Test public void should_not_suppress_static_initialization_if_class_is_not_added_to_mock_repository() throws Exception { assumeThat(strategy, equalTo(TransformStrategy.CLASSLOADER)); Class clazz = loadWithMockClassLoader(StaticInitialization.class.getName()); Object value = Whitebox.getInternalState(clazz, "value"); assertThat(value) .as("Value initialized") .isNotNull(); } @Test public void should_not_suppress_static_initialization_if_class_is_added_to_mock_repository_but_strategy_not_classloader() throws Exception { assumeThat(strategy, not(equalTo(TransformStrategy.CLASSLOADER))); Class clazz = loadWithMockClassLoader(StaticInitialization.class.getName()); Object value = Whitebox.getInternalState(clazz, "value"); assertThat(value) .as("Value initialized") .isNotNull(); } } ================================================ FILE: powermock-core/src/test/java/org/powermock/core/transformers/TestClassTransformerTest.java ================================================ /* * Copyright 2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.core.transformers; import org.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.powermock.configuration.GlobalConfiguration; import org.powermock.core.IndicateReloadClass; import org.powermock.core.classloader.ByteCodeFramework; import org.powermock.core.classloader.MockClassLoader; import org.powermock.core.classloader.MockClassLoaderBuilder; import org.powermock.reflect.internal.WhiteboxImpl; import powermock.test.support.MainMockTransformerTestSupport.SupportClasses; import powermock.test.support.TestWithTwoTestMethods; import powermock.test.support.TestWithTwoTestMethods.NestedTestWithTwoTestMethods; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.List; import static java.lang.reflect.Modifier.isPrivate; import static java.lang.reflect.Modifier.isProtected; import static java.lang.reflect.Modifier.isPublic; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Java6Assertions.assertThatThrownBy; import static org.junit.Assert.assertEquals; import static org.junit.Assume.assumeTrue; @RunWith(Parameterized.class) public class TestClassTransformerTest { @Parameterized.Parameter public ByteCodeFramework bytecodeFramework; @Parameterized.Parameter(1) public MockClassLoaderCase classLoaderCase; @Parameterized.Parameters(name = "{0}-{1}") public static List values() { final List values = new ArrayList(); for (ByteCodeFramework byteCodeFramework : ByteCodeFramework.values()) { for (MockClassLoaderCase eachFactoryAlternative : MockClassLoaderCase.values()) { values.add(new Object[]{byteCodeFramework, eachFactoryAlternative}); } } return values; } @Before public void setUp() { GlobalConfiguration.powerMockConfiguration().setByteCodeFramework(bytecodeFramework); } @Test public void should_make_defer_constructor_non_public_for_inner_classes() throws Exception { MockClassLoader mockClassLoader = classLoaderCase.createMockClassLoaderThatPrepare( SupportClasses.SubClass.class, bytecodeFramework, Collections.emptyList()); final Class clazz = Class.forName(SupportClasses.SubClass.class.getName(), true, mockClassLoader); assertThat(SupportClasses.SubClass.class.getConstructors()) .as("Original number of constructors") .hasSize(1); assertThatThrownBy( new ThrowingCallable() { @Override public void call() throws Throwable { clazz.getConstructor(IndicateReloadClass.class); } } ).withFailMessage("A public defer-constructor still presents.") .isExactlyInstanceOf(NoSuchMethodException.class); assertThat(clazz.getConstructors()) .as("Number of (public) constructors in modified class") .hasSize(1); assumeTrue(bytecodeFramework == ByteCodeFramework.Javassist); assertThat(clazz.getDeclaredConstructor(IndicateReloadClass.class)) .as("But there should still be a non-public defer constructor!") .isNotNull(); } @Test public void should_restore_original_constructors_accesses() throws Exception { MockClassLoader mockClassLoader = classLoaderCase.createMockClassLoaderThatPrepare( SupportClasses.MultipleConstructors.class, bytecodeFramework, Collections.emptyList()); final Class clazz = Class.forName( SupportClasses.MultipleConstructors.class.getName(), true, mockClassLoader ); for (Constructor originalConstructor : SupportClasses.MultipleConstructors.class.getDeclaredConstructors()) { Class[] paramTypes = originalConstructor.getParameterTypes(); int originalModifiers = originalConstructor.getModifiers(); int newModifiers = clazz.getDeclaredConstructor(paramTypes).getModifiers(); String constructorName = 0 == paramTypes.length ? "Default constructor " : paramTypes[0].getSimpleName() + " constructor "; assertEquals(constructorName + "is public?", isPublic(originalModifiers), isPublic(newModifiers)); assertEquals(constructorName + "is protected?", isProtected(originalModifiers), isProtected(newModifiers)); assertEquals(constructorName + "is private?", isPrivate(originalModifiers), isPrivate(newModifiers)); } } @Test public void should_remove_test_annotation_from_all_method() throws ClassNotFoundException { final String methodName = "test_method_2"; final MockClassLoader mockClassLoader = classLoaderCase.createMockClassLoaderThatPrepare( TestWithTwoTestMethods.class, bytecodeFramework, Collections.singletonList(WhiteboxImpl.findMethod(TestWithTwoTestMethods.class, methodName)) ); final Class clazz = Class.forName( TestWithTwoTestMethods.class.getName(), true, mockClassLoader ); final Method modifiedMethod = WhiteboxImpl.findMethod(clazz, methodName); assertThat(modifiedMethod.isAnnotationPresent(Test.class)) .as("Test annotation has been removed.") .isFalse(); } @Test public void should_not_remove_test_annotation_from_all_method_if_nested_class_in_test_class() throws ClassNotFoundException { final String methodName = "test_nested_method_2"; final MockClassLoader mockClassLoader = classLoaderCase.createMockClassLoaderThatPrepare( TestWithTwoTestMethods.class, bytecodeFramework, Collections.singletonList(WhiteboxImpl.findMethod(NestedTestWithTwoTestMethods.class, methodName)) ); final Class clazz = Class.forName( NestedTestWithTwoTestMethods.class.getName(), true, mockClassLoader ); final Method modifiedMethod = WhiteboxImpl.findMethod(clazz, methodName); assertThat(modifiedMethod.isAnnotationPresent(Test.class)) .as("Test annotation has been removed.") .isTrue(); } enum MockClassLoaderCase { WHEN_PREPARED_CLASS_IS_TESTCLASS { @Override Class chooseTestClass(Class prepare4test) { return prepare4test; } @Override String[] preparations(Class prepare4test) { return new String[]{MockClassLoader.MODIFY_ALL_CLASSES}; } }, WHEN_ENCLOSING_CLASS_IS_TESTCLASS { @Override Class chooseTestClass(Class prepare4test) { final Class declaringClass = prepare4test.getDeclaringClass(); if (declaringClass == null) { return prepare4test; } else { return declaringClass; } } @Override String[] preparations(Class prepare4test) { return new String[]{prepare4test.getName()}; } }; abstract Class chooseTestClass(Class prepare4test); abstract String[] preparations(Class prepare4test); MockClassLoader createMockClassLoaderThatPrepare(Class prepare4test, final ByteCodeFramework bytecodeFramework, final List methodsToRemoveAnnotations) { final Class testClass = chooseTestClass(prepare4test); final MockTransformer testClassTransformer = TestClassTransformerBuilder .forTestClass(testClass) .removesTestMethodAnnotation(Test.class) .fromMethods(new ArrayList(methodsToRemoveAnnotations)); return MockClassLoaderBuilder.create(bytecodeFramework) .forTestClass(testClass) .addExtraMockTransformers(testClassTransformer) .addClassesToModify(preparations(prepare4test)) .build(); } } } ================================================ FILE: powermock-core/src/test/java/org/powermock/core/transformers/javassist/TestPrimitives.java ================================================ /* * Copyright 2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.core.transformers.javassist; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import javassist.CtClass; import javassist.CtPrimitiveType; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.powermock.core.transformers.javassist.support.Primitives; @RunWith(Parameterized.class) public class TestPrimitives { final CtPrimitiveType ctType; public TestPrimitives(CtPrimitiveType ctType) { this.ctType = ctType; } @Parameterized.Parameters(name = "{0}") public static List values() throws Exception { List valuesList = new ArrayList(); for (Field f : CtClass.class.getFields()) { if (CtClass.class.isAssignableFrom(f.getType())) { valuesList.add(new Object[] {f.get(null)}); } } return valuesList; } @Test public void testMapping() { Class mapping = Primitives.getClassFor(ctType); Assert.assertEquals("Mapping for ctType=" + ctType.getName(), ctType.getSimpleName(), mapping.getSimpleName()); } } ================================================ FILE: powermock-core/src/test/java/org/powermock/core/transformers/mock/MockGatewaySpy.java ================================================ package org.powermock.core.transformers.mock; import org.assertj.core.api.Condition; import org.assertj.core.description.Description; import org.assertj.core.description.TextDescription; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import static org.powermock.core.MockGateway.SUPPRESS; public class MockGatewaySpy { private static final String ANY = "$*$"; private static Map returnOnMethodCall = new HashMap(); private final static List methodCalls = new LinkedList(); private final static List constructorCalls = new LinkedList(); private final static List fieldCalls = new LinkedList(); public static Object constructorCall(Class type, Object[] args, Class[] sig) { final MethodCall methodCall = new MethodCall(); methodCall.type = type; methodCall.args = args; methodCall.sig = sig; constructorCalls.add(methodCall); return getResult(""); } public static boolean suppressConstructorCall(Class type, Object[] args, Class[] sig) { return constructorCall(type, args, sig) == SUPPRESS; } public static Object methodCall(Object instance, String methodName, Object[] args, Class[] sig, String returnTypeAsString) throws Throwable { return doMethodCall(instance.getClass(), methodName, args, sig, returnTypeAsString); } public static Object methodCall(Class type, String methodName, Object[] args, Class[] sig, String returnTypeAsString) throws Throwable { return doMethodCall(type, methodName, args, sig, returnTypeAsString); } private static Object doMethodCall(final Class type, final String methodName, final Object[] args, final Class[] sig, final String returnTypeAsString) { final MethodCall methodCall = new MethodCall(); methodCall.type = type; methodCall.methodName = methodName; methodCall.args = args; methodCall.sig = sig; methodCall.returnTypeAsString = returnTypeAsString; registerMethodCall(methodCall); return getResult(methodName); } private static Object getResult(final String methodName) { Object result = returnOnMethodCall.get(methodName); if (result == null) { result = returnOnMethodCall.get(ANY); } return result; } private static void registerMethodCall(MethodCall methodName) { methodCalls.add(methodName); } private static void registerFieldCall(String fieldName) { fieldCalls.add(fieldName); } public static List methodCalls() { return methodCalls; } public static List getFieldCalls() { return fieldCalls; } public static List constructorCalls() { return constructorCalls; } public static void returnOnMethodCall(final Object expected) { MockGatewaySpy.returnOnMethodCall.put(ANY, expected); } public static void returnOnMethodCall(final String methodName, final Object expected) { MockGatewaySpy.returnOnMethodCall.put(methodName, expected); } public static void clear() { methodCalls.clear(); fieldCalls.clear(); constructorCalls.clear(); returnOnMethodCall.clear(); } public static class MethodCall { public Object[] args; public Class[] sig; public String returnTypeAsString; public Class type; public String methodName; @Override public String toString() { final StringBuffer sb = new StringBuffer("MethodCall{\n"); sb.append("args=").append(args == null ? "null" : Arrays.asList(args).toString()); sb.append("\n, sig=").append(sig == null ? "null" : Arrays.asList(sig).toString()); sb.append("\n, returnTypeAsString='").append(returnTypeAsString).append('\''); sb.append("\n, type=").append(type); sb.append("\n, methodName='").append(methodName).append('\''); sb.append("}\n"); return sb.toString(); } } public static class ConditionBuilder { public static ConditionBuilder registered() { return new ConditionBuilder(); } public Condition> forMethod(final String methodName) { return new Condition>() { @Override public boolean matches(final List value) { for (MethodCall methodCall : value) { if (methodName.equals(methodCall.methodName)) { return true; } } return false; } @Override public Description description() { return new TextDescription("The method `%s` has not been called.", methodName); } }; } } } ================================================ FILE: powermock-core/src/test/java/org/powermock/tests/utils/impl/PowerMockIgnorePackagesExtractorImplTest.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.tests.utils.impl; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.powermock.configuration.Configuration; import org.powermock.configuration.ConfigurationFactory; import org.powermock.configuration.GlobalConfiguration; import org.powermock.configuration.PowerMockConfiguration; import org.powermock.core.classloader.annotations.PowerMockIgnore; import static org.assertj.core.api.Java6Assertions.assertThat; @SuppressWarnings("unchecked") public class PowerMockIgnorePackagesExtractorImplTest { private PowerMockIgnorePackagesExtractorImpl objectUnderTest; @Before public void setUp() throws Exception { GlobalConfiguration.clear(); objectUnderTest = new PowerMockIgnorePackagesExtractorImpl(); } @After public void tearDown() throws Exception { GlobalConfiguration.clear(); } @Test public void should_find_ignore_packages_in_the_whole_class_hierarchy() throws Exception { final String[] values = {"ignore0", "ignore1", "ignore2", "ignore3"}; final String[] expectedValues = calculateExpectedValues(values); final String[] packagesToIgnore = objectUnderTest.getPackagesToIgnore(IgnoreAnnotatedDemoClass.class); assertThat(packagesToIgnore) .as("Packages added to ignore") .hasSize(expectedValues.length) .containsExactlyInAnyOrder(expectedValues); } @Test public void should_scan_interfaces_when_search_package_to_ignore() { final String[] values = {"ignore4", "ignore5", "ignore6"}; String[] expected = calculateExpectedValues(values); final String[] packagesToIgnore = objectUnderTest.getPackagesToIgnore(IgnoreAnnotationFromInterfaces.class); assertThat(packagesToIgnore) .as("Packages from interfaces added to ignore") .hasSize(expected.length) .contains(expected); } @Test public void should_include_global_powermock_ignore_to_list_of_package_to_ignore() { final String[] globalIgnore = {"org.somepacakge.*", "org.otherpackage.Class"}; GlobalConfiguration.setConfigurationFactory(new ConfigurationFactory() { @Override public > T create(final Class configurationType) { PowerMockConfiguration powerMockConfiguration = new PowerMockConfiguration(); powerMockConfiguration.setGlobalIgnore(globalIgnore); return (T) powerMockConfiguration; } }); String[] packagesToIgnore = objectUnderTest.getPackagesToIgnore(ClassWithoutAnnotation.class); assertThat(packagesToIgnore) .as("Packages from configuration is added to ignore") .hasSize(2) .containsOnly(globalIgnore); } @Test public void should_not_include_global_powermock_ignore_when_annotation_use_global_ignore_false() { final String[] globalIgnore = {"org.somepacakge.*", "org.otherpackage.Class"}; GlobalConfiguration.setConfigurationFactory(new ConfigurationFactory() { @Override public > T create(final Class configurationType) { PowerMockConfiguration powerMockConfiguration = new PowerMockConfiguration(); powerMockConfiguration.setGlobalIgnore(globalIgnore); return (T) powerMockConfiguration; } }); String[] packagesToIgnore = objectUnderTest.getPackagesToIgnore(ClassWithAnnotationUseFalse.class); assertThat(packagesToIgnore) .as("Packages from global ignore is not added") .hasSize(2) .containsOnly("ignore6", "ignore5"); } @Test public void should_not_include_global_powermock_ignore_when_annotation_use_global_ignore_false_on_parent_class() { final String[] globalIgnore = {"org.somepacakge.*", "org.otherpackage.Class"}; GlobalConfiguration.setConfigurationFactory(new ConfigurationFactory() { @Override public > T create(final Class configurationType) { PowerMockConfiguration powerMockConfiguration = new PowerMockConfiguration(); powerMockConfiguration.setGlobalIgnore(globalIgnore); return (T) powerMockConfiguration; } }); String[] packagesToIgnore = objectUnderTest.getPackagesToIgnore(IgnoreAnnotatedWithGlobalIgnoreParent.class); assertThat(packagesToIgnore) .as("Packages from global ignore is not added") .hasSize(4) .containsOnly("ignore0", "ignore1", "ignore6", "ignore5"); } private String[] calculateExpectedValues(final String[] values) { final PowerMockConfiguration configuration = GlobalConfiguration.powerMockConfiguration(); final int length = configuration.getGlobalIgnore().length; final int expectedLength = length + values.length; String[] expected = new String[expectedLength]; System.arraycopy(configuration.getGlobalIgnore(), 0, expected, 0, length); System.arraycopy(values, 0, expected, length, values.length); return expected; } private static class ClassWithoutAnnotation { } @PowerMockIgnore({"ignore0", "ignore1"}) private class IgnoreAnnotatedDemoClass extends IgnoreAnnotatedDemoClassParent { } @PowerMockIgnore("ignore2") private class IgnoreAnnotatedDemoClassParent extends IgnoreAnnotatedDemoClassGrandParent { } @PowerMockIgnore("ignore3") private class IgnoreAnnotatedDemoClassGrandParent { } private static class IgnoreAnnotationFromInterfaces implements IgnoreAnnotatedDemoInterfaceParent1, IgnoreAnnotatedDemoInterfaceParent2 { } @PowerMockIgnore("ignore5") private interface IgnoreAnnotatedDemoInterfaceGrandParent { } @PowerMockIgnore("ignore4") private interface IgnoreAnnotatedDemoInterfaceParent1 extends IgnoreAnnotatedDemoInterfaceGrandParent { } @PowerMockIgnore("ignore6") private interface IgnoreAnnotatedDemoInterfaceParent2 extends IgnoreAnnotatedDemoInterfaceGrandParent { } @PowerMockIgnore(value = "ignore6", globalIgnore = false) private class ClassWithAnnotationUseFalse implements IgnoreAnnotatedDemoInterfaceGrandParent { } @PowerMockIgnore({"ignore0", "ignore1"}) private class IgnoreAnnotatedWithGlobalIgnoreParent extends ClassWithAnnotationUseFalse { } } ================================================ FILE: powermock-core/src/test/java/org/powermock/tests/utils/impl/PrepareForTestExtractorImplTest.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.tests.utils.impl; import org.junit.Test; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.reflect.Whitebox; import java.io.Serializable; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * Unit tests for the {@link PrepareForTestExtractorImpl} class. * */ public class PrepareForTestExtractorImplTest { /** * Makes sure that issue 81 is * solved. */ @Test public void assertThatInterfacesWorks() throws Exception { final PrepareForTestExtractorImpl tested = new PrepareForTestExtractorImpl(); final Set hashSet = new HashSet(); Whitebox.invokeMethod(tested, "addClassHierarchy", hashSet, Serializable.class); assertEquals(1, hashSet.size()); assertEquals(Serializable.class.getName(), hashSet.iterator().next()); } /** * Makes sure that issue 111 is * solved. */ @Test public void shouldFindClassesToPrepareForTestInTheWholeClassHierarchy() throws Exception { final PrepareForTestExtractorImpl tested = new PrepareForTestExtractorImpl(); final String[] classesToPrepare = tested.getTestClasses(PrepareForTestDemoClass.class); assertEquals(8, classesToPrepare.length); final String classPrefix = "Class"; final List classesToPrepareList = Arrays.asList(classesToPrepare); final int noOfClassesExplicitlyPrepared = 5; for (int i = 0; i < noOfClassesExplicitlyPrepared; i++) { final String className = classPrefix + (i + 1); assertTrue("Should prepare " + className, classesToPrepareList.contains(className)); } // We assert that the implicit classes (the test cases) are also added. assertTrue(classesToPrepareList.contains(PrepareForTestDemoClass.class.getName())); assertTrue(classesToPrepareList.contains(PrepareForTestDemoClassParent.class.getName())); assertTrue(classesToPrepareList.contains(PrepareForTestDemoClassGrandParent.class.getName())); } } @PrepareForTest(fullyQualifiedNames = { "Class1", "Class2" }) class PrepareForTestDemoClass extends PrepareForTestDemoClassParent { } @PrepareForTest(fullyQualifiedNames = { "Class3" }) class PrepareForTestDemoClassParent extends PrepareForTestDemoClassGrandParent { } @PrepareForTest(fullyQualifiedNames = { "Class4", "Class5" }) class PrepareForTestDemoClassGrandParent { } ================================================ FILE: powermock-core/src/test/java/org/powermock/utils/JavaVersionTest.java ================================================ package org.powermock.utils; import org.junit.Test; import static org.assertj.core.api.Java6Assertions.assertThat; public class JavaVersionTest { @Test public void should_return_true_for_current_version_that_if_high_than16() { assertThat(JavaVersion.JAVA_RECENT.atLeast(JavaVersion.JAVA_1_6)) .isTrue(); } } ================================================ FILE: powermock-core/src/test/java/org/powermock/utils/NumberUtilsTest.java ================================================ package org.powermock.utils; import org.assertj.core.data.Offset; import org.junit.Test; import static org.assertj.core.api.Java6Assertions.assertThat; public class NumberUtilsTest { @Test public void should_parse_and_return_float() { assertThat(NumberUtils.toFloat("133.1", 0.0f)) .as("String parsed to float") .isEqualTo(133.1f, Offset.offset(0.01f)); } @Test public void should_return_default_value_when_cannot_parse() { assertThat(NumberUtils.toFloat("11,1", 0.0f)) .as("String parsed to float") .isEqualTo(0.0f, Offset.offset(0.01f)); } @Test public void should_return_default_value_when_string_is_null() { assertThat(NumberUtils.toFloat(null, 0.0f)) .as("String parsed to float") .isEqualTo(0.0f, Offset.offset(0.01f)); } } ================================================ FILE: powermock-core/src/test/java/powermock/test/support/ClassForMockClassLoaderTestCase.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package powermock.test.support; public class ClassForMockClassLoaderTestCase { public String description() { return "This class is used for MockClassLoaderTest and located here only because package 'org.powermock.core' is always ignored."; } } ================================================ FILE: powermock-core/src/test/java/powermock/test/support/ClassWithLargeMethods.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package powermock.test.support; public class ClassWithLargeMethods { public static class MethodLowerThanLimit { /** * Method size after instrumentation is equal to 42989 */ public static String init() { String a = "A"; a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A"; a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A"; a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A"; a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A"; a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A"; a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A"; a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A"; a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A"; return a; } } public static class MethodGreaterThanLimit { /** * Method size after instrumentation is equal to 79522 */ public static String init() { String a = "A"; a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A"; a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A"; a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A"; a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A"; a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A"; a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A"; a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A"; String 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";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";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";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";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";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";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";b+="B"; return a + b; } } } ================================================ FILE: powermock-core/src/test/java/powermock/test/support/MainMockTransformerTestSupport.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package powermock.test.support; import org.powermock.core.classloader.MockClassLoaderConfiguration; import powermock.test.support.MainMockTransformerTestSupport.ConstructorCall.SupperClassThrowsException; /** * This class is used when running tests for different {@link org.powermock.core.transformers.MockTransformer}. It is * placed in this package because classes in org.powermock.core.* are deferred by: * {@link MockClassLoaderConfiguration#getDeferPackages()}. * Additionally, the class must be modified when it is loaded, and as such not in {@link MockClassLoaderConfiguration#shouldLoadWithMockClassloaderWithoutModifications(String)}. */ public class MainMockTransformerTestSupport { public static class StaticInitialization { public static String value; static { value = "Init"; } } public interface SomeInterface { } public interface ParameterInterface { } public static class ConstructorCall { public static class SupperClassThrowsException { public static final String MESSAGE = "Constructor of super class has been called"; public SupperClassThrowsException(String name, double value) { throw new IllegalArgumentException(MESSAGE); } public SupperClassThrowsException(final ParameterImpl value) { throw new IllegalArgumentException(MESSAGE); } public SupperClassThrowsException(final long... array) { throw new IllegalArgumentException(MESSAGE); } public void aVoid() { } public void bVoid(final String lname, final long lvalue) { } } } public static class SuperClassWithObjectMethod { public static boolean syntheticMethodIsCalled = false; public void doSomething(Object o) { } } public static class SubclassWithBridgeMethod extends SuperClassWithObjectMethod { public void doSomething(String s) { } } public static class SupportClasses { private static final Object finalStaticField = new Object(); private static transient final Object finalStaticTransientField = new Object(); private final Object finalField = new Object(); public enum EnumClass { VALUE } public final static class StaticFinalInnerClass { } public final static class FinalInnerClass { } private final static class PrivateStaticFinalInnerClass { } public static class MultipleConstructors { public MultipleConstructors() {} protected MultipleConstructors(String s) {} MultipleConstructors(int i) {} private MultipleConstructors(Boolean[] array) {} protected MultipleConstructors(int[] iarray, boolean b, String[] sarray) {} } public static class PublicSuperClass { public PublicSuperClass(String name) { } } class SuperClass { } public class SubClass extends SuperClass { public void dummyMethod() {} } } public static class SuperClassCallSuperConstructor extends SupperClassThrowsException { private final String field; public SuperClassCallSuperConstructor(final String name, String field, final double value) { super(name, value); this.field = field; String lname = name + "(a)"; long lvalue = (long) value * 2; if (lname == null) { aVoid(); } else { bVoid(lname, lvalue); } cVoid(lname, lvalue); } private void cVoid(final String lname, final long lvalue) { } } public static class SuperClassCallSuperConstructorWithCast extends SupperClassThrowsException { public SuperClassCallSuperConstructorWithCast(final ParameterInterface value) { super((ParameterImpl) value); } } public static class SuperClassCallSuperConstructorWithVararg extends SupperClassThrowsException { public SuperClassCallSuperConstructorWithVararg(final long... array) { super(array); } } public static class ParameterImpl implements ParameterInterface { } public static class StaticVoidMethodsTestClass { private static Object field; private static String lname; private static long value; public static void voidMethod(final String name, String field, final double value) { String lname = name + "(a)"; long lvalue = (long) value * 2; if (name == null) { aVoid(lvalue); } else { bVoid(lname); } StaticVoidMethodsTestClass.field = field; } private static void bVoid(final String lname) { StaticVoidMethodsTestClass.lname = lname; } private static void aVoid(final long value) { StaticVoidMethodsTestClass.value = value; } } public static class VoidMethodsTestClass { private Object field; private String lname; private long value; public void voidMethod(final String name, String field, final double value) { String lname = name + "(a)"; long lvalue = (long) value * 2; if (name == null) { aVoid(lvalue); } else { voidPrivateMethod(lname); } this.field = field; } public void finalVoidMethod(final String name, String field, final double value) { String lname = name + "(a)"; long lvalue = (long) value * 2; if (name == null) { aVoid(lvalue); } else { voidPrivateMethod(lname); } this.field = field; } private void voidPrivateMethod(final String lname) { this.lname = lname; } private void aVoid(final long value) { this.value = value; } } public static class ReturnMethodsTestClass { private String lname; private long value; public String returnMethod(final String name, String field, final double value) { long lvalue = (long) value * 2; if (name == null) { return aVoid(lvalue); } else { return privateReturnMethod(name); } } public final String finalReturnMethod(final String name, String field, final double value) { long lvalue = (long) value * 2; if (name == null) { return aVoid(lvalue); } else { return privateReturnMethod(name); } } private String privateReturnMethod(final String name) { final String lname = name + "(a)"; this.lname = lname; return lname; } private String aVoid(final long value) { this.value = value; return "" + value; } } public static abstract class AbstractMethodTestClass { public abstract String returnMethod(final String name, String field, final double value); } public static class NativeMethodsTestClass { public static native String nativeStaticReturnMethod(final String name); public native String nativeReturnMethod(final String name); } public static class ChildOfNativeMethodsTestClass extends NativeMethodsTestClass { } public static class ParentTestClass { public static class NestedTestClass{ public NestedTestClass() {} protected NestedTestClass(String s) {} NestedTestClass(int i) {} private NestedTestClass(Boolean[] array) {} protected NestedTestClass(int[] iarray, boolean b, String[] sarray) {} } } public static class ClassWithoutHashCode { } } ================================================ FILE: powermock-core/src/test/java/powermock/test/support/TestWithTwoTestMethods.java ================================================ package powermock.test.support; import org.junit.Test; public class TestWithTwoTestMethods { @Test public void test_method_1() { } @Test public void test_method_2() { } public static class NestedTestWithTwoTestMethods { @Test public void test_nested_method_1() { } @Test public void test_nested_method_2() { } } } ================================================ FILE: powermock-core/src/test/resources/org/powermock/core/classloader/foo/bar/baz/test.txt ================================================ This is the droid that you are looking for... ================================================ FILE: powermock-core/src/test/resources/org/powermock/extensions/test.properties ================================================ mockito.mock-maker-class=TestMockMaker powermock.global-ignore=org.somepacckage.*,org.other.Class ================================================ FILE: powermock-core/src/test/resources/org/powermock/extensions/test_configuration.properties ================================================ powermock.global-ignore=org.somepackage powermock.byte-code-framework=Javassist ================================================ FILE: powermock-core/src/test/resources/org/powermock/extensions/test_with_alias.properties ================================================ mockito.mock-maker-class=alias ================================================ FILE: powermock-core/src/test/resources/org/powermock/extensions/test_without_prefix.properties ================================================ mock-maker-class=TestMockMaker ================================================ FILE: powermock-core/src/test/resources/org/powermock/test_default_configuration.properties ================================================ powermock.global-ignore=org.powermock.core* powermock.byte-code-framework=Javassist ================================================ FILE: powermock-modules/powermock-module-javaagent/jmockit-license.txt ================================================ The JMockit Testing Toolkit Copyright (c) 2006-2011 Rogério Liesenfeld Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: powermock-modules/powermock-module-javaagent/src/main/java/com/sun/tools/attach/AgentInitializationException.java ================================================ /* * Copyright 2005-2006 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ package com.sun.tools.attach; /** * The exception thrown when an agent fails to initialize in the target Java virtual machine. *

*

This exception is thrown by {@link * VirtualMachine#loadAgent VirtualMachine.loadAgent}, * {@link VirtualMachine#loadAgentLibrary * VirtualMachine.loadAgentLibrary}, {@link * VirtualMachine#loadAgentPath VirtualMachine.loadAgentPath} * methods if an agent, or agent library, cannot be initialized. * When thrown by VirtualMachine.loadAgentLibrary, or * VirtualMachine.loadAgentPath then the exception encapsulates * the error returned by the agent's {@code Agent_OnAttach} function. * This error code can be obtained by invoking the {@link #returnValue() returnValue} method. */ public final class AgentInitializationException extends Exception { private static final long serialVersionUID = -1508756333332806353L; private final int returnValue; /** * Constructs an {@code AgentInitializationException} with * no detail message. */ public AgentInitializationException() { returnValue = 0; } /** * Constructs an {@code AgentInitializationException} with the specified detail message. * * @param s the detail message. */ public AgentInitializationException(String s) { super(s); returnValue = 0; } /** * Constructs an {@code AgentInitializationException} with * the specified detail message and the return value from the * execution of the agent's {@code Agent_OnAttach} function. * * @param s the detail message. * @param returnValue the return value */ public AgentInitializationException(String s, int returnValue) { super(s); this.returnValue = returnValue; } /** * If the exception was created with the return value from the agent * {@code Agent_OnAttach} function then this returns that value, * otherwise returns {@code 0}.

*/ public int returnValue() { return returnValue; } } ================================================ FILE: powermock-modules/powermock-module-javaagent/src/main/java/com/sun/tools/attach/AgentLoadException.java ================================================ /* * Copyright 2005 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ package com.sun.tools.attach; /** * The exception thrown when an agent cannot be loaded into the target Java virtual machine. *

*

This exception is thrown by {@link * VirtualMachine#loadAgent VirtualMachine.loadAgent} or * {@link VirtualMachine#loadAgentLibrary * VirtualMachine.loadAgentLibrary}, {@link VirtualMachine#loadAgentPath loadAgentPath} methods * if the agent, or agent library, cannot be loaded. */ public final class AgentLoadException extends Exception { private static final long serialVersionUID = 688047862952114238L; /** * Constructs an {@code AgentLoadException} with * no detail message. */ public AgentLoadException() { } /** * Constructs an {@code AgentLoadException} with the specified detail message. */ public AgentLoadException(String s) { super(s); } } ================================================ FILE: powermock-modules/powermock-module-javaagent/src/main/java/com/sun/tools/attach/AttachNotSupportedException.java ================================================ /* * Copyright 2005 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ package com.sun.tools.attach; /** * Thrown by {@link VirtualMachine#attach VirtalMachine.attach} when attempting to attach to a Java * virtual machine for which a compatible {@link com.sun.tools.attach.spi.AttachProvider * AttachProvider} does not exist. It is also thrown by {@link * com.sun.tools.attach.spi.AttachProvider#attachVirtualMachine * AttachProvider.attachVirtualMachine} if the provider attempts to * attach to a Java virtual machine with which it not compatible. */ public final class AttachNotSupportedException extends Exception { private static final long serialVersionUID = 3391824968260177264L; /** * Constructs an {@code AttachNotSupportedException} with no detail message. */ public AttachNotSupportedException() { } /** * Constructs an {@code AttachNotSupportedException} with * the specified detail message. * * @param s the detail message. */ public AttachNotSupportedException(String s) { super(s); } } ================================================ FILE: powermock-modules/powermock-module-javaagent/src/main/java/com/sun/tools/attach/VirtualMachine.java ================================================ /* * Copyright 2005-2006 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ package com.sun.tools.attach; import com.sun.tools.attach.spi.AttachProvider; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Properties; /** *

* A Java virtual machine. *

*

A {@code VirtualMachine} represents a Java virtual machine to which this * Java virtual machine has attached. The Java virtual machine to which it is * attached is sometimes called the target virtual machine, or target VM. * An application (typically a tool such as a managemet console or profiler) uses a * VirtualMachine to load an agent into the target VM. For example, a profiler tool * written in the Java Language might attach to a running application and load its * profiler agent to profile the running application.

*

A VirtualMachine is obtained by invoking the {@link #attach(String) attach} method * with an identifier that identifies the target virtual machine. The identifier is * implementation-dependent but is typically the process identifier (or pid) in * environments where each Java virtual machine runs in its own operating system process. * Alternatively, a {@code VirtualMachine} instance is obtained by invoking the * {@link #attach(VirtualMachineDescriptor) attach} method with a {@link * com.sun.tools.attach.VirtualMachineDescriptor VirtualMachineDescriptor} obtained * from the list of virtual machine descriptors returned by the {@link #list list} method. * Once a reference to a virtual machine is obtained, the {@link #loadAgent loadAgent}, * {@link #loadAgentLibrary loadAgentLibrary}, and {@link #loadAgentPath loadAgentPath} * methods are used to load agents into target virtual machine. The {@link * #loadAgent loadAgent} method is used to load agents that are written in the Java * Language and deployed in a {@link java.util.jar.JarFile JAR file}. (See * {@link java.lang.instrument} for a detailed description on how these agents * are loaded and started). The {@link #loadAgentLibrary loadAgentLibrary} and * {@link #loadAgentPath loadAgentPath} methods are used to load agents that * are deployed in a dynamic library and make use of the JVM Tools * Interface.

*

In addition to loading agents a VirtualMachine provides read access to the * {@link java.lang.System#getProperties() system properties} in the target VM. * This can be useful in some environments where properties such as * {@code java.home}, {@code os.name}, or {@code os.arch} are * used to construct the path to agent that will be loaded into the target VM. *

*

The following example demonstrates how VirtualMachine may be used:

*
 *      // attach to target VM
 *      VirtualMachine vm = VirtualMachine.attach("2177");
 *      // get system properties in target VM
 *      Properties props = vm.getSystemProperties();
 *      // construct path to management agent
 *      String home = props.getProperty("java.home");
 *      String agent = home + File.separator + "lib" + File.separator
 *          + "management-agent.jar";
 *      // load agent into target VM
 *      vm.loadAgent(agent, "com.sun.management.jmxremote.port=5000");
 *      // detach
 *      vm.detach();
 * 
*

In this example we attach to a Java virtual machine that is identified by * the process identifier {@code 2177}. The system properties from the target * VM are then used to construct the path to a management agent which is then * loaded into the target VM. Once loaded the client detaches from the target VM.

*

A VirtualMachine is safe for use by multiple concurrent threads.

* * @since 1.6 */ public abstract class VirtualMachine { private final AttachProvider provider; private final String id; private volatile int hash; // 0 => not computed /** * Initializes a new instance of this class. * * @param provider The attach provider creating this class. * @param id The abstract identifier that identifies the Java virtual machine. */ protected VirtualMachine(AttachProvider provider, String id) { this.provider = provider; this.id = id; } /** *

* Return a list of Java virtual machines. *

*

* This method returns a list of Java {@link com.sun.tools.attach.VirtualMachineDescriptor} * elements. The list is an aggregation of the virtual machine descriptor lists obtained by * invoking the {@link com.sun.tools.attach.spi.AttachProvider#listVirtualMachines * listVirtualMachines} method of all installed {@link com.sun.tools.attach.spi.AttachProvider * attach providers}. If there are no Java virtual machines known to any provider then an empty * list is returned. *

* @return The list of virtual machine descriptors. */ public static List list() { List l = new ArrayList(); List providers = AttachProvider.providers(); for (AttachProvider provider : providers) { l.addAll(provider.listVirtualMachines()); } return l; } /** *

* Attaches to a Java virtual machine. *

*

* This method obtains the list of attach providers by invoking the * {@link com.sun.tools.attach.spi.AttachProvider#providers() AttachProvider.providers()} method. * It then iterates overs the list and invokes each provider's {@link * com.sun.tools.attach.spi.AttachProvider#attachVirtualMachine(java.lang.String) * attachVirtualMachine} method in turn. If a provider successfully * attaches then the iteration terminates, and the VirtualMachine created * by the provider that successfully attached is returned by this method. * If the {@code attachVirtualMachine} method of all providers throws * {@link com.sun.tools.attach.AttachNotSupportedException AttachNotSupportedException} * then this method also throws {@code AttachNotSupportedException}. * This means that {@code AttachNotSupportedException} is thrown when * the identifier provided to this method is invalid, or the identifier * corresponds to a Java virtual machine that does not exist, or none * of the providers can attach to it. This exception is also thrown if * {@link com.sun.tools.attach.spi.AttachProvider#providers() * AttachProvider.providers()} returns an empty list. *

* * @param id The abstract identifier that identifies the Java virtual machine. * @return A VirtualMachine representing the target VM. * @throws SecurityException If a security manager has been installed and it denies * {@link com.sun.tools.attach.AttachPermission AttachPermission} * ("attachVirtualMachine"), or another permission * required by the implementation. * @throws IOException If an I/O error occurs */ public static VirtualMachine attach(String id) throws AttachNotSupportedException, IOException { List providers = AttachProvider.providers(); AttachNotSupportedException lastExc = null; for (AttachProvider provider : providers) { try { return provider.attachVirtualMachine(id); } catch (AttachNotSupportedException x) { lastExc = x; } } throw lastExc; } /** * Attaches to a Java virtual machine. *

* This method first invokes the {@link com.sun.tools.attach.VirtualMachineDescriptor#provider() * provider()} method of the given virtual machine descriptor to obtain the attach provider. * It then invokes the attach provider's {@link * com.sun.tools.attach.spi.AttachProvider#attachVirtualMachine(VirtualMachineDescriptor) * attachVirtualMachine} to attach to the target VM. * * @param vmd The virtual machine descriptor. * * @return A VirtualMachine representing the target VM. * * @throws SecurityException * If a security manager has been installed and it denies * {@link com.sun.tools.attach.AttachPermission AttachPermission} * ("attachVirtualMachine"), or another permission * required by the implementation. * * @throws AttachNotSupportedException * If the attach provider's {@code attachVirtualmachine} * throws {@code AttachNotSupportedException}. * * @throws IOException If an I/O error occurs * * @throws NullPointerException If {@code vmd} is {@code null}. */ public static VirtualMachine attach(VirtualMachineDescriptor vmd) throws AttachNotSupportedException, IOException { return vmd.provider().attachVirtualMachine(vmd); } /** * Detach from the virtual machine. *

* After detaching from the virtual machine, any further attempt to invoke * operations on that virtual machine will cause an {@link java.io.IOException * IOException} to be thrown. If an operation (such as {@link #loadAgent * loadAgent} for example) is in progress when this method is invoked then * the behaviour is implementation dependent. In other words, it is * implementation specific if the operation completes or throws IOException. *

* If already detached from the virtual machine then invoking this method has no effect. * * @throws IOException If an I/O error occurs */ public abstract void detach() throws IOException; /** * Returns the provider that created this virtual machine. */ public final AttachProvider provider() { return provider; } /** * Returns the identifier for this Java virtual machine. */ public final String id() { return id; } /** * Loads an agent library. *

* A JVM * TI client is called an agent. It is developed in a native language. * A JVM TI agent is deployed in a platform specific manner but it is typically the * platform equivalent of a dynamic library. This method causes the given agent * library to be loaded into the target VM (if not already loaded). * It then causes the target VM to invoke the {@code Agent_OnAttach} function * as specified in the * JVM Tools * Interface specification. Note that the {@code Agent_OnAttach} * function is invoked even if the agent library was loaded prior to invoking * this method. *

* The agent library provided is the name of the agent library. It is interpreted * in the target virtual machine in an implementation-dependent manner. Typically an * implementation will expand the library name into an operating system specific file * name. For example, on UNIX systems, the name foo might be expanded to * libfoo.so, and located using the search path specified by the * LD_LIBRARY_PATH environment variable. *

* If the {@code Agent_OnAttach} function in the agent library returns * an error then an {@link com.sun.tools.attach.AgentInitializationException} is * thrown. The return value from the {@code Agent_OnAttach} can then be * obtained by invoking the {@link * com.sun.tools.attach.AgentInitializationException#returnValue() returnValue} * method on the exception. * * @param agentLibrary The name of the agent library. * @param options The options to provide to the {@code Agent_OnAttach} * function (can be {@code null}). * @throws AgentLoadException If the agent library does not exist, or cannot be loaded for * another reason. * @throws AgentInitializationException If the {@code Agent_OnAttach} function returns an error * @throws IOException If an I/O error occurs * @throws NullPointerException If {@code agentLibrary} is {@code null}. * @see com.sun.tools.attach.AgentInitializationException#returnValue() */ public abstract void loadAgentLibrary(String agentLibrary, String options) throws AgentLoadException, AgentInitializationException, IOException; /** * Loads an agent library. *

* This convenience method works as if by invoking: *

*

* {@link #loadAgentLibrary(String, String) loadAgentLibrary}(agentLibrary, null); *
* * @param agentLibrary The name of the agent library. * @throws AgentLoadException If the agent library does not exist, or cannot be loaded for * another reason. * @throws AgentInitializationException If the {@code Agent_OnAttach} function returns an error * @throws IOException If an I/O error occurs * @throws NullPointerException If {@code agentLibrary} is {@code null}. */ public void loadAgentLibrary(String agentLibrary) throws AgentLoadException, AgentInitializationException, IOException { loadAgentLibrary(agentLibrary, null); } /** * Load a native agent library by full pathname. *

* A JVM TI client is * called an agent. It is developed in a native language. * A JVM TI agent is deployed in a platform specific manner but it is typically the * platform equivalent of a dynamic library. This method causes the given agent * library to be loaded into the target VM (if not already loaded). * It then causes the target VM to invoke the {@code Agent_OnAttach} function * as specified in the * JVM Tools * Interface specification. Note that the {@code Agent_OnAttach} * function is invoked even if the agent library was loaded prior to invoking * this method. *

* The agent library provided is the absolute path from which to load the * agent library. Unlike {@link #loadAgentLibrary loadAgentLibrary}, the library name * is not expanded in the target virtual machine. *

* If the {@code Agent_OnAttach} function in the agent library returns * an error then an {@link com.sun.tools.attach.AgentInitializationException} is * thrown. The return value from the {@code Agent_OnAttach} can then be * obtained by invoking the {@link * com.sun.tools.attach.AgentInitializationException#returnValue() returnValue} * method on the exception. * * @param agentPath The full path of the agent library. * @param options The options to provide to the {@code Agent_OnAttach} * function (can be {@code null}). * @throws AgentLoadException If the agent library does not exist, or cannot be loaded for * another reason. * @throws AgentInitializationException If the {@code Agent_OnAttach} function returns an error * @throws IOException If an I/O error occurs * @throws NullPointerException If {@code agentPath} is {@code null}. * @see com.sun.tools.attach.AgentInitializationException#returnValue() */ public abstract void loadAgentPath(String agentPath, String options) throws AgentLoadException, AgentInitializationException, IOException; /** * Load a native agent library by full pathname. *

* This convenience method works as if by invoking: *

*

* {@link #loadAgentPath(String, String) loadAgentPath}(agentLibrary, null); *
* * @param agentPath The full path to the agent library. * @throws AgentLoadException If the agent library does not exist, or cannot be loaded for * another reason. * @throws AgentInitializationException If the {@code Agent_OnAttach} function returns an error * @throws IOException If an I/O error occurs * @throws NullPointerException If {@code agentPath} is {@code null}. */ public void loadAgentPath(String agentPath) throws AgentLoadException, AgentInitializationException, IOException { loadAgentPath(agentPath, null); } /** * Loads an agent. *

*

The agent provided to this method is a path name to a JAR file on the file * system of the target virtual machine. This path is passed to the target virtual * machine where it is interpreted. The target virtual machine attempts to start * the agent as specified by the {@link java.lang.instrument} specification. * That is, the specified JAR file is added to the system class path (of the target * virtual machine), and the {@code agentmain} method of the agent class, specified * by the {@code Agent-Class} attribute in the JAR manifest, is invoked. This * method completes when the {@code agentmain} method completes. * * @param agent Path to the JAR file containing the agent. * @param options The options to provide to the agent's {@code agentmain} * method (can be {@code null}). * @throws AgentLoadException If the agent does not exist, or cannot be started in the manner * specified in the {@link java.lang.instrument} specification. * @throws AgentInitializationException If the {@code agentmain} throws an exception * @throws IOException If an I/O error occurs * @throws NullPointerException If {@code agent} is {@code null}. */ public abstract void loadAgent(String agent, String options) throws AgentLoadException, AgentInitializationException, IOException; /** * Loads an agent. *

* This convenience method works as if by invoking: *

*

* {@link #loadAgent(String, String) loadAgent}(agent, null); *
* * @param agent Path to the JAR file containing the agent. * @throws AgentLoadException If the agent does not exist, or cannot be started in the manner * specified in the {@link java.lang.instrument} specification. * @throws AgentInitializationException If the {@code agentmain} throws an exception * @throws IOException If an I/O error occurs * @throws NullPointerException If {@code agent} is {@code null}. */ public void loadAgent(String agent) throws AgentLoadException, AgentInitializationException, IOException { loadAgent(agent, null); } /** * Returns the current system properties in the target virtual machine. *

* This method returns the system properties in the target virtual * machine. Properties whose key or value is not a String are * omitted. The method is approximately equivalent to the invocation of the * method {@link java.lang.System#getProperties System.getProperties} * in the target virtual machine except that properties with a key or * value that is not a String are not included. *

* This method is typically used to decide which agent to load into * the target virtual machine with {@link #loadAgent loadAgent}, or * {@link #loadAgentLibrary loadAgentLibrary}. For example, the * {@code java.home} or {@code user.dir} properties might be * use to create the path to the agent library or JAR file. * * @return The system properties * @throws IOException If an I/O error occurs * @see java.lang.System#getProperties * @see #loadAgentLibrary * @see #loadAgent */ public abstract Properties getSystemProperties() throws IOException; /** * Returns the current agent properties in the target virtual * machine. *

* The target virtual machine can maintain a list of properties on * behalf of agents. The manner in which this is done, the names of the * properties, and the types of values that are allowed, is implementation * specific. Agent properties are typically used to store communication * end-points and other agent configuration details. For example, a debugger * agent might create an agent property for its transport address. *

* This method returns the agent properties whose key and value is a * String. Properties whose key or value is not a String * are omitted. If there are no agent properties maintained in the target * virtual machine then an empty property list is returned. * * @return The agent properties * @throws IOException If an I/O error occurs */ public abstract Properties getAgentProperties() throws IOException; /** * Returns a hash-code value for this VirtualMachine. The hash * code is based upon the VirtualMachine's components, and satisfies * the general contract of the Object.hashCode method. * * @return A hash-code value for this virtual machine */ @Override public int hashCode() { if (hash != 0) { return hash; } hash = provider.hashCode() * 127 + id.hashCode(); return hash; } /** * Tests this VirtualMachine for equality with another object. *

*

If the given object is not a VirtualMachine then this * method returns false. For two VirtualMachines to * be considered equal requires that they both reference the same * provider, and their {@link VirtualMachineDescriptor#id() identifiers} are equal.

*

*

This method satisfies the general contract of the method.

* * @param ob The object to which this object is to be compared * @return true if, and only if, the given object is * a VirtualMachine that is equal to this * VirtualMachine. */ @Override public boolean equals(Object ob) { if (ob == this) { return true; } if (!(ob instanceof VirtualMachine)) { return false; } VirtualMachine other = (VirtualMachine) ob; return other.provider() == provider() && other.id().equals(id()); } /** * Returns the string representation of the {@code VirtualMachine}. */ @Override public String toString() { return provider.toString() + ": " + id; } } ================================================ FILE: powermock-modules/powermock-module-javaagent/src/main/java/com/sun/tools/attach/VirtualMachineDescriptor.java ================================================ /* * Copyright 2005-2006 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ package com.sun.tools.attach; import com.sun.tools.attach.spi.AttachProvider; /** * Describes a Java virtual machine. *

*

A {@code VirtualMachineDescriptor} is a container class used to * describe a Java virtual machine. It encapsulates an identifier that identifies * a target virtual machine, and a reference to the {@link * com.sun.tools.attach.spi.AttachProvider AttachProvider} that should be used * when attempting to attach to the virtual machine. The identifier is * implementation-dependent but is typically the process identifier (or pid) * environments where each Java virtual machine runs in its own operating system * process.

*

*

A {@code VirtualMachineDescriptor} also has a {@link #displayName() displayName}. * The display name is typically a human readable string that a tool might * display to a user. For example, a tool that shows a list of Java * virtual machines running on a system might use the display name rather * than the identifier. A {@code VirtualMachineDescriptor} may be * created without a display name. In that case the identifier is * used as the display name. *

*

{@code VirtualMachineDescriptor} instances are typically created by * invoking the {@link VirtualMachine#list VirtualMachine.list()} * method. This returns the complete list of descriptors to describe the * Java virtual machines known to all installed {@link * com.sun.tools.attach.spi.AttachProvider attach providers}. * * @since 1.6 */ public final class VirtualMachineDescriptor { private AttachProvider provider; private String id; private String displayName; private volatile int hash; // 0 => not computed /** * Creates a virtual machine descriptor from the given components. * * @param provider The AttachProvider to attach to the Java virtual machine. * @param id The virtual machine identifier. * @param displayName The display name. * @throws NullPointerException If any of the arguments are {@code null} */ public VirtualMachineDescriptor(AttachProvider provider, String id, String displayName) { if (provider == null) { throw new NullPointerException("provider cannot be null"); } if (id == null) { throw new NullPointerException("identifier cannot be null"); } if (displayName == null) { throw new NullPointerException("display name cannot be null"); } this.provider = provider; this.id = id; this.displayName = displayName; } /** * Creates a virtual machine descriptor from the given components. *

*

This convenience constructor works as if by invoking the * three-argument constructor as follows: *

*

* new {@link #VirtualMachineDescriptor(com.sun.tools.attach.spi.AttachProvider, String, String) * VirtualMachineDescriptor}(provider,  id,  id); *
*

*

That is, it creates a virtual machine descriptor such that * the display name is the same as the virtual machine * identifier. * * @param provider The AttachProvider to attach to the Java virtual machine. * @param id The virtual machine identifier. * @throws NullPointerException If provider or id is null. */ public VirtualMachineDescriptor(AttachProvider provider, String id) { this(provider, id, id); } /** * Return the {@code AttachProvider} that this descriptor references. * * @return The {@code AttachProvider} that this descriptor references. */ public AttachProvider provider() { return provider; } /** * Return the identifier component of this descriptor. * * @return The identifier component of this descriptor. */ public String id() { return id; } /** * Return the display name component of this descriptor. * * @return The display name component of this descriptor. */ public String displayName() { return displayName; } /** * Returns a hash-code value for this VirtualMachineDescriptor. The hash * code is based upon the descriptor's components, and satisfies * the general contract of the Object.hashCode method. * * @return A hash-code value for this descriptor. */ @Override public int hashCode() { if (hash != 0) { return hash; } hash = provider.hashCode() * 127 + id.hashCode(); return hash; } /** * Tests this VirtualMachineDescriptor for equality with another object. *

*

If the given object is not a VirtualMachineDescriptor then this * method returns false. For two VirtualMachineDescriptors to * be considered equal requires that they both reference the same * provider, and their {@link #id() identifiers} are equal.

*

*

This method satisfies the general contract of the method.

* * @param ob The object to which this object is to be compared * @return true if, and only if, the given object is * a VirtualMachineDescriptor that is equal to this * VirtualMachineDescriptor. */ @Override public boolean equals(Object ob) { if (ob == this) return true; if (!(ob instanceof VirtualMachineDescriptor)) return false; VirtualMachineDescriptor other = (VirtualMachineDescriptor) ob; if (other.provider() != this.provider()) { return false; } if (!other.id().equals(this.id())) { return false; } return true; } /** * Returns the string representation of the {@code VirtualMachineDescriptor}. */ @Override public String toString() { String s = provider.toString() + ": " + id; if (displayName != id) { s += " " + displayName; } return s; } } ================================================ FILE: powermock-modules/powermock-module-javaagent/src/main/java/com/sun/tools/attach/spi/AttachProvider.java ================================================ /* * Copyright 2005-2006 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ package com.sun.tools.attach.spi; import com.sun.tools.attach.AttachNotSupportedException; import com.sun.tools.attach.VirtualMachine; import com.sun.tools.attach.VirtualMachineDescriptor; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.ServiceLoader; /** *

* Attach provider class for attaching to a Java virtual machine. *

*

An attach provider is a concrete subclass of this class that has a * zero-argument constructor and implements the abstract methods specified * below. *

*

* An attach provider implementation is typically tied to a Java virtual * machine implementation, version, or even mode of operation. That is, a specific * provider implementation will typically only be capable of attaching to * a specific Java virtual machine implementation or version. For example, Sun's * JDK implementation ships with provider implementations that can only attach to * Sun's HotSpot virtual machine. In general, if an environment * consists of Java virtual machines of different versions and from different * vendors then there will be an attach provider implementation for each * family of implementations or versions. *

*

An attach provider is identified by its {@link #name name} and * {@link #type type}. The name is typically, but not required to * be, a name that corresponds to the VM vendor. The Sun JDK implementation, * for example, ships with attach providers that use the name "sun". The * type typically corresponds to the attach mechanism. For example, an * implementation that uses the Doors inter-process communication mechanism * might use the type "doors". The purpose of the name and type is to * identify providers in environments where there are multiple providers * installed.

*

AttachProvider implementations are loaded and instantiated at the first * invocation of the {@link #providers() providers} method. This method * attempts to load all provider implementations that are installed on the * platform.

*

All of the methods in this class are safe for use by multiple * concurrent threads.

* * @since 1.6 */ public abstract class AttachProvider { private static final Object lock = new Object(); private static List providers; /** * Initializes a new instance of this class. */ protected AttachProvider() {} /** * Return this provider's name. * * @return The name of this provider */ public abstract String name(); /** * Return this provider's type. * * @return The type of this provider */ public abstract String type(); /** *

* Attaches to a Java virtual machine. *

*

A Java virtual machine is identified by an abstract identifier. The * nature of this identifier is platform dependent but in many cases it will be the * string representation of the process identifier (or pid).

*

*

This method parses the identifier and maps the identifier to a Java * virtual machine (in an implementation dependent manner). If the identifier * cannot be parsed by the provider then an {@link * com.sun.tools.attach.AttachNotSupportedException AttachNotSupportedException} * is thrown. Once parsed this method attempts to attach to the Java virtual machine. * If the provider detects that the identifier corresponds to a Java virtual machine * that does not exist, or it corresponds to a Java virtual machine that does not support * the attach mechanism implemented by this provider, or it detects that the * Java virtual machine is a version to which this provider cannot attach, then * an AttachNotSupportedException is thrown.

* * @param id The abstract identifier that identifies the Java virtual machine. * @return VirtualMachine representing the target virtual machine. * @throws SecurityException If a security manager has been installed and it denies * {@link com.sun.tools.attach.AttachPermission AttachPermission} * ("attachVirtualMachine"), or other permission * required by the implementation. * @throws AttachNotSupportedException If the identifier cannot be parsed, or it corresponds to * to a Java virtual machine that does not exist, or it * corresponds to a Java virtual machine which this * provider cannot attach. * @throws IOException If some other I/O error occurs * @throws NullPointerException If id is null */ public abstract VirtualMachine attachVirtualMachine(String id) throws AttachNotSupportedException, IOException; /** *

* Attaches to a Java virtual machine. *

*

* A Java virtual machine can be described using a {@link * com.sun.tools.attach.VirtualMachineDescriptor VirtualMachineDescriptor}. * This method invokes the descriptor's {@link * com.sun.tools.attach.VirtualMachineDescriptor#provider() provider()} method * to check that it is equal to this provider. It then attempts to attach to the * Java virtual machine. *

* * @param vmd The virtual machine descriptor * @return VirtualMachine representing the target virtual machine. * @throws SecurityException If a security manager has been installed and it denies * {@link com.sun.tools.attach.AttachPermission AttachPermission} * ("attachVirtualMachine"), or other permission * required by the implementation. * @throws AttachNotSupportedException If the descriptor's {@link * com.sun.tools.attach.VirtualMachineDescriptor#provider() provider()} method * returns a provider that is not this provider, or it does not correspond * to a Java virtual machine to which this provider can attach. * @throws IOException If some other I/O error occurs * @throws NullPointerException If vmd is null */ public VirtualMachine attachVirtualMachine(VirtualMachineDescriptor vmd) throws AttachNotSupportedException, IOException { if (vmd.provider() != this) { throw new AttachNotSupportedException("provider mismatch"); } return attachVirtualMachine(vmd.id()); } /** *

* Lists the Java virtual machines known to this provider. *

*

* This method returns a list of {@link com.sun.tools.attach.VirtualMachineDescriptor} elements. * Each VirtualMachineDescriptor describes a Java virtual machine * to which this provider can potentially attach. There isn't any * guarantee that invoking {@link #attachVirtualMachine(VirtualMachineDescriptor) * attachVirtualMachine} on each descriptor in the list will succeed. *

* @return The list of virtual machine descriptors which describe the * Java virtual machines known to this provider (may be empty). */ public abstract List listVirtualMachines(); /** *

* Returns a list of the installed attach providers. *

*

An AttachProvider is installed on the platform if: *

*

    *
  • It is installed in a JAR file that is visible to the defining * class loader of the AttachProvider type (usually, but not required * to be, the {@link java.lang.ClassLoader#getSystemClassLoader system * class loader}).

  • *
  • The JAR file contains a provider configuration named * com.sun.tools.attach.spi.AttachProvider in the resource directory * META-INF/services.

  • *
  • The provider configuration file lists the full-qualified class * name of the AttachProvider implementation.

  • *
*

The format of the provider configuration file is one fully-qualified * class name per line. Space and tab characters surrounding each class name, * as well as blank lines are ignored. The comment character is * '#' (0x23), and on each line all characters following * the first comment character are ignored. The file must be encoded in * UTF-8.

*

AttachProvider implementations are loaded and instantiated * (using the zero-arg constructor) at the first invocation of this method. * The list returned by the first invocation of this method is the list * of providers. Subsequent invocations of this method return a list of the same * providers. The list is unmodifable.

* * @return A list of the installed attach providers. */ @SuppressWarnings({"Since15"}) public static List providers() { synchronized (lock) { if (providers == null) { providers = new ArrayList(); ServiceLoader providerLoader = ServiceLoader.load(AttachProvider.class, AttachProvider.class.getClassLoader()); for (AttachProvider aProviderLoader : providerLoader) { try { providers.add(aProviderLoader); } catch (ThreadDeath td) { throw td; } catch (Throwable t) { // Ignore errors and exceptions. System.err.println(t); } } } return Collections.unmodifiableList(providers); } } } ================================================ FILE: powermock-modules/powermock-module-javaagent/src/main/java/org/powermock/modules/agent/AbstractClassTransformer.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.modules.agent; import org.powermock.core.WildcardMatcher; import java.util.Collections; import java.util.LinkedList; import java.util.List; public abstract class AbstractClassTransformer { private static final List ALWAYS_IGNORED = new LinkedList(); private final List USER_IGNORED = Collections.synchronizedList(new LinkedList()); static { ALWAYS_IGNORED.add("org.powermock.*"); ALWAYS_IGNORED.add("org.junit.*"); ALWAYS_IGNORED.add("org.testng.*"); ALWAYS_IGNORED.add("org.assertj.*"); ALWAYS_IGNORED.add("org.mockito.*"); ALWAYS_IGNORED.add("javassist.*"); ALWAYS_IGNORED.add("org.objenesis.*"); ALWAYS_IGNORED.add("junit.*"); ALWAYS_IGNORED.add("org.hamcrest.*"); ALWAYS_IGNORED.add("sun.*"); ALWAYS_IGNORED.add("$Proxy*"); ALWAYS_IGNORED.add("*CGLIB$$*"); ALWAYS_IGNORED.add("*$$PowerMock*"); } public synchronized void setPackagesToIgnore(List packagesToIgnore) { USER_IGNORED.clear(); USER_IGNORED.addAll(packagesToIgnore); } public void resetPackagesToIgnore() { USER_IGNORED.clear(); } protected boolean shouldIgnore(String className) { return WildcardMatcher.matchesAny(merge(USER_IGNORED), replaceSlashWithDots(className)); } private List merge(List userIgnored) { List list = new LinkedList(AbstractClassTransformer.ALWAYS_IGNORED); list.addAll(userIgnored); return Collections.unmodifiableList(list); } String replaceSlashWithDots(String className) { return className.replaceAll("/", "."); } } ================================================ FILE: powermock-modules/powermock-module-javaagent/src/main/java/org/powermock/modules/agent/AgentInitialization.java ================================================ /* * The JMockit Testing Toolkit * Copyright (c) 2006-2011 Rogério Liesenfeld * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.powermock.modules.agent; import java.io.File; import java.net.URI; import java.net.URISyntaxException; import java.security.CodeSource; import java.util.regex.Pattern; final class AgentInitialization { private static final Pattern JAR_REGEX = Pattern.compile(".*powermock-module-javaagent[-]?[.\\d+]*[-]?[A-Z]*.jar"); void initializeAccordingToJDKVersion() { String jarFilePath = discoverPathToJarFile(); if (PowerMockAgent.jdk6OrLater) { new AgentLoader(jarFilePath).loadAgent(); } else if ("1.5".equals(PowerMockAgent.javaSpecVersion)) { throw new IllegalStateException( "PowerMock has not been initialized. Check that your Java 5 VM has been started with the -javaagent:" + jarFilePath + " command line option."); } else { throw new IllegalStateException("PowerMock requires a Java 5 VM or later."); } } private String discoverPathToJarFile() { String jarFilePath = findPathToJarFileFromClasspath(); if (jarFilePath == null) { // This can fail for a remote URL, so it is used as a fallback only: jarFilePath = getPathToJarFileContainingThisClass(); } if (jarFilePath != null) { return jarFilePath; } throw new IllegalStateException( "No jar file with name ending in \"powermock-module-javaagent.jar\" or \"powermock-module-javaagent-nnn.jar\" (where \"nnn\" is a version number) " + "found in the classpath"); } private String findPathToJarFileFromClasspath() { String[] classPath = System.getProperty("java.class.path").split(File.pathSeparator); for (String cpEntry : classPath) { if (JAR_REGEX.matcher(cpEntry).matches()) { return cpEntry; } } return null; } private String getPathToJarFileContainingThisClass() { CodeSource codeSource = AgentInitialization.class.getProtectionDomain().getCodeSource(); if (codeSource == null) { return null; } URI jarFileURI; // URI is needed to deal with spaces and non-ASCII characters try { jarFileURI = codeSource.getLocation().toURI(); } catch (URISyntaxException e) { throw new RuntimeException(e); } return new File(jarFileURI).getPath(); } } ================================================ FILE: powermock-modules/powermock-module-javaagent/src/main/java/org/powermock/modules/agent/AgentLoader.java ================================================ /* * The JMockit Testing Toolkit * Copyright (c) 2006-2011 Rogério Liesenfeld * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.powermock.modules.agent; import com.sun.tools.attach.AgentInitializationException; import com.sun.tools.attach.AgentLoadException; import com.sun.tools.attach.AttachNotSupportedException; import com.sun.tools.attach.VirtualMachine; import com.sun.tools.attach.VirtualMachineDescriptor; import com.sun.tools.attach.spi.AttachProvider; import org.powermock.reflect.Whitebox; import sun.tools.attach.BsdVirtualMachine; import sun.tools.attach.LinuxVirtualMachine; import sun.tools.attach.SolarisVirtualMachine; import sun.tools.attach.WindowsVirtualMachine; import java.io.File; import java.io.IOException; import java.lang.management.ManagementFactory; import java.util.List; final class AgentLoader { private static final AttachProvider ATTACH_PROVIDER = new AttachProvider() { @Override public String name() { return null; } @Override public String type() { return null; } @Override public VirtualMachine attachVirtualMachine(String id) { return null; } @Override public List listVirtualMachines() { return null; } }; private final String jarFilePath; private final String pid; AgentLoader(String jarFilePath) { this.jarFilePath = jarFilePath; pid = discoverProcessIdForRunningVM(); } private static String discoverProcessIdForRunningVM() { String nameOfRunningVM = ManagementFactory.getRuntimeMXBean().getName(); int p = nameOfRunningVM.indexOf('@'); return nameOfRunningVM.substring(0, p); } boolean loadAgent() { VirtualMachine vm; if (AttachProvider.providers().isEmpty()) { vm = getVirtualMachineImplementationFromEmbeddedOnes(); } else { vm = attachToThisVM(); } if (vm != null) { loadAgentAndDetachFromThisVM(vm); return true; } return false; } @SuppressWarnings("UseOfSunClasses") private VirtualMachine getVirtualMachineImplementationFromEmbeddedOnes() { try { Class vmClass; if (File.separatorChar == '\\') { vmClass = WindowsVirtualMachine.class; } else { String osName = System.getProperty("os.name"); if (osName.startsWith("Linux") || osName.startsWith("LINUX")) { vmClass = LinuxVirtualMachine.class; } else if (osName.startsWith("Mac OS X")) { vmClass = BsdVirtualMachine.class; } else if (osName.startsWith("Solaris")) { vmClass = SolarisVirtualMachine.class; } else { return null; } } // This is only done with Reflection to avoid the JVM pre-loading all the XyzVirtualMachine classes. Class[] parameterTypes = {AttachProvider.class, String.class}; VirtualMachine newVM = null; try { newVM = Whitebox.invokeConstructor(vmClass, parameterTypes, new Object[]{ATTACH_PROVIDER, pid}); } catch (Exception e) { throw new RuntimeException(e); } return newVM; } catch (UnsatisfiedLinkError e) { throw new IllegalStateException("Native library for Attach API not available in this JRE", e); } } private VirtualMachine attachToThisVM() { try { return VirtualMachine.attach(pid); } catch (AttachNotSupportedException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } } private void loadAgentAndDetachFromThisVM(VirtualMachine vm) { try { vm.loadAgent(jarFilePath, null); vm.detach(); } catch (AgentLoadException e) { throw new RuntimeException(e); } catch (AgentInitializationException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } } } ================================================ FILE: powermock-modules/powermock-module-javaagent/src/main/java/org/powermock/modules/agent/DefinalizingClassTransformer.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.modules.agent; import net.bytebuddy.jar.asm.ClassReader; import net.bytebuddy.jar.asm.ClassWriter; import java.lang.instrument.ClassFileTransformer; import java.security.ProtectionDomain; public class DefinalizingClassTransformer extends AbstractClassTransformer implements ClassFileTransformer { private static final int NO_FLAGS_OR_OPTIONS = 0; public byte[] transform(ClassLoader loader, String className, Class classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) { if (loader == null || shouldIgnore(className)) { return null; } final ClassReader reader = new ClassReader(classfileBuffer); final ClassWriter writer = new ClassWriter(NO_FLAGS_OR_OPTIONS); reader.accept(new DefinalizingClassVisitor(writer), NO_FLAGS_OR_OPTIONS); return writer.toByteArray(); } } ================================================ FILE: powermock-modules/powermock-module-javaagent/src/main/java/org/powermock/modules/agent/DefinalizingClassVisitor.java ================================================ package org.powermock.modules.agent; import net.bytebuddy.jar.asm.ClassVisitor; import net.bytebuddy.jar.asm.MethodVisitor; import net.bytebuddy.jar.asm.Opcodes; class DefinalizingClassVisitor extends ClassVisitor { public DefinalizingClassVisitor(ClassVisitor classVisitor) { super(Opcodes.ASM5, classVisitor); } @Override public void visit(final int version, final int access, final String name, final String signature, final String superName, final String[] interfaces) { final int accessModifiersWithFinalRemoved = removeFinal(access); super.visit(version, accessModifiersWithFinalRemoved, name, signature, superName, interfaces); } @Override public MethodVisitor visitMethod(int access, final String name, final String desc, final String signature, final String[] exceptions) { return super.visitMethod(removeFinal(access), name, desc, signature, exceptions); } @Override public void visitInnerClass(String name, String outerName, String innerName, int access) { super.visitInnerClass(name, outerName, innerName, removeFinal(access)); } private int removeFinal(int access) { return access & ~Opcodes.ACC_FINAL; } } ================================================ FILE: powermock-modules/powermock-module-javaagent/src/main/java/org/powermock/modules/agent/PowerMockAgent.java ================================================ /* * The JMockit Testing Toolkit * Copyright (c) 2006-2011 Rogério Liesenfeld * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.powermock.modules.agent; import org.powermock.utils.JavaVersion; import java.io.IOException; import java.lang.instrument.Instrumentation; /** * This is the "agent class" that initializes the PowerMock "Java agent". It is not intended for use in client code. * It must be public, however, so the JVM can call the {@code premain} method, which as the name implies is called * before the {@code main} method. * * @see #premain(String, Instrumentation) */ public final class PowerMockAgent { static final String javaSpecVersion = System.getProperty("java.specification.version"); static final boolean jdk6OrLater = JavaVersion.JAVA_RECENT.atLeast(JavaVersion.JAVA_1_6); private static final PowerMockClassTransformer classTransformer = new PowerMockClassTransformer(); private static Instrumentation instrumentation; private PowerMockAgent() {} /** * This method must only be called by the JVM, to provide the instrumentation object. * In order for this to occur, the JVM must be started with "-javaagent:powermock-module-javaagent-nnn.jar" as a command line parameter * (assuming the jar file is in the current directory). * */ public static void premain(String agentArgs, Instrumentation inst) throws Exception { initialize(agentArgs, inst); } @SuppressWarnings({"UnusedDeclaration"}) public static void agentmain(String agentArgs, Instrumentation inst) throws Exception { initialize(agentArgs, inst); } private static void initialize(String agentArgs, Instrumentation inst) throws IOException { instrumentation = inst; inst.addTransformer(new DefinalizingClassTransformer(), false); inst.addTransformer(classTransformer, true); } public static PowerMockClassTransformer getClasstransformer() { return classTransformer; } public static Instrumentation instrumentation() { verifyInitialization(); return instrumentation; } public static void verifyInitialization() { if (instrumentation == null) { new AgentInitialization().initializeAccordingToJDKVersion(); } } public static boolean initializeIfNeeded() { if (instrumentation == null) { try { new AgentInitialization().initializeAccordingToJDKVersion(); return true; } catch (RuntimeException e) { e.printStackTrace(); // makes sure the exception gets printed at least once throw e; } } return false; } public static void initializeIfPossible() { if (jdk6OrLater) { initializeIfNeeded(); } } } ================================================ FILE: powermock-modules/powermock-module-javaagent/src/main/java/org/powermock/modules/agent/PowerMockClassRedefiner.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.modules.agent; import org.powermock.core.agent.JavaAgentClassRegister; import java.util.Arrays; public class PowerMockClassRedefiner { public static void redefine(String[] classes, String[] packagesToIgnore, JavaAgentClassRegister agentClassRegister) { PowerMockClassTransformer transformer = PowerMockAgent.getClasstransformer(); transformer.setClassesToTransform(Arrays.asList(classes)); transformer.setPackagesToIgnore(Arrays.asList(packagesToIgnore)); transformer.setJavaAgentClassRegister(agentClassRegister); try { for (int i = classes.length - 1; i >= 0; i--) { String className = classes[i]; Class clazz; try { clazz = Class.forName(className); PowerMockAgent.instrumentation().retransformClasses(clazz); } catch (Exception e) { throw new RuntimeException(e); } } } finally { transformer.resetPackagesToIgnore(); } } } ================================================ FILE: powermock-modules/powermock-module-javaagent/src/main/java/org/powermock/modules/agent/PowerMockClassTransformer.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.modules.agent; import javassist.ClassPool; import javassist.CtClass; import org.powermock.core.agent.JavaAgentClassRegister; import org.powermock.core.transformers.ClassWrapper; import org.powermock.core.transformers.ClassWrapperFactory; import org.powermock.core.transformers.MockTransformerChain; import org.powermock.core.transformers.TransformStrategy; import org.powermock.core.transformers.javassist.JavassistMockTransformerChainFactory; import org.powermock.core.transformers.javassist.support.JavaAssistClassWrapperFactory; import java.io.ByteArrayInputStream; import java.io.IOException; import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.IllegalClassFormatException; import java.security.ProtectionDomain; import java.util.Collection; import java.util.HashSet; import java.util.Set; class PowerMockClassTransformer extends AbstractClassTransformer implements ClassFileTransformer { private static final MockTransformerChain MOCK_TRANSFORMER_CHAIN = new JavassistMockTransformerChainFactory() .createDefaultChain(TransformStrategy.INST_REDEFINE); private final ClassWrapperFactory wrapperFactory; private volatile Set classesToTransform; private volatile JavaAgentClassRegister javaAgentClassRegister; PowerMockClassTransformer() { super(); wrapperFactory = new JavaAssistClassWrapperFactory(); } public void setClassesToTransform(Collection classesToTransform) { this.classesToTransform = new HashSet(classesToTransform); } public void setJavaAgentClassRegister(JavaAgentClassRegister javaAgentClassRegister) { this.javaAgentClassRegister = javaAgentClassRegister; } public byte[] transform( ClassLoader loader, String className, Class classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer ) throws IllegalClassFormatException { if (loader == null || shouldIgnore(className)) { return null; } try { String normalizedClassName = className.replace("/", "."); if (classesToTransform != null && classesToTransform.contains(normalizedClassName)) { CtClass ctClass = getCtClass(classfileBuffer); ctClass = transform(ctClass); /* * ClassPool may cause huge memory consumption if the number of CtClass * objects becomes amazingly large (this rarely happens since Javassist * tries to reduce memory consumption in various ways). To avoid this * problem, you can explicitly remove an unnecessary CtClass object from * the ClassPool. If you call detach() on a CtClass object, then that * CtClass object is removed from the ClassPool. */ ctClass.detach(); javaAgentClassRegister.registerClass(loader, normalizedClassName); return ctClass.toBytecode(); } return null; } catch (Exception e) { throw new RuntimeException("Failed to redefine class " + className, e); } } private CtClass getCtClass(final byte[] classfileBuffer) throws IOException { final CtClass ctClass; ByteArrayInputStream is = new ByteArrayInputStream(classfileBuffer); try { ctClass = ClassPool.getDefault().makeClass(is); } finally { is.close(); } return ctClass; } private CtClass transform(CtClass ctClass) throws Exception { ClassWrapper wrapped = wrapperFactory.wrap(ctClass); wrapped = MOCK_TRANSFORMER_CHAIN.transform(wrapped); return wrapped.unwrap(); } } ================================================ FILE: powermock-modules/powermock-module-javaagent/src/main/java/org/powermock/modules/agent/support/JavaAgentClassRegisterImpl.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.modules.agent.support; import org.powermock.core.agent.JavaAgentClassRegister; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * Basic not thread-safety implementation of the {@link JavaAgentClassRegister} */ public class JavaAgentClassRegisterImpl implements JavaAgentClassRegister { private final Map> modifiedClasses; public JavaAgentClassRegisterImpl() { modifiedClasses = new HashMap>(); } @Override public boolean isModifiedByAgent(ClassLoader classLoader, String className) { return modifiedClasses.containsKey(classLoader) && modifiedClasses.get(classLoader).contains(className); } @Override public void registerClass(ClassLoader loader, String className) { Set names = modifiedClasses.get(loader); if (names == null){ names = new HashSet(); modifiedClasses.put(loader, names); } names.add(className); } @Override public void clear() { modifiedClasses.clear(); } } ================================================ FILE: powermock-modules/powermock-module-javaagent/src/main/java/org/powermock/modules/agent/support/PowerMockAgentTestInitializer.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.modules.agent.support; import org.powermock.core.MockRepository; import org.powermock.core.agent.JavaAgentClassRegister; import org.powermock.modules.agent.PowerMockClassRedefiner; import org.powermock.tests.utils.impl.MockPolicyInitializerImpl; import org.powermock.tests.utils.impl.PowerMockIgnorePackagesExtractorImpl; import org.powermock.tests.utils.impl.PrepareForTestExtractorImpl; import org.powermock.tests.utils.impl.StaticConstructorSuppressExtractorImpl; public class PowerMockAgentTestInitializer { public static void initialize(Class testClass, JavaAgentClassRegister agentClassRegister) { /* * For extra safety clear the MockitoRepository. */ MockRepository.clear(); redefineClasses(testClass, agentClassRegister); final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); new MockPolicyInitializerImpl(testClass).initialize(contextClassLoader); } private static void redefineClasses(Class testClass, JavaAgentClassRegister agentClassRegister) { final String[] packagesToIgnore = new PowerMockIgnorePackagesExtractorImpl().getPackagesToIgnore(testClass); redefineClassesToPrepare(testClass, packagesToIgnore, agentClassRegister); redefineClassesToSuppress(testClass, packagesToIgnore, agentClassRegister); } private static void redefineClassesToSuppress(Class testClass, String[] packagesToIgnore, JavaAgentClassRegister agentClassRegister) { final String[] classesToSuppress = new StaticConstructorSuppressExtractorImpl().getTestClasses(testClass); redefine(classesToSuppress, packagesToIgnore, agentClassRegister); } private static void redefineClassesToPrepare(Class testClass, String[] packagesToIgnore, JavaAgentClassRegister agentClassRegister) { final String[] classesToPrepare = new PrepareForTestExtractorImpl(true).getTestClasses(testClass); redefine(classesToPrepare, packagesToIgnore, agentClassRegister); } private static void redefine(String[] classes, String[] packagesToIgnore, JavaAgentClassRegister agentClassRegister) { PowerMockClassRedefiner.redefine(classes, packagesToIgnore, agentClassRegister); } } ================================================ FILE: powermock-modules/powermock-module-javaagent/src/main/java/sun/tools/attach/BsdVirtualMachine.java ================================================ /* * Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package sun.tools.attach; import com.sun.tools.attach.AgentLoadException; import com.sun.tools.attach.AttachNotSupportedException; import com.sun.tools.attach.spi.AttachProvider; import java.io.File; import java.io.IOException; import java.io.InputStream; /* * Bsd implementation of HotSpotVirtualMachine */ public class BsdVirtualMachine extends HotSpotVirtualMachine { // "tmpdir" is used as a global well-known location for the files // .java_pid. and .attach_pid. It is important that this // location is the same for all processes, otherwise the tools // will not be able to find all Hotspot processes. // This is intentionally not the same as java.io.tmpdir, since // the latter can be changed by the user. // Any changes to this needs to be synchronized with HotSpot. private static final String tmpdir; // The patch to the socket file created by the target VM String path; /** * Attaches to the target VM */ public BsdVirtualMachine(AttachProvider provider, String vmid) throws AttachNotSupportedException, IOException { super(provider, vmid); // This provider only understands pids int pid; try { pid = Integer.parseInt(vmid); } catch (NumberFormatException x) { throw new AttachNotSupportedException("Invalid process identifier"); } // Find the socket file. If not found then we attempt to start the // attach mechanism in the target VM by sending it a QUIT signal. // Then we attempt to find the socket file again. path = findSocketFile(pid); if (path == null) { File f = new File(tmpdir, ".attach_pid" + pid); createAttachFile(f.getPath()); try { sendQuitTo(pid); // give the target VM time to start the attach mechanism int i = 0; long delay = 200; int retries = (int)(attachTimeout() / delay); do { try { Thread.sleep(delay); } catch (InterruptedException x) { } path = findSocketFile(pid); i++; } while (i <= retries && path == null); if (path == null) { throw new AttachNotSupportedException( "Unable to open socket file: target process not responding " + "or HotSpot VM not loaded"); } } finally { f.delete(); } } // Check that the file owner/permission to avoid attaching to // bogus process checkPermissions(path); // Check that we can connect to the process // - this ensures we throw the permission denied error now rather than // later when we attempt to enqueue a command. int s = socket(); try { connect(s, path); } finally { close(s); } } /** * Detach from the target VM */ @Override public void detach() throws IOException { synchronized (this) { if (this.path != null) { this.path = null; } } } // protocol version private final static String PROTOCOL_VERSION = "1"; // known errors private final static int ATTACH_ERROR_BADVERSION = 101; /** * Execute the given command in the target VM. */ @Override InputStream execute(String cmd, Object ... args) throws AgentLoadException, IOException { assert args.length <= 3; // includes null // did we detach? String p; synchronized (this) { if (this.path == null) { throw new IOException("Detached from target VM"); } p = this.path; } // create UNIX socket int s = socket(); // connect to target VM try { connect(s, p); } catch (IOException x) { close(s); throw x; } IOException ioe = null; // connected - write request // try { writeString(s, PROTOCOL_VERSION); writeString(s, cmd); for (int i=0; i<3; i++) { if (i < args.length && args[i] != null) { writeString(s, (String)args[i]); } else { writeString(s, ""); } } } catch (IOException x) { ioe = x; } // Create an input stream to read reply SocketInputStream sis = new SocketInputStream(s); // Read the command completion status int completionStatus; try { completionStatus = readInt(sis); } catch (IOException x) { sis.close(); if (ioe != null) { throw ioe; } else { throw x; } } if (completionStatus != 0) { sis.close(); // In the event of a protocol mismatch then the target VM // returns a known error so that we can throw a reasonable // error. if (completionStatus == ATTACH_ERROR_BADVERSION) { throw new IOException("Protocol mismatch with target VM"); } // Special-case the "load" command so that the right exception is // thrown. if (cmd.equals("load")) { throw new AgentLoadException("Failed to load agent library"); } else { throw new IOException("Command failed in target VM"); } } // Return the input stream so that the command output can be read return sis; } /* * InputStream for the socket connection to get target VM */ private class SocketInputStream extends InputStream { int s; public SocketInputStream(int s) { this.s = s; } @Override public synchronized int read() throws IOException { byte b[] = new byte[1]; int n = this.read(b, 0, 1); if (n == 1) { return b[0] & 0xff; } else { return -1; } } @Override public synchronized int read(byte[] bs, int off, int len) throws IOException { if ((off < 0) || (off > bs.length) || (len < 0) || ((off + len) > bs.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException(); } else if (len == 0) return 0; return BsdVirtualMachine.read(s, bs, off, len); } @Override public void close() throws IOException { BsdVirtualMachine.close(s); } } // Return the socket file for the given process. // Checks temp directory for .java_pid. private String findSocketFile(int pid) { String fn = ".java_pid" + pid; File f = new File(tmpdir, fn); return f.exists() ? f.getPath() : null; } /* * Write/sends the given to the target VM. String is transmitted in * UTF-8 encoding. */ private void writeString(int fd, String s) throws IOException { if (s.length() > 0) { byte b[]; try { b = s.getBytes("UTF-8"); } catch (java.io.UnsupportedEncodingException x) { throw new InternalError(); } BsdVirtualMachine.write(fd, b, 0, b.length); } byte b[] = new byte[1]; b[0] = 0; write(fd, b, 0, 1); } //-- native methods static native void sendQuitTo(int pid) throws IOException; static native void checkPermissions(String path) throws IOException; static native int socket() throws IOException; static native void connect(int fd, String path) throws IOException; static native void close(int fd) throws IOException; static native int read(int fd, byte buf[], int off, int bufLen) throws IOException; static native void write(int fd, byte buf[], int off, int bufLen) throws IOException; static native void createAttachFile(String path); static native String getTempDir(); static { System.loadLibrary("attach"); tmpdir = getTempDir(); } } ================================================ FILE: powermock-modules/powermock-module-javaagent/src/main/java/sun/tools/attach/HotSpotVirtualMachine.java ================================================ /* * Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package sun.tools.attach; import com.sun.tools.attach.AgentInitializationException; import com.sun.tools.attach.AgentLoadException; import com.sun.tools.attach.VirtualMachine; import com.sun.tools.attach.spi.AttachProvider; import java.io.IOException; import java.io.InputStream; import java.util.Properties; /* * The HotSpot implementation of com.sun.tools.attach.VirtualMachine. */ public abstract class HotSpotVirtualMachine extends VirtualMachine { HotSpotVirtualMachine(AttachProvider provider, String id) { super(provider, id); } /* * Load agent library * If isAbsolute is true then the agent library is the absolute path * to the library and thus will not be expanded in the target VM. * if isAbsolute is false then the agent library is just a library * name and it will be expended in the target VM. */ private void loadAgentLibrary(String agentLibrary, boolean isAbsolute, String options) throws AgentLoadException, AgentInitializationException, IOException { InputStream in = execute("load", agentLibrary, isAbsolute ? "true" : "false", options); try { int result = readInt(in); if (result != 0) { throw new AgentInitializationException("Agent_OnAttach failed", result); } } finally { in.close(); } } /* * Load agent library - library name will be expanded in target VM */ @Override public void loadAgentLibrary(String agentLibrary, String options) throws AgentLoadException, AgentInitializationException, IOException { loadAgentLibrary(agentLibrary, false, options); } /* * Load agent - absolute path of library provided to target VM */ @Override public void loadAgentPath(String agentLibrary, String options) throws AgentLoadException, AgentInitializationException, IOException { loadAgentLibrary(agentLibrary, true, options); } /* * Load JPLIS agent which will load the agent JAR file and invoke * the agentmain method. */ @Override public void loadAgent(String agent, String options) throws AgentLoadException, AgentInitializationException, IOException { String args = agent; if (options != null) { args = args + "=" + options; } try { loadAgentLibrary("instrument", args); } catch (AgentLoadException x) { throw new InternalError("instrument library is missing in target VM"); } catch (AgentInitializationException x) { /* * Translate interesting errors into the right exception and * message (FIXME: create a better interface to the instrument * implementation so this isn't necessary) */ int rc = x.returnValue(); switch (rc) { case JNI_ENOMEM: throw new AgentLoadException("Insuffient memory"); case ATTACH_ERROR_BADJAR: throw new AgentLoadException("Agent JAR not found or no Agent-Class attribute"); case ATTACH_ERROR_NOTONCP: throw new AgentLoadException("Unable to add JAR file to system class path"); case ATTACH_ERROR_STARTFAIL: throw new AgentInitializationException("Agent JAR loaded but agent failed to initialize"); default : throw new AgentLoadException("Failed to load agent - unknown reason: " + rc); } } } /* * The possible errors returned by JPLIS's agentmain */ private static final int JNI_ENOMEM = -4; private static final int ATTACH_ERROR_BADJAR = 100; private static final int ATTACH_ERROR_NOTONCP = 101; private static final int ATTACH_ERROR_STARTFAIL = 102; /* * Send "properties" command to target VM */ @Override public Properties getSystemProperties() throws IOException { InputStream in = null; Properties props = new Properties(); try { in = executeCommand("properties"); props.load(in); } finally { if (in != null) in.close(); } return props; } @Override public Properties getAgentProperties() throws IOException { InputStream in = null; Properties props = new Properties(); try { in = executeCommand("agentProperties"); props.load(in); } finally { if (in != null) in.close(); } return props; } // --- HotSpot specific methods --- // same as SIGQUIT public void localDataDump() throws IOException { executeCommand("datadump").close(); } // Remote ctrl-break. The output of the ctrl-break actions can // be read from the input stream. public InputStream remoteDataDump(Object ... args) throws IOException { return executeCommand("threaddump", args); } // Remote heap dump. The output (error message) can be read from the // returned input stream. public InputStream dumpHeap(Object ... args) throws IOException { return executeCommand("dumpheap", args); } // Heap histogram (heap inspection in HotSpot) public InputStream heapHisto(Object ... args) throws IOException { return executeCommand("inspectheap", args); } // set JVM command line flag public InputStream setFlag(String name, String value) throws IOException { return executeCommand("setflag", name, value); } // print command line flag public InputStream printFlag(String name) throws IOException { return executeCommand("printflag", name); } public InputStream executeJCmd(String command) throws IOException { return executeCommand("jcmd", command); } // -- Supporting methods /* * Execute the given command in the target VM - specific platform * implementation must implement this. */ abstract InputStream execute(String cmd, Object ... args) throws AgentLoadException, IOException; /* * Convenience method for simple commands */ private InputStream executeCommand(String cmd, Object ... args) throws IOException { try { return execute(cmd, args); } catch (AgentLoadException x) { throw new InternalError("Should not get here"); } } /* * Utility method to read an 'int' from the input stream. Ideally * we should be using java.util.Scanner here but this implementation * guarantees not to read ahead. */ int readInt(InputStream in) throws IOException { StringBuilder sb = new StringBuilder(); // read to \n or EOF int n; byte buf[] = new byte[1]; do { n = in.read(buf, 0, 1); if (n > 0) { char c = (char)buf[0]; if (c == '\n') { break; // EOL found } else { sb.append(c); } } } while (n > 0); if (sb.length() == 0) { throw new IOException("Premature EOF"); } int value; try { value = Integer.parseInt(sb.toString()); } catch (NumberFormatException x) { throw new IOException("Non-numeric value found - int expected"); } return value; } // -- attach timeout support private static long defaultAttachTimeout = 5000; private volatile long attachTimeout; /* * Return attach timeout based on the value of the sun.tools.attach.attachTimeout * property, or the default timeout if the property is not set to a positive * value. */ final long attachTimeout() { if (attachTimeout == 0) { synchronized(this) { if (attachTimeout == 0) { try { String s = System.getProperty("sun.tools.attach.attachTimeout"); attachTimeout = Long.parseLong(s); } catch (SecurityException se) { } catch (NumberFormatException ne) { } if (attachTimeout <= 0) { attachTimeout = defaultAttachTimeout; } } } } return attachTimeout; } } ================================================ FILE: powermock-modules/powermock-module-javaagent/src/main/java/sun/tools/attach/LinuxVirtualMachine.java ================================================ /* * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package sun.tools.attach; import com.sun.tools.attach.AgentLoadException; import com.sun.tools.attach.AttachNotSupportedException; import com.sun.tools.attach.spi.AttachProvider; import java.io.File; import java.io.IOException; import java.io.InputStream; /* * Linux implementation of HotSpotVirtualMachine */ public class LinuxVirtualMachine extends HotSpotVirtualMachine { // "/tmp" is used as a global well-known location for the files // .java_pid. and .attach_pid. It is important that this // location is the same for all processes, otherwise the tools // will not be able to find all Hotspot processes. // Any changes to this needs to be synchronized with HotSpot. private static final String tmpdir = "/tmp"; // Indicates if this machine uses the old LinuxThreads static boolean isLinuxThreads; // The patch to the socket file created by the target VM String path; /** * Attaches to the target VM */ public LinuxVirtualMachine(AttachProvider provider, String vmid) throws AttachNotSupportedException, IOException { super(provider, vmid); // This provider only understands pids int pid; try { pid = Integer.parseInt(vmid); } catch (NumberFormatException x) { throw new AttachNotSupportedException("Invalid process identifier"); } // Find the socket file. If not found then we attempt to start the // attach mechanism in the target VM by sending it a QUIT signal. // Then we attempt to find the socket file again. path = findSocketFile(pid); if (path == null) { File f = createAttachFile(pid); try { // On LinuxThreads each thread is a process and we don't have the // pid of the VMThread which has SIGQUIT unblocked. To workaround // this we get the pid of the "manager thread" that is created // by the first call to pthread_create. This is parent of all // threads (except the initial thread). if (isLinuxThreads) { int mpid; try { mpid = getLinuxThreadsManager(pid); } catch (IOException x) { throw new AttachNotSupportedException(x.getMessage()); } assert(mpid >= 1); sendQuitToChildrenOf(mpid); } else { sendQuitTo(pid); } // give the target VM time to start the attach mechanism int i = 0; long delay = 200; int retries = (int)(attachTimeout() / delay); do { try { Thread.sleep(delay); } catch (InterruptedException x) { } path = findSocketFile(pid); i++; } while (i <= retries && path == null); if (path == null) { throw new AttachNotSupportedException( "Unable to open socket file: target process not responding " + "or HotSpot VM not loaded"); } } finally { f.delete(); } } // Check that the file owner/permission to avoid attaching to // bogus process checkPermissions(path); // Check that we can connect to the process // - this ensures we throw the permission denied error now rather than // later when we attempt to enqueue a command. int s = socket(); try { connect(s, path); } finally { close(s); } } /** * Detach from the target VM */ @Override public void detach() throws IOException { synchronized (this) { if (this.path != null) { this.path = null; } } } // protocol version private final static String PROTOCOL_VERSION = "1"; // known errors private final static int ATTACH_ERROR_BADVERSION = 101; /** * Execute the given command in the target VM. */ @Override InputStream execute(String cmd, Object ... args) throws AgentLoadException, IOException { assert args.length <= 3; // includes null // did we detach? String p; synchronized (this) { if (this.path == null) { throw new IOException("Detached from target VM"); } p = this.path; } // create UNIX socket int s = socket(); // connect to target VM try { connect(s, p); } catch (IOException x) { close(s); throw x; } IOException ioe = null; // connected - write request // try { writeString(s, PROTOCOL_VERSION); writeString(s, cmd); for (int i=0; i<3; i++) { if (i < args.length && args[i] != null) { writeString(s, (String)args[i]); } else { writeString(s, ""); } } } catch (IOException x) { ioe = x; } // Create an input stream to read reply SocketInputStream sis = new SocketInputStream(s); // Read the command completion status int completionStatus; try { completionStatus = readInt(sis); } catch (IOException x) { sis.close(); if (ioe != null) { throw ioe; } else { throw x; } } if (completionStatus != 0) { sis.close(); // In the event of a protocol mismatch then the target VM // returns a known error so that we can throw a reasonable // error. if (completionStatus == ATTACH_ERROR_BADVERSION) { throw new IOException("Protocol mismatch with target VM"); } // Special-case the "load" command so that the right exception is // thrown. if (cmd.equals("load")) { throw new AgentLoadException("Failed to load agent library"); } else { throw new IOException("Command failed in target VM"); } } // Return the input stream so that the command output can be read return sis; } /* * InputStream for the socket connection to get target VM */ private class SocketInputStream extends InputStream { int s; public SocketInputStream(int s) { this.s = s; } @Override public synchronized int read() throws IOException { byte b[] = new byte[1]; int n = this.read(b, 0, 1); if (n == 1) { return b[0] & 0xff; } else { return -1; } } @Override public synchronized int read(byte[] bs, int off, int len) throws IOException { if ((off < 0) || (off > bs.length) || (len < 0) || ((off + len) > bs.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException(); } else if (len == 0) return 0; return LinuxVirtualMachine.read(s, bs, off, len); } @Override public void close() throws IOException { LinuxVirtualMachine.close(s); } } // Return the socket file for the given process. private String findSocketFile(int pid) { File f = new File(tmpdir, ".java_pid" + pid); if (!f.exists()) { return null; } return f.getPath(); } // On Solaris/Linux a simple handshake is used to start the attach mechanism // if not already started. The client creates a .attach_pid file in the // target VM's working directory (or temp directory), and the SIGQUIT handler // checks for the file. private File createAttachFile(int pid) throws IOException { String fn = ".attach_pid" + pid; String path = "/proc/" + pid + "/cwd/" + fn; File f = new File(path); try { f.createNewFile(); } catch (IOException x) { f = new File(tmpdir, fn); f.createNewFile(); } return f; } /* * Write/sends the given to the target VM. String is transmitted in * UTF-8 encoding. */ private void writeString(int fd, String s) throws IOException { if (s.length() > 0) { byte b[]; try { b = s.getBytes("UTF-8"); } catch (java.io.UnsupportedEncodingException x) { throw new InternalError(); } LinuxVirtualMachine.write(fd, b, 0, b.length); } byte b[] = new byte[1]; b[0] = 0; write(fd, b, 0, 1); } //-- native methods static native boolean isLinuxThreads(); static native int getLinuxThreadsManager(int pid) throws IOException; static native void sendQuitToChildrenOf(int pid) throws IOException; static native void sendQuitTo(int pid) throws IOException; static native void checkPermissions(String path) throws IOException; static native int socket() throws IOException; static native void connect(int fd, String path) throws IOException; static native void close(int fd) throws IOException; static native int read(int fd, byte buf[], int off, int bufLen) throws IOException; static native void write(int fd, byte buf[], int off, int bufLen) throws IOException; static { System.loadLibrary("attach"); isLinuxThreads = isLinuxThreads(); } } ================================================ FILE: powermock-modules/powermock-module-javaagent/src/main/java/sun/tools/attach/SolarisVirtualMachine.java ================================================ /* * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package sun.tools.attach; import com.sun.tools.attach.AgentLoadException; import com.sun.tools.attach.AttachNotSupportedException; import com.sun.tools.attach.spi.AttachProvider; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; /* * Solaris implementation of HotSpotVirtualMachine. */ public class SolarisVirtualMachine extends HotSpotVirtualMachine { // "/tmp" is used as a global well-known location for the files // .java_pid. and .attach_pid. It is important that this // location is the same for all processes, otherwise the tools // will not be able to find all Hotspot processes. // Any changes to this needs to be synchronized with HotSpot. private static final String tmpdir = "/tmp"; // door descriptor; private int fd = -1; /** * Attaches to the target VM */ public SolarisVirtualMachine(AttachProvider provider, String vmid) throws AttachNotSupportedException, IOException { super(provider, vmid); // This provider only understands process-ids (pids). int pid; try { pid = Integer.parseInt(vmid); } catch (NumberFormatException x) { throw new AttachNotSupportedException("invalid process identifier"); } // Opens the door file to the target VM. If the file is not // found it might mean that the attach mechanism isn't started in the // target VM so we attempt to start it and retry. try { fd = openDoor(pid); } catch (FileNotFoundException fnf1) { File f = createAttachFile(pid); try { // kill -QUIT will tickle target VM to check for the // attach file. sigquit(pid); // give the target VM time to start the attach mechanism int i = 0; long delay = 200; int retries = (int)(attachTimeout() / delay); do { try { Thread.sleep(delay); } catch (InterruptedException x) { } try { fd = openDoor(pid); } catch (FileNotFoundException fnf2) { } i++; } while (i <= retries && fd == -1); if (fd == -1) { throw new AttachNotSupportedException( "Unable to open door: target process not responding or " + "HotSpot VM not loaded"); } } finally { f.delete(); } } assert fd >= 0; } /** * Detach from the target VM */ @Override public void detach() throws IOException { synchronized (this) { if (fd != -1) { close(fd); fd = -1; } } } /** * Execute the given command in the target VM. */ @Override InputStream execute(String cmd, Object ... args) throws AgentLoadException, IOException { assert args.length <= 3; // includes null // first check that we are still attached int door; synchronized (this) { if (fd == -1) { throw new IOException("Detached from target VM"); } door = fd; } // enqueue the command via a door call int s = enqueue(door, cmd, args); assert s >= 0; // valid file descriptor // The door call returns a file descriptor (one end of a socket pair). // Create an input stream around it. SocketInputStream sis = new SocketInputStream(s); // Read the command completion status int completionStatus; try { completionStatus = readInt(sis); } catch (IOException ioe) { sis.close(); throw ioe; } // If non-0 it means an error but we need to special-case the // "load" command to ensure that the right exception is thrown. if (completionStatus != 0) { sis.close(); if (cmd.equals("load")) { throw new AgentLoadException("Failed to load agent library"); } else { throw new IOException("Command failed in target VM"); } } // Return the input stream so that the command output can be read return sis; } // InputStream over a socket private class SocketInputStream extends InputStream { int s; public SocketInputStream(int s) { this.s = s; } @Override public synchronized int read() throws IOException { byte b[] = new byte[1]; int n = this.read(b, 0, 1); if (n == 1) { return b[0] & 0xff; } else { return -1; } } @Override public synchronized int read(byte[] bs, int off, int len) throws IOException { if ((off < 0) || (off > bs.length) || (len < 0) || ((off + len) > bs.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException(); } else if (len == 0) return 0; return SolarisVirtualMachine.read(s, bs, off, len); } @Override public void close() throws IOException { SolarisVirtualMachine.close(s); } } // The door is attached to .java_pid in the temporary directory. private int openDoor(int pid) throws IOException { String path = tmpdir + "/.java_pid" + pid;; fd = open(path); // Check that the file owner/permission to avoid attaching to // bogus process try { checkPermissions(path); } catch (IOException ioe) { close(fd); throw ioe; } return fd; } // On Solaris/Linux a simple handshake is used to start the attach mechanism // if not already started. The client creates a .attach_pid file in the // target VM's working directory (or temporary directory), and the SIGQUIT // handler checks for the file. private File createAttachFile(int pid) throws IOException { String fn = ".attach_pid" + pid; String path = "/proc/" + pid + "/cwd/" + fn; File f = new File(path); try { f.createNewFile(); } catch (IOException x) { f = new File(tmpdir, fn); f.createNewFile(); } return f; } //-- native methods static native int open(String path) throws IOException; static native void close(int fd) throws IOException; static native int read(int fd, byte buf[], int off, int buflen) throws IOException; static native void checkPermissions(String path) throws IOException; static native void sigquit(int pid) throws IOException; // enqueue a command (and arguments) to the given door static native int enqueue(int fd, String cmd, Object ... args) throws IOException; static { System.loadLibrary("attach"); } } ================================================ FILE: powermock-modules/powermock-module-javaagent/src/main/java/sun/tools/attach/WindowsVirtualMachine.java ================================================ /* * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package sun.tools.attach; import com.sun.tools.attach.AgentLoadException; import com.sun.tools.attach.AttachNotSupportedException; import com.sun.tools.attach.spi.AttachProvider; import java.io.IOException; import java.io.InputStream; import java.util.Random; public class WindowsVirtualMachine extends HotSpotVirtualMachine { // the enqueue code stub (copied into each target VM) private static byte[] stub; private volatile long hProcess; // handle to the process public WindowsVirtualMachine(AttachProvider provider, String id) throws AttachNotSupportedException, IOException { super(provider, id); int pid; try { pid = Integer.parseInt(id); } catch (NumberFormatException x) { throw new AttachNotSupportedException("Invalid process identifier"); } hProcess = openProcess(pid); // The target VM might be a pre-6.0 VM so we enqueue a "null" command // which minimally tests that the enqueue function exists in the target // VM. try { enqueue(hProcess, stub, null, null); } catch (IOException x) { throw new AttachNotSupportedException(x.getMessage()); } } @Override public void detach() throws IOException { synchronized (this) { if (hProcess != -1) { closeProcess(hProcess); hProcess = -1; } } } @Override InputStream execute(String cmd, Object ... args) throws AgentLoadException, IOException { assert args.length <= 3; // includes null // create a pipe using a random name int r = (new Random()).nextInt(); String pipename = "\\\\.\\pipe\\javatool" + r; long hPipe = createPipe(pipename); // check if we are detached - in theory it's possible that detach is invoked // after this check but before we enqueue the command. if (hProcess == -1) { closePipe(hPipe); throw new IOException("Detached from target VM"); } try { // enqueue the command to the process enqueue(hProcess, stub, cmd, pipename, args); // wait for command to complete - process will connect with the // completion status connectPipe(hPipe); // create an input stream for the pipe PipedInputStream is = new PipedInputStream(hPipe); // read completion status int status = readInt(is); if (status != 0) { // special case the load command so that the right exception is thrown if (cmd.equals("load")) { throw new AgentLoadException("Failed to load agent library"); } else { throw new IOException("Command failed in target VM"); } } // return the input stream return is; } catch (IOException ioe) { closePipe(hPipe); throw ioe; } } // An InputStream based on a pipe to the target VM private class PipedInputStream extends InputStream { private long hPipe; public PipedInputStream(long hPipe) { this.hPipe = hPipe; } @Override public synchronized int read() throws IOException { byte b[] = new byte[1]; int n = this.read(b, 0, 1); if (n == 1) { return b[0] & 0xff; } else { return -1; } } @Override public synchronized int read(byte[] bs, int off, int len) throws IOException { if ((off < 0) || (off > bs.length) || (len < 0) || ((off + len) > bs.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException(); } else if (len == 0) return 0; return WindowsVirtualMachine.readPipe(hPipe, bs, off, len); } @Override public void close() throws IOException { if (hPipe != -1) { WindowsVirtualMachine.closePipe(hPipe); hPipe = -1; } } } //-- native methods static native void init(); static native byte[] generateStub(); static native long openProcess(int pid) throws IOException; static native void closeProcess(long hProcess) throws IOException; static native long createPipe(String name) throws IOException; static native void closePipe(long hPipe) throws IOException; static native void connectPipe(long hPipe) throws IOException; static native int readPipe(long hPipe, byte buf[], int off, int buflen) throws IOException; static native void enqueue(long hProcess, byte[] stub, String cmd, String pipename, Object ... args) throws IOException; static { System.loadLibrary("attach"); init(); // native initialization stub = generateStub(); // generate stub to copy into target process } } ================================================ FILE: powermock-modules/powermock-module-javaagent/src/main/javadoc/resources/org,powermock/modules/agent/package.html ================================================ PowerMock Java Agent package The PowerMock agent classes. The PowerMock agent solution is based on the excellent work of Rogério Liesenfeld, founder of JMockit. JMockit license: The JMockit Testing Toolkit Copyright (c) 2006-2011 Rogério Liesenfeld Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: powermock-modules/powermock-module-junit4/src/main/java/org/powermock/modules/junit4/PowerMockRunner.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.modules.junit4; import org.junit.runner.Description; import org.junit.runner.notification.RunNotifier; import org.powermock.modules.junit4.common.internal.PowerMockJUnitRunnerDelegate; import org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner; import org.powermock.modules.junit4.common.internal.impl.JUnitVersion; import org.powermock.modules.junit4.internal.impl.DelegatingPowerMockRunner; import org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl; import org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl; import org.powermock.modules.junit4.internal.impl.PowerMockJUnit49RunnerDelegateImpl; import org.powermock.reflect.Whitebox; import java.lang.annotation.Annotation; public class PowerMockRunner extends AbstractCommonPowerMockRunner { public PowerMockRunner(Class klass) throws Exception { super(klass, getRunnerDelegateImplClass(klass)); } private static Class getRunnerDelegateImplClass(Class klass) { if (klass.isAnnotationPresent(PowerMockRunnerDelegate.class) || Boolean.getBoolean("powermock.implicitDelegateAnnotation")) { return DelegatingPowerMockRunner.class; } Class concreteClass = PowerMockJUnit44RunnerDelegateImpl.class; if(JUnitVersion.isGreaterThanOrEqualTo("4.9")) { concreteClass = PowerMockJUnit49RunnerDelegateImpl.class; } else if( JUnitVersion.isGreaterThanOrEqualTo("4.7") ) { concreteClass = PowerMockJUnit47RunnerDelegateImpl.class; } return concreteClass; } /** * Clean up some state to avoid OOM issues */ @Override public void run(RunNotifier notifier) { Description description = getDescription(); try { super.run(notifier); } finally { Whitebox.setInternalState(description, "fAnnotations", new Annotation[]{}); } } } ================================================ FILE: powermock-modules/powermock-module-junit4/src/main/java/org/powermock/modules/junit4/PowerMockRunnerDelegate.java ================================================ /* * Copyright 2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.modules.junit4; import org.junit.internal.builders.AllDefaultPossibilitiesBuilder; import org.junit.internal.runners.JUnit38ClassRunner; import org.junit.internal.runners.JUnit4ClassRunner; import org.junit.runner.Description; import org.junit.runner.Runner; import org.junit.runner.notification.RunNotifier; import org.junit.runners.AllTests; import org.junit.runners.JUnit4; import org.junit.runners.model.InitializationError; import org.junit.runners.model.RunnerBuilder; import org.powermock.modules.junit4.common.internal.impl.JUnitVersion; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; @Target(ElementType.TYPE) @Documented @Retention(RetentionPolicy.RUNTIME) @Inherited public @interface PowerMockRunnerDelegate { Class value() default DefaultJUnitRunner.class; public final class DefaultJUnitRunner extends Runner { private final Runner wrappedDefaultRunner; public DefaultJUnitRunner(Class testClass) throws Throwable { wrappedDefaultRunner = createDefaultRunner(testClass); } private static Runner createDefaultRunner(Class testClass) throws Throwable { try { Method suiteMethod = testClass.getMethod("suite"); if (junit.framework.Test.class.isAssignableFrom(suiteMethod.getReturnType())) { return new AllTests(testClass); } else { /* Continue below ... */ } } catch (NoSuchMethodException thereIsNoSuiteMethod) { /* Continue below ... */ } if (junit.framework.TestCase.class.isAssignableFrom(testClass)) { return new JUnit38ClassRunner(testClass); } else if (JUnitVersion.isGreaterThanOrEqualTo("4.5")) { return SinceJUnit_4_5.createRunnerDelegate(testClass); } else { return new JUnit4ClassRunner(testClass); } } @Override public Description getDescription() { return wrappedDefaultRunner.getDescription(); } @Override public void run(RunNotifier notifier) { wrappedDefaultRunner.run(notifier); } } /** * Stuff that needs to be handled in a separate class, because it * deals with API that did not exist before JUnit-4.5. Having this inside * {@link DefaultJUnitRunner} would cause runtime error when JUnit-4.4 * or earlier is used. */ public class SinceJUnit_4_5 { static Runner createRunnerDelegate(Class testClass) throws InitializationError { return new JUnit4(testClass); } public static Class[] runnerAlternativeConstructorParams() { return new Class[] {Class.class, RunnerBuilder.class}; } public static Object newRunnerBuilder() { return new AllDefaultPossibilitiesBuilder(false); } } } ================================================ FILE: powermock-modules/powermock-module-junit4/src/main/java/org/powermock/modules/junit4/internal/impl/DelegatingPowerMockRunner.java ================================================ /* * Copyright 2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.modules.junit4.internal.impl; import org.junit.Test; import org.junit.experimental.theories.Theory; import org.junit.runner.Description; import org.junit.runner.Runner; import org.junit.runner.manipulation.Filter; import org.junit.runner.manipulation.Filterable; import org.junit.runner.manipulation.NoTestsRemainException; import org.junit.runner.notification.RunNotifier; import org.powermock.core.spi.PowerMockTestListener; import org.powermock.core.testlisteners.GlobalNotificationBuildSupport; import org.powermock.modules.junit4.PowerMockRunnerDelegate; import org.powermock.modules.junit4.PowerMockRunnerDelegate.SinceJUnit_4_5; import org.powermock.modules.junit4.common.internal.PowerMockJUnitRunnerDelegate; import org.powermock.modules.junit4.common.internal.impl.JUnitVersion; import org.powermock.reflect.Whitebox; import org.powermock.reflect.exceptions.ConstructorNotFoundException; import org.powermock.tests.utils.PowerMockTestNotifier; import org.powermock.tests.utils.impl.PowerMockTestNotifierImpl; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; public class DelegatingPowerMockRunner extends Runner implements PowerMockJUnitRunnerDelegate, Filterable { private final String testClassName; private final Runner delegate; private final ClassLoader testClassLoader; private final Method[] testMethods; private final PowerMockTestNotifier powerMockTestNotifier; public DelegatingPowerMockRunner(Class klass) throws Throwable { this(klass, null); } public DelegatingPowerMockRunner(Class klass, String[] methodsToRun) throws Throwable { this(klass, methodsToRun, null); } public DelegatingPowerMockRunner( Class klass, String[] methodsToRun, PowerMockTestListener[] listeners) throws Exception { testClassName = klass.getName(); delegate = createDelegate(klass); testClassLoader = klass.getClassLoader(); testMethods = determineTestMethods(klass, methodsToRun); powerMockTestNotifier = new PowerMockTestNotifierImpl(listeners == null ? new PowerMockTestListener[0] : listeners); } private static Method[] determineTestMethods( Class testClass, String[] testMethodNames) { List testMethods = new ArrayList(); for (Method m : testClass.getMethods()) { if (m.isAnnotationPresent(Test.class) || m.isAnnotationPresent(Theory.class)) { testMethods.add(m); } } if (testMethods.isEmpty()) { for (String testMethodName : testMethodNames) { try { testMethods.add(testClass.getMethod(testMethodName)); } catch (NoSuchMethodException ignore) { System.err.println(ignore.getMessage()); } } } return testMethods.toArray(new Method[testMethods.size()]); } private static Runner createDelegate(final Class testClass) throws Exception { /* * Because of the mockito integration it seems like it is necessary to * set context classloader during delegate creation ... */ return withContextClassLoader(testClass.getClassLoader(), new Callable() { @Override public Runner call() throws Exception { try { return Whitebox.invokeConstructor( testClass.isAnnotationPresent(PowerMockRunnerDelegate.class) ? testClass.getAnnotation(PowerMockRunnerDelegate.class).value() : PowerMockRunnerDelegate.DefaultJUnitRunner.class, new Class[] {Class.class}, new Object[] {testClass}); } catch (ConstructorNotFoundException rootProblem) { if (testClass.isAnnotationPresent(PowerMockRunnerDelegate.class) && JUnitVersion.isGreaterThanOrEqualTo("4.5")) { try { return Whitebox.invokeConstructor(testClass.getAnnotation(PowerMockRunnerDelegate.class).value(), SinceJUnit_4_5.runnerAlternativeConstructorParams(), new Object[] { testClass, SinceJUnit_4_5.newRunnerBuilder() }); } catch (ConstructorNotFoundException ignoredWorkAroundFailure) { } } throw rootProblem; } } }); } private static T withContextClassLoader( ClassLoader loader, Callable callable) throws Exception { final ClassLoader originalClassLoaderBackup = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(loader); return callable.call(); } finally { Thread.currentThread().setContextClassLoader(originalClassLoaderBackup); } } @Override public void run(final RunNotifier notifier) { try { withContextClassLoader(testClassLoader, new Callable() { @Override public Void call() { PowerMockRunNotifier powerNotifier = new PowerMockRunNotifier( notifier, powerMockTestNotifier, testMethods); try { GlobalNotificationBuildSupport.prepareTestSuite( testClassName, powerNotifier); delegate.run(powerNotifier); } finally { GlobalNotificationBuildSupport .closePendingTestSuites(powerNotifier); } return null; } }); } catch (Exception cannotHappen) { throw new Error(cannotHappen); } } @Override public Description getDescription() { return delegate.getDescription(); } @Override public int getTestCount() { return delegate.testCount(); } @Override public Class getTestClass() { return getDescription().getTestClass(); } @Override public void filter(Filter filter) throws NoTestsRemainException { if (this.delegate instanceof Filterable) { ((Filterable) this.delegate).filter(filter); } } } ================================================ FILE: powermock-modules/powermock-module-junit4/src/main/java/org/powermock/modules/junit4/internal/impl/NotificationBuilder.java ================================================ /* * Copyright 2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.modules.junit4.internal.impl; import org.junit.runner.Description; import org.junit.runner.notification.Failure; import org.powermock.core.spi.testresult.Result; import org.powermock.core.spi.testresult.TestMethodResult; import org.powermock.tests.utils.PowerMockTestNotifier; import org.powermock.tests.utils.impl.MockPolicyInitializerImpl; import java.lang.reflect.Array; import java.lang.reflect.Method; import java.util.IdentityHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Stateful class that, from information from JUnit and test-classes, * can build and send notifications to PowerMockTestNotifier. */ class NotificationBuilder { enum DetectedTestRunBehaviour { PENDING, START_FIRES_FIRST, TEST_INSTANCE_CREATED_FIRST, ALL_TESTINSTANCES_ARE_CREATED_FIRST, TEST_INSTANCES_ARE_REUSED, INCONSISTENT_BEHAVIOUR; } private static final Pattern methodDisplayNameRgx = Pattern.compile("(^[^\\(\\[]++)|([^(]+(?=\\)))"); private final Method[] testMethods; private final List pendingTestInstances; private final PowerMockTestNotifier powerMockTestNotifier; private DetectedTestRunBehaviour behaviour = DetectedTestRunBehaviour.PENDING; private Description currentDescription; private Object currentTestInstance; private String testClassName; private Object latestTestInstance; private Method latestMethod; private static final Object[] unsupportedMethodArgs = {}; private final Map> methodsPerInstance = new IdentityHashMap>() { @Override public List get(Object key) { if (!containsKey(key)) { put(key, new LinkedList()); } return super.get(key); } }; private final Map ongoingTestRuns = new IdentityHashMap(); private class OngoingTestRun implements TestMethodResult { final Description testDescription; final Object testInstance; final Method testMethod; private Result result; OngoingTestRun(Description testDescription, Object testInstance) { this.testDescription = testDescription; this.testInstance = testInstance; this.testMethod = determineTestMethod(testDescription); pendingTestInstances.remove(testInstance); Class testClass = testClass(); new MockPolicyInitializerImpl(testClass).initialize(testClass.getClassLoader()); powerMockTestNotifier.notifyBeforeTestMethod( testInstance, testMethod, unsupportedMethodArgs); ongoingTestRuns.put(testDescription, this); } final Class testClass() { if (null == testClassName) { return testInstance.getClass(); } else { try { return Class.forName(testClassName, false, testInstance.getClass().getClassLoader()); } catch (ClassNotFoundException ex) { return testInstance.getClass(); } } } void report(Result result) { if (null != this.result && Result.SUCCESSFUL == result || this.result == result) { /* Already notified - ignore this duplication */ return; } else if (null != this.result) { new IllegalStateException( "Will report an unexpected result-notification " + result + " after previously received notification " + this.result) .printStackTrace(); } this.result = result; powerMockTestNotifier.notifyAfterTestMethod( testInstance, testMethod, unsupportedMethodArgs, this); } @Override public Result getResult() { return this.result; } } public NotificationBuilder(Method[] testMethods, PowerMockTestNotifier notifier, List pendingTestInstances) { this.testMethods = testMethods; this.pendingTestInstances = pendingTestInstances; this.powerMockTestNotifier = notifier; } private Method determineTestMethod(Description d) { Matcher matchMethodName = methodDisplayNameRgx .matcher(d.getDisplayName()); matchMethodName.find(); String methodName = matchMethodName.group(); boolean latestTestMethodCanBeRepeated = false; for (Method m : testMethods) { if (m.getName().equals(methodName)) { if (m == latestMethod) { latestTestMethodCanBeRepeated = true; } else { return latestMethod = m; } } } if (latestTestMethodCanBeRepeated) { return latestMethod; } else { new IllegalArgumentException( "Unable to determine method-name from description=" + d + "; - ignored").printStackTrace(); return null; } } private Class reloadParamType( Class testClass, Class typeToReload) { if (typeToReload.isPrimitive() || testClass.getClassLoader() == typeToReload.getClassLoader()) { return typeToReload; } else if (typeToReload.isArray()) { Class newComponentType = reloadParamType( testClass, typeToReload.getComponentType()); if (newComponentType == typeToReload.getComponentType()) { return typeToReload; } else { return Array.newInstance(newComponentType, 0).getClass(); } } else { try { return Class.forName(typeToReload.getName(), true, testClass.getClassLoader()); } catch (ClassNotFoundException ex) { throw new Error(ex); } } } private Method reloadMethod(Class testClass, Method m) { if (testClass.getClassLoader() == m.getDeclaringClass().getClassLoader()) { return m; } else if (!m.getDeclaringClass().getName() .equals(testClass.getName())) { return reloadMethod(testClass.getSuperclass(), m); } Class[] paramTypes = m.getParameterTypes(); for (int i = 0; i < paramTypes.length; ++i) { paramTypes[i] = reloadParamType(testClass, paramTypes[i]); } try { return testClass.getDeclaredMethod(m.getName(), paramTypes); } catch (NoSuchMethodException ex) { throw new Error(ex); } } void testSuiteStarted(Class testClass) { for (int i = 0; i < testMethods.length; ++i) { testMethods[i] = reloadMethod(testClass, testMethods[i]); } powerMockTestNotifier.notifyBeforeTestSuiteStarted(testClass, testMethods); this.testClassName = testClass.getName(); } void testStartHasBeenFired(Description d) { OngoingTestRun oldTestRun = ongoingTestRuns.get(d); if (null != oldTestRun && null != oldTestRun.getResult()) { throw new IllegalStateException( "Fired testrun is already running: " + d); } currentDescription = d; switch (behaviour) { case PENDING: behaviour = DetectedTestRunBehaviour.START_FIRES_FIRST; case START_FIRES_FIRST: return; case TEST_INSTANCE_CREATED_FIRST: if (currentTestInstance == latestTestInstance) { behaviour = DetectedTestRunBehaviour.TEST_INSTANCES_ARE_REUSED; } case TEST_INSTANCES_ARE_REUSED: latestTestInstance = currentTestInstance; methodsPerInstance.get(currentTestInstance).add( new OngoingTestRun(d, currentTestInstance).testMethod); return; case ALL_TESTINSTANCES_ARE_CREATED_FIRST: System.err.println( "Notifications are not supported when all test-instances are created first!"); return; default: throw new AssertionError(); } } void testInstanceCreated(Object newTestInstance) { switch (behaviour) { case PENDING: behaviour = DetectedTestRunBehaviour.TEST_INSTANCE_CREATED_FIRST; currentTestInstance = newTestInstance; return ; case TEST_INSTANCE_CREATED_FIRST: if (methodsPerInstance.isEmpty()) { behaviour = DetectedTestRunBehaviour.ALL_TESTINSTANCES_ARE_CREATED_FIRST; } else if (currentTestInstance == latestTestInstance) { currentTestInstance = newTestInstance; } else { behaviour = DetectedTestRunBehaviour.INCONSISTENT_BEHAVIOUR; } return; case ALL_TESTINSTANCES_ARE_CREATED_FIRST: case INCONSISTENT_BEHAVIOUR: System.err.println( "Notifications are not supported for behaviour " + behaviour); return; case START_FIRES_FIRST: currentTestInstance = latestTestInstance = newTestInstance; latestMethod = determineTestMethod(currentDescription); methodsPerInstance.get(newTestInstance).add( new OngoingTestRun(currentDescription, newTestInstance).testMethod); return; default: throw new AssertionError("Unknown behaviour: " + behaviour); } } void testIgnored(Description d) { if (!notify(d, Result.IGNORED) && DetectedTestRunBehaviour.TEST_INSTANCE_CREATED_FIRST == behaviour && currentTestInstance != latestTestInstance) { /* * Workaround for some bad behaviour in JUnit-4.4 default runner, * which creates a test-instance first, even for a test that is ignored!! */ currentTestInstance = latestTestInstance; } } void assumptionFailed(Description d) { notify(d, Result.IGNORED); } void failure(Failure f) { notify(f.getDescription(), Result.FAILED); } void testFinished(Description d) { notify(d, Result.SUCCESSFUL); } /** * @return true if notification concerns an ongoing testrun; otherwise false * when there is no test launched for the specified description */ private boolean notify(Description d, Result result) { OngoingTestRun testRun = ongoingTestRuns.get(d); if (null == testRun) { // System.err.println("Notification not enabled for " + d); return false; } else { testRun.report(result); return true; } } } ================================================ FILE: powermock-modules/powermock-module-junit4/src/main/java/org/powermock/modules/junit4/internal/impl/PowerMockJUnit44RunnerDelegateImpl.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.modules.junit4.internal.impl; import junit.framework.TestCase; import junit.framework.TestSuite; import org.junit.Before; import org.junit.internal.runners.ClassRoadie; import org.junit.internal.runners.InitializationError; import org.junit.internal.runners.JUnit4ClassRunner; import org.junit.internal.runners.MethodRoadie; import org.junit.internal.runners.MethodValidator; import org.junit.internal.runners.TestClass; import org.junit.internal.runners.TestMethod; import org.junit.runner.Description; import org.junit.runner.Runner; import org.junit.runner.manipulation.Filter; import org.junit.runner.manipulation.Filterable; import org.junit.runner.manipulation.NoTestsRemainException; import org.junit.runner.manipulation.Sortable; import org.junit.runner.manipulation.Sorter; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunNotifier; import org.powermock.core.classloader.annotations.MockPolicy; import org.powermock.core.classloader.annotations.PrepareEverythingForTest; import org.powermock.core.spi.PowerMockTestListener; import org.powermock.modules.junit4.common.internal.PowerMockJUnitRunnerDelegate; import org.powermock.modules.junit4.internal.impl.testcaseworkaround.PowerMockJUnit4MethodValidator; import org.powermock.reflect.Whitebox; import org.powermock.tests.utils.PowerMockTestNotifier; import org.powermock.tests.utils.impl.MockPolicyInitializerImpl; import org.powermock.tests.utils.impl.PowerMockTestNotifierImpl; import org.powermock.tests.utils.impl.PrepareForTestExtractorImpl; import org.powermock.tests.utils.impl.StaticConstructorSuppressExtractorImpl; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedList; import java.util.List; /** *

* A JUnit4 test runner that only runs a specified set of test methods in a test * class. *

*

* Many parts of this class are essentially a rip off from * {@link JUnit4ClassRunner} used in JUnit 4.4. It does however not extend this * class because we cannot let it perform the stuff it does in its constructor. * Another thing that different is that if an exception is thrown in the test we * add a tip to error message asking the user if they've not forgot to add a * class to test. Yet another difference is that this runner notifies the * PowerMock listeners of certain events. *

* @see JUnit4ClassRunner */ @SuppressWarnings("deprecation") public class PowerMockJUnit44RunnerDelegateImpl extends Runner implements Filterable, Sortable, PowerMockJUnitRunnerDelegate { private final List testMethods; private final TestClass testClass; private final PowerMockTestNotifier powerMockTestNotifier; public PowerMockJUnit44RunnerDelegateImpl(Class klass, String[] methodsToRun, PowerMockTestListener[] listeners) throws InitializationError { this.powerMockTestNotifier = new PowerMockTestNotifierImpl(listeners == null ? new PowerMockTestListener[0] : listeners); testClass = new TestClass(klass); testMethods = getTestMethods(klass, methodsToRun); validate(); } public PowerMockJUnit44RunnerDelegateImpl(Class klass, String[] methodsToRun) throws InitializationError { this(klass, methodsToRun, null); } public PowerMockJUnit44RunnerDelegateImpl(Class klass) throws InitializationError { this(klass, null); } @SuppressWarnings("unchecked") protected final List getTestMethods(Class klass, String[] methodsToRun) { if (methodsToRun == null || methodsToRun.length == 0) { // The getTestMethods of TestClass is not visible so we need to look // it invoke it using reflection. try { return (List) Whitebox.invokeMethod(testClass, "getTestMethods"); } catch (Throwable e) { throw new RuntimeException(e); } } else { List foundMethods = new LinkedList(); Method[] methods = klass.getMethods(); for (Method method : methods) { for (String methodName : methodsToRun) { if (method.getName().equals(methodName)) { foundMethods.add(method); } } } return foundMethods; } } protected final void validate() throws InitializationError { if (!TestCase.class.isAssignableFrom(testClass.getJavaClass())) { MethodValidator methodValidator = new PowerMockJUnit4MethodValidator(testClass); methodValidator.validateMethodsForDefaultRunner(); methodValidator.assertValid(); } } @Override public void run(final RunNotifier notifier) { new ClassRoadie(notifier, testClass, getDescription(), new Runnable() { @Override public void run() { runMethods(notifier); } }).runProtected(); } protected void runMethods(final RunNotifier notifier) { final StaticConstructorSuppressExtractorImpl staticConstructorSuppressExtractorImpl = new StaticConstructorSuppressExtractorImpl(); Class testType = getTestClass(); final ClassLoader thisClassLoader = getClass().getClassLoader(); if (!thisClassLoader.equals(testType.getClassLoader())) { /* * The test is loaded from another classloader, this means that we * cannot get the correct annotations if we don't load the class * from the correct class loader */ try { testType = thisClassLoader.loadClass(testType.getName()); } catch (ClassNotFoundException e) { // This should never happen throw new RuntimeException("Internal error in PowerMock", e); } } for (Method method : testMethods) { if (staticConstructorSuppressExtractorImpl.getTestClasses(method) == null) { staticConstructorSuppressExtractorImpl.getTestClasses(testType); } invokeTestMethod(method, notifier); } } @Override public Description getDescription() { Description spec = Description.createSuiteDescription(getName(), classAnnotations()); List testMethods = this.testMethods; for (Method method : testMethods) spec.addChild(methodDescription(method)); return spec; } protected Annotation[] classAnnotations() { return getTestClass().getAnnotations(); } protected String getName() { return getTestWrappedClass().getName(); } protected Object createTest() throws Exception { return createTestInstance(); } private Object createTestInstance() throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { final TestClass testWrappedClass = getTestWrappedClass(); Constructor constructor = null; final Class javaClass = testWrappedClass.getJavaClass(); if (TestCase.class.isAssignableFrom(javaClass)) { constructor = TestSuite.getTestConstructor(javaClass.asSubclass(TestCase.class)); if (constructor.getParameterTypes().length == 1) { return constructor.newInstance(javaClass.getSimpleName()); } } else { constructor = testWrappedClass.getConstructor(); } return constructor.newInstance(); } protected void invokeTestMethod(final Method method, RunNotifier notifier) { Description description = methodDescription(method); final Object testInstance; try { testInstance = createTest(); } catch (InvocationTargetException e) { testAborted(notifier, description, e.getTargetException()); return; } catch (Exception e) { testAborted(notifier, description, e); return; } // Check if we extend from TestClass, in that case we must run the setUp // and tearDown methods. final boolean extendsFromTestCase = TestCase.class.isAssignableFrom(testClass.getJavaClass()); final TestMethod testMethod = wrapMethod(method); createPowerMockRunner(testInstance, testMethod, notifier, description, extendsFromTestCase).run(); } protected PowerMockJUnit44MethodRunner createPowerMockRunner(final Object testInstance, final TestMethod testMethod, RunNotifier notifier, Description description, final boolean extendsFromTestCase) { return new PowerMockJUnit44MethodRunner(testInstance, testMethod, notifier, description, extendsFromTestCase); } private void testAborted(RunNotifier notifier, Description description, Throwable e) { notifier.fireTestStarted(description); notifier.fireTestFailure(new Failure(description, e)); notifier.fireTestFinished(description); } protected TestMethod wrapMethod(Method method) { return new TestMethod(method, testClass); } protected String testName(Method method) { return method.getName(); } protected Description methodDescription(Method method) { return Description.createTestDescription(getTestWrappedClass().getJavaClass(), testName(method), testAnnotations(method)); } protected Annotation[] testAnnotations(Method method) { return method.getAnnotations(); } @Override public void filter(Filter filter) throws NoTestsRemainException { for (Iterator iter = testMethods.iterator(); iter.hasNext(); ) { Method method = iter.next(); if (!filter.shouldRun(methodDescription(method))) iter.remove(); } if (testMethods.isEmpty()) throw new NoTestsRemainException(); } @Override public void sort(final Sorter sorter) { Collections.sort(testMethods, new Comparator() { @Override public int compare(Method o1, Method o2) { return sorter.compare(methodDescription(o1), methodDescription(o2)); } }); } protected TestClass getTestWrappedClass() { return testClass; } @Override public int getTestCount() { return testMethods.size(); } @Override public Class getTestClass() { return testClass.getJavaClass(); } protected class PowerMockJUnit44MethodRunner extends MethodRoadie { private final Object testInstance; private final boolean extendsFromTestCase; protected final TestMethod testMethod; protected PowerMockJUnit44MethodRunner(Object testInstance, TestMethod method, RunNotifier notifier, Description description, boolean extendsFromTestCase) { super(testInstance, method, notifier, description); this.testInstance = testInstance; this.extendsFromTestCase = extendsFromTestCase; this.testMethod = method; } @Override public void runBeforesThenTestThenAfters(final Runnable test) { executeTest(Whitebox.getInternalState(testMethod, Method.class), testInstance, test); } public void executeTest(final Method method, final Object testInstance, final Runnable test) { // Initialize mock policies for each test final ClassLoader classloader = this.getClass().getClassLoader(); final Thread currentThread = Thread.currentThread(); final ClassLoader originalClassLoader = currentThread.getContextClassLoader(); currentThread.setContextClassLoader(classloader); new MockPolicyInitializerImpl(testClass.getJavaClass()).initialize(classloader); powerMockTestNotifier.notifyBeforeTestMethod(testInstance, method, new Object[0]); try { super.runBeforesThenTestThenAfters(test); } finally { currentThread.setContextClassLoader(originalClassLoader); } } @Override protected void runTestMethod() { try { try { if (extendsFromTestCase) { final Method setUp = Whitebox.getMethod(testInstance.getClass(), "setUp"); if (!setUp.isAnnotationPresent(Before.class)) { Whitebox.invokeMethod(testInstance, "setUp"); } } testMethod.invoke(testInstance); if (Whitebox.invokeMethod(testMethod, "expectsException")) { addFailure(new AssertionError("Expected exception: " + getExpectedExceptionName(testMethod))); } } catch (InvocationTargetException e) { handleInvocationTargetException(testMethod, e); } catch (Throwable e) { addFailure(e); } finally { if (extendsFromTestCase) { try { Whitebox.invokeMethod(testInstance, "tearDown"); } catch (Throwable tearingDown) { addFailure(tearingDown); } } } } catch (Throwable e) { throw new RuntimeException("Internal error in PowerMock.", e); } } private void handleInvocationTargetException(final TestMethod testMethod, InvocationTargetException e) throws Exception { Throwable actual = e.getTargetException(); while (actual instanceof InvocationTargetException) { actual = ((InvocationTargetException) actual).getTargetException(); } handleException(testMethod, actual); } protected void handleException(final TestMethod testMethod, Throwable actualFailure) { try { final String throwableName = actualFailure.getClass().getName(); if (throwableName.equals("org.junit.internal.AssumptionViolatedException") || throwableName.startsWith("org.junit.Assume$AssumptionViolatedException")) { return; } else if (!(Boolean) Whitebox.invokeMethod(testMethod, "expectsException")) { final String className = actualFailure.getStackTrace()[0].getClassName(); final Class testClassAsJavaClass = testClass.getJavaClass(); if (actualFailure instanceof NullPointerException && !testClassAsJavaClass.getName().equals(className) && !className.startsWith("java.lang") && !className.startsWith("org.powermock") && !className.startsWith("org.junit") && !new PrepareForTestExtractorImpl().isPrepared(testClassAsJavaClass, className) && !testClassAsJavaClass.isAnnotationPresent(PrepareEverythingForTest.class) && !new MockPolicyInitializerImpl(testClassAsJavaClass.isAnnotationPresent(MockPolicy.class) ? testClassAsJavaClass .getAnnotation(MockPolicy.class).value() : null).isPrepared(className)) { Whitebox.setInternalState(actualFailure, "detailMessage", "Perhaps the class " + className + " must be prepared for test?", Throwable.class); } addFailure(actualFailure); } else if (Whitebox.invokeMethod(testMethod, "isUnexpected", actualFailure)) { String message = "Unexpected exception, expected<" + getExpectedExceptionName(testMethod) + "> but was<" + actualFailure.getClass().getName() + ">"; addFailure(new Exception(message, actualFailure)); } } catch (Exception e) { throw new RuntimeException("PowerMock internal error: Should never throw exception at this level", e); } } @SuppressWarnings("unchecked") private String getExpectedExceptionName(TestMethod fTestMethod) throws Exception { return ((Class) Whitebox.invokeMethod(fTestMethod, "getExpectedException")).getName(); } } } ================================================ FILE: powermock-modules/powermock-module-junit4/src/main/java/org/powermock/modules/junit4/internal/impl/PowerMockJUnit47RunnerDelegateImpl.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.modules.junit4.internal.impl; import org.junit.Rule; import org.junit.internal.runners.InitializationError; import org.junit.internal.runners.TestMethod; import org.junit.rules.MethodRule; import org.junit.runner.Description; import org.junit.runner.notification.RunNotifier; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.Statement; import org.powermock.core.spi.PowerMockTestListener; import org.powermock.reflect.Whitebox; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Set; /** * Extends the functionality of {@link PowerMockJUnit44RunnerDelegateImpl} to * enable the usage of rules. */ @SuppressWarnings("deprecation") public class PowerMockJUnit47RunnerDelegateImpl extends PowerMockJUnit44RunnerDelegateImpl { public boolean hasRules; public PowerMockJUnit47RunnerDelegateImpl(Class klass, String[] methodsToRun, PowerMockTestListener[] listeners) throws InitializationError { super(klass, methodsToRun, listeners); } public PowerMockJUnit47RunnerDelegateImpl(Class klass, String[] methodsToRun) throws InitializationError { super(klass, methodsToRun); } public PowerMockJUnit47RunnerDelegateImpl(Class klass) throws InitializationError { super(klass); } @Override protected PowerMockJUnit44MethodRunner createPowerMockRunner(final Object testInstance, final TestMethod testMethod, RunNotifier notifier, Description description, final boolean extendsFromTestCase) { return new PowerMockJUnit47MethodRunner(testInstance, testMethod, notifier, description, extendsFromTestCase); } protected class PowerMockJUnit47MethodRunner extends PowerMockJUnit44MethodRunner { private Throwable potentialTestFailure; protected PowerMockJUnit47MethodRunner(Object testInstance, TestMethod method, RunNotifier notifier, Description description, boolean extendsFromTestCase) { super(testInstance, method, notifier, description, extendsFromTestCase); } @Override public void executeTest(final Method method, final Object testInstance, final Runnable test) { // We change the context classloader to the current CL in order for the Mockito // framework to load it's plugins (such as MockMaker) correctly. final ClassLoader originalCL = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); final Set rules; try { rules = Whitebox.getFieldsAnnotatedWith( testInstance, Rule.class ); } finally { Thread.currentThread().setContextClassLoader(originalCL); } hasRules = !rules.isEmpty(); Statement statement = createStatement(method, testInstance, test, rules); evaluateStatement(statement); } private Statement createStatement(Method method, Object testInstance, Runnable test, Set rules) { Statement statement = new TestExecutorStatement(test, testInstance, method); for (Field field : rules) { try { statement = applyRuleToLastStatement(method, testInstance, field, statement); } catch (Throwable e) { super.handleException(testMethod, e); } } return statement; } protected Statement applyRuleToLastStatement(final Method method, final Object testInstance, Field field, final Statement lastStatement) throws IllegalAccessException { MethodRule rule = (MethodRule) field.get(testInstance); Statement statement = rule.apply(lastStatement, new FrameworkMethod(method), testInstance); return statement; } private void evaluateStatement(Statement statement) { try { statement.evaluate(); } catch (Throwable e) { //No rule could handle the exception thus we need to add it as a failure. super.handleException(testMethod, potentialTestFailure == null ? e : potentialTestFailure); } } /** * Since a JUnit 4.7 rule may potentially deal with "unexpected" * exceptions we cannot handle the exception before the rule has been * completely evaluated. Thus we just store the exception here and * rethrow it after the test method has finished executing. In that way * the rule may get a chance to handle the exception appropriately. */ @Override protected void handleException(TestMethod testMethod, Throwable actualFailure) { if (hasRules) { potentialTestFailure = actualFailure; } else { super.handleException(testMethod, actualFailure); } } private void executeTestInSuper(final Method method, final Object testInstance, final Runnable test) { super.executeTest(method, testInstance, test); } private final class TestExecutorStatement extends Statement { private final Runnable test; private final Object testInstance; private final Method method; private TestExecutorStatement(Runnable test, Object testInstance, Method method) { this.test = test; this.testInstance = testInstance; this.method = method; } @Override public void evaluate() throws Throwable { executeTestInSuper(method, testInstance, test); if (potentialTestFailure != null) { // Rethrow the potential failure caught in the test. throw potentialTestFailure; } } } } } ================================================ FILE: powermock-modules/powermock-module-junit4/src/main/java/org/powermock/modules/junit4/internal/impl/PowerMockJUnit49RunnerDelegateImpl.java ================================================ package org.powermock.modules.junit4.internal.impl; import org.junit.internal.runners.InitializationError; import org.junit.internal.runners.TestMethod; import org.junit.rules.MethodRule; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runner.notification.RunNotifier; import org.junit.runners.model.Statement; import org.powermock.core.spi.PowerMockTestListener; import java.lang.reflect.Field; import java.lang.reflect.Method; /** * Extends the functionality of {@link PowerMockJUnit47RunnerDelegateImpl} to enable the usage of * {@link TestRule}. */ @SuppressWarnings( "deprecation" ) public class PowerMockJUnit49RunnerDelegateImpl extends PowerMockJUnit47RunnerDelegateImpl { public PowerMockJUnit49RunnerDelegateImpl( Class klass, String[] methodsToRun, PowerMockTestListener[] listeners ) throws InitializationError { super( klass, methodsToRun, listeners ); } public PowerMockJUnit49RunnerDelegateImpl( Class klass, String[] methodsToRun ) throws InitializationError { super( klass, methodsToRun ); } public PowerMockJUnit49RunnerDelegateImpl( Class klass ) throws InitializationError { super( klass ); } @Override protected PowerMockJUnit47MethodRunner createPowerMockRunner( final Object testInstance, final TestMethod testMethod, RunNotifier notifier, Description description, final boolean extendsFromTestCase ) { return new PowerMockJUnit49MethodRunner( testInstance, testMethod, notifier, description, extendsFromTestCase ); } protected class PowerMockJUnit49MethodRunner extends PowerMockJUnit47MethodRunner { private Description description; protected PowerMockJUnit49MethodRunner( Object testInstance, TestMethod method, RunNotifier notifier, Description description, boolean extendsFromTestCase ) { super( testInstance, method, notifier, description, extendsFromTestCase ); this.description = description; } @Override protected Statement applyRuleToLastStatement(final Method method, final Object testInstance, Field field, final Statement lastStatement) throws IllegalAccessException { final Object fieldValue = field.get(testInstance); final Statement statement; if (fieldValue instanceof MethodRule) { // the MethodRule is known by junit 4.9 -> delegate to super-class statement = super.applyRuleToLastStatement(method, testInstance, field, lastStatement); } else if (fieldValue instanceof TestRule){ TestRule rule = (TestRule) fieldValue; statement = rule.apply(lastStatement, description); } else { throw new IllegalStateException("Can only handle MethodRule and TestRule"); } return statement; } } } ================================================ FILE: powermock-modules/powermock-module-junit4/src/main/java/org/powermock/modules/junit4/internal/impl/PowerMockRunNotifier.java ================================================ /* * Copyright 2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.modules.junit4.internal.impl; import org.junit.runner.Description; import org.junit.runner.Result; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunListener; import org.junit.runner.notification.RunNotifier; import org.junit.runner.notification.StoppedByUserException; import org.powermock.core.spi.PowerMockTestListener; import org.powermock.core.testlisteners.GlobalNotificationBuildSupport; import org.powermock.tests.utils.PowerMockTestNotifier; import java.lang.reflect.Method; import java.util.LinkedList; import static org.powermock.reflect.Whitebox.invokeMethod; /** * Wraps JUnit's RunNotifier to make sure that the PowerMock-specific * instances of {@link PowerMockTestListener} will also be informed. * It is stateful and (hopefully) thread-safe. * * @see PowerMockTestListener */ class PowerMockRunNotifier extends RunNotifier implements GlobalNotificationBuildSupport.Callback { private Class suiteClass = null; private final Thread motherThread = Thread.currentThread(); private final RunNotifier junitRunNotifier; private final PowerMockTestNotifier powerMockTestNotifier; private final Method[] testMethods; private final LinkedList pendingTestInstancesOnMotherThread = new LinkedList(); private final ThreadLocal notificationBuilder = new ThreadLocal() { @Override protected NotificationBuilder initialValue() { return new NotificationBuilder( testMethods.clone(), powerMockTestNotifier, pendingTestInstancesOnMotherThread); } }; PowerMockRunNotifier( RunNotifier junitRunNotifier, PowerMockTestNotifier powerMockTestNotifier, Method[] testMethods) { this.junitRunNotifier = junitRunNotifier; this.powerMockTestNotifier = powerMockTestNotifier; this.testMethods = testMethods; } Class getSuiteClass() { return this.suiteClass; } @Override public void suiteClassInitiated(Class testClass) { this.suiteClass = testClass; notificationBuilder.get().testSuiteStarted(testClass); } @Override public void testInstanceCreated(Object testInstance) { if (Thread.currentThread() == motherThread) { pendingTestInstancesOnMotherThread.add(testInstance); } notificationBuilder.get().testInstanceCreated(testInstance); } @Override public void addListener(RunListener listener) { invoke("addListener", listener); } @Override public void removeListener(RunListener listener) { invoke("removeListener", listener); } @Override public void fireTestRunStarted(Description description) { invoke("fireTestRunStarted", description); } @Override public void fireTestRunFinished(Result result) { invoke("fireTestRunFinished", result); } @Override public void fireTestStarted(Description description) throws StoppedByUserException { invoke("fireTestStarted", description); notificationBuilder.get().testStartHasBeenFired(description); } @Override public void fireTestFailure(Failure failure) { notificationBuilder.get().failure(failure); invoke("fireTestFailure", failure); } @Override public void fireTestAssumptionFailed(Failure failure) { notificationBuilder.get().assumptionFailed(failure.getDescription()); invoke("fireTestAssumptionFailed", failure); } @Override public void fireTestIgnored(Description description) { notificationBuilder.get().testIgnored(description); invoke("fireTestIgnored", description); } @Override public void fireTestFinished(Description description) { try { notificationBuilder.get().testFinished(description); } catch (Throwable failure) { fireTestFailure(new Failure(description, failure)); return; } invoke("fireTestFinished", description); } @Override public void pleaseStop() { invoke("pleaseStop"); } @Override public void addFirstListener(RunListener listener) { invoke("addFirstListener", listener); } private void invoke(String methodName, Object... args) { try { invokeMethod(junitRunNotifier, methodName, args); } catch (Exception ex) { throw new RuntimeException(ex); } } } ================================================ FILE: powermock-modules/powermock-module-junit4/src/main/java/org/powermock/modules/junit4/internal/impl/testcaseworkaround/PowerMockJUnit4MethodValidator.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.modules.junit4.internal.impl.testcaseworkaround; import junit.framework.TestCase; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.internal.runners.MethodValidator; import org.junit.internal.runners.TestClass; import org.powermock.modules.junit4.common.internal.impl.JUnitVersion; import org.powermock.reflect.Whitebox; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.LinkedList; import java.util.List; /** * A custom {@link MethodValidator} that makes sure that test methods not * annotated by the Test annotation works in JUnit 4.4 with the custom * JUnit-runner when the test class is extending {@link TestCase}. This is * actually a workaround for JUnit 4.4 when the test case extends from the * {@code TestCase} class. */ @SuppressWarnings("deprecation") public class PowerMockJUnit4MethodValidator extends MethodValidator { private static final String TEST_CLASS_FIELD; private static final String CLASS_UNDER_TEST_FIELD; private static final String ERRORS_FIELD; static { if(JUnitVersion.isGreaterThanOrEqualTo("4.12")) { TEST_CLASS_FIELD = "testClass"; CLASS_UNDER_TEST_FIELD = "klass"; ERRORS_FIELD = "errors"; } else { TEST_CLASS_FIELD = "fTestClass"; CLASS_UNDER_TEST_FIELD = "fClass"; ERRORS_FIELD = "fErrors"; } } public PowerMockJUnit4MethodValidator(TestClass testClass) { super(testClass); } @SuppressWarnings("unchecked") @Override public void validateInstanceMethods() { validateTestMethods(After.class, false); validateTestMethods(Before.class, false); validateTestMethods(Test.class, false); TestClass testClass = Whitebox.getInternalState(this, TEST_CLASS_FIELD, MethodValidator.class); Class classUnderTest = Whitebox.getInternalState(testClass, CLASS_UNDER_TEST_FIELD); List fErrors = Whitebox.getInternalState(this, ERRORS_FIELD, MethodValidator.class); List methods = getTestMethods(testClass, classUnderTest); if (methods.size() == 0) fErrors.add(new Exception("No runnable methods")); } private List getTestMethods(TestClass testClass, Class classUnderTest) { List methods = testClass.getAnnotatedMethods(Test.class); if (methods.isEmpty()) { methods.addAll(getTestMethodsWithNoAnnotation(classUnderTest)); } return methods; } /** * This is a rip-off of the * {@link MethodValidator#validateInstanceMethods()} with the exception that * this method also searches for test methods if the class extends * {@link TestCase} and has methods that starts with test which are not * annotated. */ @SuppressWarnings("unchecked") private void validateTestMethods(Class annotation, boolean isStatic) { TestClass testClass = Whitebox.getInternalState(this, TEST_CLASS_FIELD, MethodValidator.class); Class classUnderTest = Whitebox.getInternalState(testClass, CLASS_UNDER_TEST_FIELD); final List methods; if (TestCase.class.equals(classUnderTest.getSuperclass()) && !isStatic) { methods = getTestMethodsWithNoAnnotation(classUnderTest); } else { methods = testClass.getAnnotatedMethods(annotation); } List fErrors = Whitebox.getInternalState(this, ERRORS_FIELD, MethodValidator.class); for (Method each : methods) { if (Modifier.isStatic(each.getModifiers()) != isStatic) { String state = isStatic ? "should" : "should not"; fErrors.add(new Exception("Method " + each.getName() + "() " + state + " be static")); } if (!Modifier.isPublic(each.getDeclaringClass().getModifiers())) fErrors.add(new Exception("Class " + each.getDeclaringClass().getName() + " should be public")); if (!Modifier.isPublic(each.getModifiers())) fErrors.add(new Exception("Method " + each.getName() + " should be public")); if (each.getReturnType() != Void.TYPE) fErrors.add(new Exception("Method " + each.getName() + " should be void")); if (each.getParameterTypes().length != 0) fErrors.add(new Exception("Method " + each.getName() + " should have no parameters")); } } private List getTestMethodsWithNoAnnotation(Class testClass) { List potentialTestMethods = new LinkedList(); Method[] methods = testClass.getMethods(); for (Method method : methods) { if (method.getName().startsWith("test")) { potentialTestMethods.add(method); } } return potentialTestMethods; } } ================================================ FILE: powermock-modules/powermock-module-junit4/src/test/java/org/powermock/modules/junit4/internal/impl/PowerMockRunNotifierTest.java ================================================ /* * Copyright 2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.modules.junit4.internal.impl; import org.junit.Test; import org.junit.runner.Description; import org.junit.runner.Result; import org.junit.runner.RunWith; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunListener; import org.junit.runner.notification.RunNotifier; import org.junit.runners.Parameterized; import org.easymock.EasyMock; import org.powermock.tests.utils.PowerMockTestNotifier; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import static org.easymock.EasyMock.createMock; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; @RunWith(Parameterized.class) public class PowerMockRunNotifierTest { /* * Dummy test data ... */ private static final Object[][] testDataAlternatives; static { Description description = Description.createSuiteDescription(Description.class); testDataAlternatives = new Object[][] { {description}, {new Failure(description, new Throwable())}, {new RunListener()}, {new Result()} }; } /** * Parameter data */ @Parameterized.Parameter(0) public Method method; @Parameterized.Parameters(name = "{0}") public static List runNotifierMethods() { List methods = new ArrayList(); for (Method m : RunNotifier.class.getMethods()) { if (Object.class != m.getDeclaringClass()) { methods.add(new Object[] {m}); } } return methods; } @Test public void verifyBackendRunNotifierIsProperlyNotified() throws Exception { Object[] testData = retrieveSuitableTestData(); RunNotifier backendRunNotifierMock = createMock(RunNotifier.class); method.invoke(backendRunNotifierMock, testData); replay(backendRunNotifierMock); method.invoke(new PowerMockRunNotifier( backendRunNotifierMock, EasyMock.createNiceMock(PowerMockTestNotifier.class), new Method[0]), testData); verify(backendRunNotifierMock); } private Object[] retrieveSuitableTestData() { Class[] paramTypes = method.getParameterTypes(); if (0 == paramTypes.length) { return null; } for (Object[] testData : testDataAlternatives) { if (paramTypes[0] == testData[0].getClass()) { return testData; } } throw new Error("No test-data available for method " + method); } } ================================================ FILE: powermock-modules/powermock-module-junit4-common/src/main/java/org/powermock/modules/junit4/common/internal/JUnit4TestSuiteChunker.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.modules.junit4.common.internal; import org.junit.runner.Description; import org.junit.runner.manipulation.Filterable; import org.junit.runner.manipulation.Sortable; import org.junit.runner.notification.RunNotifier; import org.powermock.tests.utils.RunnerTestSuiteChunker; public interface JUnit4TestSuiteChunker extends RunnerTestSuiteChunker, Filterable, Sortable { Description getDescription(); void run(RunNotifier notifier); } ================================================ FILE: powermock-modules/powermock-module-junit4-common/src/main/java/org/powermock/modules/junit4/common/internal/PowerMockJUnitRunnerDelegate.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.modules.junit4.common.internal; import org.junit.runner.Description; import org.junit.runner.notification.RunNotifier; public interface PowerMockJUnitRunnerDelegate { void run(final RunNotifier notifier); Description getDescription(); int getTestCount(); Class getTestClass(); } ================================================ FILE: powermock-modules/powermock-module-junit4-common/src/main/java/org/powermock/modules/junit4/common/internal/impl/AbstractCommonPowerMockRunner.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.modules.junit4.common.internal.impl; import org.junit.runner.Description; import org.junit.runner.Runner; import org.junit.runner.manipulation.Filter; import org.junit.runner.manipulation.Filterable; import org.junit.runner.manipulation.NoTestsRemainException; import org.junit.runner.manipulation.Sortable; import org.junit.runner.manipulation.Sorter; import org.junit.runner.notification.RunNotifier; import org.powermock.core.MockRepository; import org.powermock.modules.junit4.common.internal.JUnit4TestSuiteChunker; import org.powermock.modules.junit4.common.internal.PowerMockJUnitRunnerDelegate; public abstract class AbstractCommonPowerMockRunner extends Runner implements Filterable, Sortable { private JUnit4TestSuiteChunker suiteChunker; public AbstractCommonPowerMockRunner(Class klass, Class runnerDelegateImplClass) throws Exception { suiteChunker = new JUnit4TestSuiteChunkerImpl(klass, runnerDelegateImplClass); /* * For extra safety clear the MockitoRepository on each new * instantiation of the runner. This is good in cases where a previous * test has used e.g. PowerMock#createMock(..) to create a mock without * using this runner. That means that there's some state left in the * MockRepository that hasn't been cleared. Currently clearing the * MockRepository from any classloader will clear the previous state but * it's not certain that this is always the case. */ MockRepository.clear(); } @Override public Description getDescription() { return suiteChunker.getDescription(); } @Override public void run(RunNotifier notifier) { try { suiteChunker.run(notifier); } finally { // To avoid out of memory errors! suiteChunker = null; } } @Override public synchronized int testCount() { return suiteChunker.getTestCount(); } @Override public void filter(Filter filter) throws NoTestsRemainException { suiteChunker.filter(filter); } @Override public void sort(Sorter sorter) { suiteChunker.sort(sorter); } } ================================================ FILE: powermock-modules/powermock-module-junit4-common/src/main/java/org/powermock/modules/junit4/common/internal/impl/JUnit4TestMethodChecker.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.modules.junit4.common.internal.impl; import junit.framework.TestCase; import org.junit.Test; import java.lang.reflect.Method; import java.lang.reflect.Modifier; /** * */ public class JUnit4TestMethodChecker { private final Class testClass; private final Method potentialTestMethod; public JUnit4TestMethodChecker(Class testClass, Method potentialTestMethod) { this.testClass = testClass; this.potentialTestMethod = potentialTestMethod; } public boolean isTestMethod() { return isJUnit3TestMethod() || isJUnit4TestMethod(); } protected boolean isJUnit4TestMethod() {return potentialTestMethod.isAnnotationPresent(Test.class);} protected boolean isJUnit3TestMethod() { return potentialTestMethod.getName().startsWith("test") && Modifier.isPublic(potentialTestMethod.getModifiers()) && potentialTestMethod.getReturnType() .equals(Void.TYPE) && TestCase.class.isAssignableFrom(testClass); } } ================================================ FILE: powermock-modules/powermock-module-junit4-common/src/main/java/org/powermock/modules/junit4/common/internal/impl/JUnit4TestSuiteChunkerImpl.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.modules.junit4.common.internal.impl; import org.junit.Test; import org.junit.runner.Description; import org.junit.runner.manipulation.Filter; import org.junit.runner.manipulation.Filterable; import org.junit.runner.manipulation.NoTestsRemainException; import org.junit.runner.manipulation.Sortable; import org.junit.runner.manipulation.Sorter; import org.junit.runner.notification.RunNotifier; import org.powermock.core.spi.PowerMockTestListener; import org.powermock.core.spi.testresult.TestSuiteResult; import org.powermock.core.spi.testresult.impl.TestSuiteResultImpl; import org.powermock.modules.junit4.common.internal.JUnit4TestSuiteChunker; import org.powermock.modules.junit4.common.internal.PowerMockJUnitRunnerDelegate; import org.powermock.tests.utils.PowerMockTestNotifier; import org.powermock.tests.utils.TestChunk; import org.powermock.tests.utils.impl.AbstractTestSuiteChunkerImpl; import org.powermock.tests.utils.impl.PowerMockTestNotifierImpl; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; public class JUnit4TestSuiteChunkerImpl extends AbstractTestSuiteChunkerImpl implements JUnit4TestSuiteChunker, Filterable, Sortable { private static final Class testMethodAnnotation = Test.class; private Description description; private final Class runnerDelegateImplementationType; JUnit4TestSuiteChunkerImpl(Class testClass, Class runnerDelegateImplementationType) throws Exception { super(testClass); if (testClass == null) { throw new IllegalArgumentException("You must supply a test class"); } if (runnerDelegateImplementationType == null) { throw new IllegalArgumentException("Runner delegate type cannot be null."); } this.runnerDelegateImplementationType = runnerDelegateImplementationType; try { createTestDelegators(testClass, getTestChunksEntries(testClass)); } catch (InvocationTargetException e) { final Throwable cause = e.getCause(); if (cause instanceof Exception) { throw (Exception) cause; } else if (cause instanceof Error) { throw (Error) cause; } else { throw new RuntimeException(cause); } } } @Override public void run(RunNotifier notifier) { List chunkEntries = getTestChunks(); Iterator iterator = chunkEntries.iterator(); if (delegates.size() != getChunkSize()) { throw new IllegalStateException("Internal error: There must be an equal number of suites and delegates."); } final Class testClass = getTestClasses()[0]; final PowerMockTestListener[] powerMockTestListeners = (PowerMockTestListener[]) getPowerMockTestListenersLoadedByASpecificClassLoader( testClass, this.getClass().getClassLoader()); final Set allMethods = new LinkedHashSet(); for (TestChunk testChunk : getTestChunks()) { allMethods.addAll(testChunk.getTestMethodsToBeExecutedByThisClassloader()); } final Method[] allMethodsAsArray = allMethods.toArray(new Method[allMethods.size()]); final PowerMockTestNotifier powerMockTestNotifier = new PowerMockTestNotifierImpl(powerMockTestListeners); powerMockTestNotifier.notifyBeforeTestSuiteStarted(testClass, allMethodsAsArray); int failureCount = 0; int successCount = 0; int ignoreCount = 0; for (PowerMockJUnitRunnerDelegate delegate : delegates) { TestChunk next = iterator.next(); final ClassLoader key = next.getClassLoader(); PowerMockJUnit4RunListener powerMockListener = new PowerMockJUnit4RunListener(key, powerMockTestNotifier); notifier.addListener(powerMockListener); final ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(key); try { delegate.run(notifier); } finally { Thread.currentThread().setContextClassLoader(originalClassLoader); } final int failureCountForThisPowerMockListener = powerMockListener.getFailureCount(); final int ignoreCountForThisPowerMockListener = powerMockListener.getIgnoreCount(); failureCount += failureCountForThisPowerMockListener; ignoreCount += ignoreCountForThisPowerMockListener; successCount += delegate.getTestCount() - failureCountForThisPowerMockListener - ignoreCountForThisPowerMockListener; notifier.removeListener(powerMockListener); } final TestSuiteResult testSuiteResult = new TestSuiteResultImpl(failureCount, successCount, getTestCount(), ignoreCount); powerMockTestNotifier.notifyAfterTestSuiteEnded(testClass, allMethodsAsArray, testSuiteResult); } @Override public boolean shouldExecuteTestForMethod(Class testClass, Method potentialTestMethod) { return new JUnit4TestMethodChecker(testClass, potentialTestMethod).isTestMethod(); } @Override protected Class testMethodAnnotation() { return testMethodAnnotation; } @Override protected PowerMockJUnitRunnerDelegate createDelegatorFromClassloader(ClassLoader classLoader, Class testClass, final List methodsToTest) throws Exception { Set methodNames = new HashSet(); for (Method method : methodsToTest) { methodNames.add(method.getName()); } final Class testClassLoadedByMockedClassLoader = Class.forName(testClass.getName(), false, classLoader); /* * Array classes cannot be loaded be classloader.loadClass(..) in JDK 6. * See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6500212. */ final Class powerMockTestListenerArrayType = Class.forName(PowerMockTestListener[].class.getName(), false, classLoader); final Class delegateClass = Class.forName(runnerDelegateImplementationType.getName(), false, classLoader); Constructor con = delegateClass.getConstructor(Class.class, String[].class, powerMockTestListenerArrayType); return (PowerMockJUnitRunnerDelegate) con.newInstance( testClassLoadedByMockedClassLoader, methodNames.toArray(new String[methodNames.size()]), getPowerMockTestListenersLoadedByASpecificClassLoader(testClass, classLoader)); } @Override public synchronized int getTestCount() { if (testCount == NOT_INITIALIZED) { testCount = 0; for (PowerMockJUnitRunnerDelegate delegate : delegates) { testCount += delegate.getTestCount(); } } return testCount; } @Override public Description getDescription() { if (description == null) { if (delegates.size() == 0) { /* * This happens if Test A extends Test B and B uses the @RunWith * annotation and there are no tests defined in class B. */ return Description.createTestDescription(this.getClass(), "no tests in this class"); } // Use the first delegator as the base for the description. PowerMockJUnitRunnerDelegate delegate = delegates.get(0); description = delegate.getDescription(); /* * Add the remaining descriptions of all the chunked delegators. We * do this to make sure that we avoid adding chunks as "Unrooted * tests". */ for (int i = 1; i < delegates.size(); i++) { // Get the method-level descriptions ArrayList children = delegates.get(i).getDescription().getChildren(); // Add all method-level descriptions to the main description. for (Description methodDescription : children) { description.addChild(methodDescription); } } } return description; } @Override public void filter(Filter filter) throws NoTestsRemainException { for (Object delegate : delegates) { if (delegate instanceof Filterable) { ((Filterable) delegate).filter(filter); } } } @Override public void sort(Sorter sorter) { for (Object delegate : delegates) { if (delegate instanceof Sortable) { ((Sortable) delegate).sort(sorter); } } } } ================================================ FILE: powermock-modules/powermock-module-junit4-common/src/main/java/org/powermock/modules/junit4/common/internal/impl/JUnitVersion.java ================================================ /* * Copyright 2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.modules.junit4.common.internal.impl; import junit.runner.Version; public class JUnitVersion { public static boolean isGreaterThanOrEqualTo(String version) { final String currentVersion = getJUnitVersion(); return new VersionComparator().compare(currentVersion, version) >= 0; } public static String getJUnitVersion() { return Version.id(); } } ================================================ FILE: powermock-modules/powermock-module-junit4-common/src/main/java/org/powermock/modules/junit4/common/internal/impl/PowerMockJUnit4RunListener.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.modules.junit4.common.internal.impl; import org.junit.runner.Description; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunListener; import org.powermock.core.MockRepository; import org.powermock.reflect.Whitebox; import org.powermock.tests.utils.PowerMockTestNotifier; public class PowerMockJUnit4RunListener extends RunListener { private final ClassLoader mockClassLoader; private int failureCount; private int ignoreCount; private boolean currentTestSuccessful = true; private final PowerMockTestNotifier powerMockTestNotifier; public PowerMockJUnit4RunListener(ClassLoader mockClassLoader, PowerMockTestNotifier powerMockTestNotifier) { this.mockClassLoader = mockClassLoader; this.powerMockTestNotifier = powerMockTestNotifier; } /** * Performs clean up after each test. The {@link MockRepository#clear()} * methods has to be called by the correct class loader for the state to be * cleared. Therefore it is invoked using reflection when the class is * loaded from the correct class loader. */ @Override public void testFinished(Description description1) throws Exception { Class mockRepositoryClass = mockClassLoader.loadClass(MockRepository.class.getName()); try { notifyListenersOfTestResult(); } finally { // Clear state Whitebox.invokeMethod(mockRepositoryClass, "clear"); } } /** * @return The number of failed tests. */ public int getFailureCount() { return failureCount; } /** * @return The number of successful tests. */ public int getIgnoreCount() { return ignoreCount; } @Override public void testFailure(Failure failure) throws Exception { currentTestSuccessful = false; failureCount++; } @Override public void testIgnored(Description description) throws Exception { ignoreCount++; } private void notifyListenersOfTestResult() { try { powerMockTestNotifier.notifyAfterTestMethod(currentTestSuccessful); } finally { currentTestSuccessful = true; } } } ================================================ FILE: powermock-modules/powermock-module-junit4-common/src/main/java/org/powermock/modules/junit4/common/internal/impl/VersionComparator.java ================================================ /* * Copyright 2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.modules.junit4.common.internal.impl; import java.util.Comparator; /** * This code is copied from http://stackoverflow.com/questions/198431/how-do-you-compare-two-version-strings-in-java */ class VersionComparator implements Comparator { public boolean equals(Object o1, Object o2) { return compare(o1, o2) == 0; } @Override public int compare(Object o1, Object o2) { String version1 = (String) o1; String version2 = (String) o2; VersionTokenizer tokenizer1 = new VersionTokenizer(version1); VersionTokenizer tokenizer2 = new VersionTokenizer(version2); int number1 = 0, number2 = 0; String suffix1 = "", suffix2 = ""; while (tokenizer1.MoveNext()) { if (!tokenizer2.MoveNext()) { do { number1 = tokenizer1.getNumber(); suffix1 = tokenizer1.getSuffix(); if (number1 != 0 || suffix1.length() != 0) { // Version one is longer than number two, and non-zero return 1; } } while (tokenizer1.MoveNext()); // Version one is longer than version two, but zero return 0; } number1 = tokenizer1.getNumber(); suffix1 = tokenizer1.getSuffix(); number2 = tokenizer2.getNumber(); suffix2 = tokenizer2.getSuffix(); if (number1 < number2) { // Number one is less than number two return -1; } if (number1 > number2) { // Number one is greater than number two return 1; } boolean empty1 = suffix1.length() == 0; boolean empty2 = suffix2.length() == 0; if (empty1 && empty2) continue; // No suffixes if (empty1) return 1; // First suffix is empty (1.2 > 1.2b) if (empty2) return -1; // Second suffix is empty (1.2a < 1.2) // Lexical comparison of suffixes int result = suffix1.compareTo(suffix2); if (result != 0) return result; } if (tokenizer2.MoveNext()) { do { number2 = tokenizer2.getNumber(); suffix2 = tokenizer2.getSuffix(); if (number2 != 0 || suffix2.length() != 0) { // Version one is longer than version two, and non-zero return -1; } } while (tokenizer2.MoveNext()); // Version two is longer than version one, but zero return 0; } return 0; } } ================================================ FILE: powermock-modules/powermock-module-junit4-common/src/main/java/org/powermock/modules/junit4/common/internal/impl/VersionTokenizer.java ================================================ /* * Copyright 2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.modules.junit4.common.internal.impl; /** * This code is copied from http://stackoverflow.com/questions/198431/how-do-you-compare-two-version-strings-in-java */ class VersionTokenizer { private final String _versionString; private final int _length; private int _position; private int _number; private String _suffix; public int getNumber() { return _number; } public String getSuffix() { return _suffix; } public VersionTokenizer(String versionString) { if (versionString == null) throw new IllegalArgumentException("versionString is null"); _versionString = versionString; _length = versionString.length(); } public boolean MoveNext() { _number = 0; _suffix = ""; // No more characters if (_position >= _length) return false; while (_position < _length) { char c = _versionString.charAt(_position); if (c < '0' || c > '9') break; _number = _number * 10 + (c - '0'); _position++; } int suffixStart = _position; while (_position < _length) { char c = _versionString.charAt(_position); if (c == '.') break; _position++; } _suffix = _versionString.substring(suffixStart, _position); if (_position < _length) _position++; return true; } } ================================================ FILE: powermock-modules/powermock-module-junit4-common/src/test/java/org/powermock/modules/junit4/common/internal/impl/JUnitVersionTest.java ================================================ package org.powermock.modules.junit4.common.internal.impl; import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; public class JUnitVersionTest { @Test public void parses_version_numbers_with_chars() { assertThat(JUnitVersion.isGreaterThanOrEqualTo("4.90b2"), is(false)); } @Test public void parses_version_numbers_with_dash_snapshot() { assertThat(JUnitVersion.isGreaterThanOrEqualTo("4.19-SNAPSHOT"), is(false)); } @Test public void parses_version_numbers_with_dash_snapshot_where_version_is_before_current() { assertThat(JUnitVersion.isGreaterThanOrEqualTo("4.1-SNAPSHOT"), is(true)); } @Test public void parses_version_numbers_major_and_minor_versions() { assertThat(JUnitVersion.isGreaterThanOrEqualTo("4.1.5"), is(true)); } @Test public void parses_version_numbers_major_and_several_minor_versions() { assertThat(JUnitVersion.isGreaterThanOrEqualTo("4.44.5.6"), is(false)); } @Test public void parses_4_11_beta_1() { assertThat(JUnitVersion.isGreaterThanOrEqualTo("4.111-beta-1"), is(false)); } } ================================================ FILE: powermock-modules/powermock-module-junit4-legacy/src/main/java/org/powermock/modules/junit4/legacy/PowerMockRunner.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.modules.junit4.legacy; import org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner; import org.powermock.modules.junit4.legacy.internal.impl.PowerMockJUnit4LegacyRunnerDelegateImpl; public class PowerMockRunner extends AbstractCommonPowerMockRunner { public PowerMockRunner(Class klass) throws Exception { super(klass, PowerMockJUnit4LegacyRunnerDelegateImpl.class); } } ================================================ FILE: powermock-modules/powermock-module-junit4-legacy/src/main/java/org/powermock/modules/junit4/legacy/internal/impl/PowerMockJUnit4LegacyFilter.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.modules.junit4.legacy.internal.impl; import org.junit.runner.Description; import org.junit.runner.manipulation.Filter; /** * A JUnit filter that will filter the methods specified in String[] passed to * the constructor (i.e. these are the only tests that will be run for a * particular test class). * * @author Johan Haleby */ public class PowerMockJUnit4LegacyFilter extends Filter { private final String[] methodNamesToRun; public PowerMockJUnit4LegacyFilter(String[] methodNamesToRun) { this.methodNamesToRun = methodNamesToRun; } @Override public String describe() { return methodNamesToRun.length + " tests."; } @Override public boolean shouldRun(Description description) { boolean shouldRun = false; for (String testMethodName : methodNamesToRun) { if (testMethodName.equals(extractMethodName(description))) { shouldRun = true; break; } } return shouldRun; } private String extractMethodName(Description description) { final String displayName = description.getDisplayName(); /* * The test method name is the string to the left of the first * parenthesis. * testSayPrivateStatic(org.powermock.modules.junit4.legacy.singleton.StupidSingletonTest) * is an example of a display name. */ final int indexOfParenthesis = displayName.indexOf('('); if (indexOfParenthesis == -1) { throw new RuntimeException( "Internal error: Failed to find the test method name."); } return displayName.substring(0, indexOfParenthesis); } } ================================================ FILE: powermock-modules/powermock-module-junit4-legacy/src/main/java/org/powermock/modules/junit4/legacy/internal/impl/PowerMockJUnit4LegacyRunnerDelegateImpl.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.modules.junit4.legacy.internal.impl; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.internal.runners.BeforeAndAfterRunner; import org.junit.internal.runners.InitializationError; import org.junit.internal.runners.TestClassRunner; import org.junit.runner.manipulation.NoTestsRemainException; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunNotifier; import org.powermock.core.spi.PowerMockTestListener; import org.powermock.modules.junit4.common.internal.PowerMockJUnitRunnerDelegate; import org.powermock.modules.junit4.legacy.internal.impl.testcaseworkaround.PowerMockJUnit4LegacyTestClassMethodsRunner; import org.powermock.modules.junit4.legacy.internal.impl.testcaseworkaround.PowerMockJUnit4LegacyTestIntrospector; import org.powermock.reflect.Whitebox; import org.powermock.tests.utils.impl.MockPolicyInitializerImpl; /** * A JUnit4 legacy (i.e. v4.0-4.3) test runner that only runs a specified set of * test methods in a test class. * *

* Most parts of this class is essentially a rip off from * {@link TestClassRunner} used in JUnit 4.3. * * @see TestClassRunner * */ public class PowerMockJUnit4LegacyRunnerDelegateImpl extends TestClassRunner implements PowerMockJUnitRunnerDelegate { private final int testCount; public PowerMockJUnit4LegacyRunnerDelegateImpl(Class klass, String[] methodsToRun, PowerMockTestListener[] listeners) throws InitializationError, NoTestsRemainException { super(klass, new PowerMockJUnit4LegacyTestClassMethodsRunner(klass, listeners == null ? new PowerMockTestListener[0] : listeners)); filter(new PowerMockJUnit4LegacyFilter(methodsToRun)); testCount = methodsToRun.length; } public PowerMockJUnit4LegacyRunnerDelegateImpl(Class klass, String[] methodsToRun) throws InitializationError, NoTestsRemainException { this(klass, methodsToRun, null); } @Override public void run(final RunNotifier notifier) { BeforeAndAfterRunner runner = new BeforeAndAfterRunner(getTestClass(), BeforeClass.class, AfterClass.class, null) { @Override protected void runUnprotected() { fEnclosedRunner.run(notifier); } @Override protected void addFailure(Throwable targetException) { notifier.fireTestFailure(new Failure(getDescription(), targetException)); } }; Whitebox.setInternalState(runner, "fTestIntrospector", new PowerMockJUnit4LegacyTestIntrospector(getTestClass()), BeforeAndAfterRunner.class); // Initialize mock policies for each test final ClassLoader classLoader = this.getClass().getClassLoader(); new MockPolicyInitializerImpl(getTestClass()).initialize(classLoader); Thread.currentThread().setContextClassLoader(classLoader); runner.runProtected(); } public int getTestCount() { return testCount; } @Override public Class getTestClass() { return super.getTestClass(); } } ================================================ FILE: powermock-modules/powermock-module-junit4-legacy/src/main/java/org/powermock/modules/junit4/legacy/internal/impl/testcaseworkaround/PowerMockJUnit4LegacyTestClassMethodsRunner.java ================================================ package org.powermock.modules.junit4.legacy.internal.impl.testcaseworkaround; import junit.framework.TestCase; import org.junit.Ignore; import org.junit.Test; import org.junit.internal.runners.TestClassMethodsRunner; import org.junit.internal.runners.TestMethodRunner; import org.junit.runner.notification.RunNotifier; import org.powermock.core.spi.PowerMockTestListener; import org.powermock.reflect.Whitebox; import org.powermock.tests.utils.PowerMockTestNotifier; import org.powermock.tests.utils.impl.PowerMockTestNotifierImpl; import org.powermock.tests.utils.impl.StaticConstructorSuppressExtractorImpl; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.LinkedList; import java.util.List; /** * Since {@link TestClassMethodsRunner} creates a new instance of * TestInterceptor in its constructor we need to manually lookup the additional * methods that should be added when extending from {@code TestCase}. */ public class PowerMockJUnit4LegacyTestClassMethodsRunner extends TestClassMethodsRunner { private final PowerMockTestNotifier powerMockTestNotifier; @SuppressWarnings("unchecked") public PowerMockJUnit4LegacyTestClassMethodsRunner(Class klass, PowerMockTestListener[] powerMockTestListeners) { super(klass); this.powerMockTestNotifier = new PowerMockTestNotifierImpl(powerMockTestListeners); List testMethods = Whitebox.getInternalState(this, "fTestMethods", TestClassMethodsRunner.class); testMethods.addAll(getAdditionalTestMethods(klass)); } private List getAdditionalTestMethods(Class klass) { List additionalMethods = new LinkedList(); if (klass != null && klass.getSuperclass().equals(TestCase.class)) { /* * We now know that we need to add additional test methods because * JUnit4 ignores public methods with no @Test annotation when * extending from TestCase. */ Method[] methods = klass.getMethods(); for (Method method : methods) { if (isAdditionalTestMethod(method)) { additionalMethods.add(method); } } } return additionalMethods; } private boolean isAdditionalTestMethod(Method method) { return !method.isAnnotationPresent(Ignore.class) && method.getName().startsWith("test") && Modifier.isPublic(method.getModifiers()) && method.getReturnType().equals(Void.TYPE) && method.getAnnotation(Test.class) == null; } @Override protected TestMethodRunner createMethodRunner(Object test, Method method, RunNotifier notifier) { return new PowerMockJUnit4LegacyTestMethodRunner(test, method, notifier, methodDescription(method), powerMockTestNotifier); } @SuppressWarnings("unchecked") @Override public void run(RunNotifier notifier) { final List methods = Whitebox.getInternalState(this, "fTestMethods"); if (methods.isEmpty()) notifier.testAborted(getDescription(), new Exception("No runnable methods")); for (Method method : methods) { final StaticConstructorSuppressExtractorImpl staticConstructorSuppressExtractorImpl = new StaticConstructorSuppressExtractorImpl(); Class testType = getTestClass(); final ClassLoader thisClassLoader = getClass().getClassLoader(); if (!thisClassLoader.equals(testType.getClassLoader())) { /* * The test is loaded from another classloader, this means that * we cannot get the correct annotations if we don't load the * class from the correct class loader */ try { testType = thisClassLoader.loadClass(testType.getName()); } catch (ClassNotFoundException e) { // This should never happen throw new RuntimeException("Internal error in PowerMock", e); } } if (staticConstructorSuppressExtractorImpl.getTestClasses(method) == null) { staticConstructorSuppressExtractorImpl.getTestClasses(testType); } invokeTestMethod(method, notifier); } } } ================================================ FILE: powermock-modules/powermock-module-junit4-legacy/src/main/java/org/powermock/modules/junit4/legacy/internal/impl/testcaseworkaround/PowerMockJUnit4LegacyTestIntrospector.java ================================================ package org.powermock.modules.junit4.legacy.internal.impl.testcaseworkaround; import org.junit.Test; import org.junit.Test.None; import org.junit.internal.runners.TestIntrospector; import java.lang.reflect.Method; /** * A custom {@link TestIntrospector} that supports methods not annotated by the * Test annotation but should still be executed in the test case. This is * actually a workaround for the JUnit 4 test runner when the test case extends * from the {@code TestCase} class. */ public class PowerMockJUnit4LegacyTestIntrospector extends TestIntrospector { private static final long NO_TIMEOUT = 0L; public PowerMockJUnit4LegacyTestIntrospector(Class testClass) { super(testClass); } @SuppressWarnings("all") public long getTimeout(Method method) { Test annotation = method.getAnnotation(Test.class); long timeout = annotation == null ? NO_TIMEOUT : annotation.timeout(); return timeout; } @SuppressWarnings("all") public Class expectedException(Method method) { Test annotation = method.getAnnotation(Test.class); if (annotation == null || annotation.expected() == None.class) return null; else return annotation.expected(); } } ================================================ FILE: powermock-modules/powermock-module-junit4-legacy/src/main/java/org/powermock/modules/junit4/legacy/internal/impl/testcaseworkaround/PowerMockJUnit4LegacyTestMethodRunner.java ================================================ package org.powermock.modules.junit4.legacy.internal.impl.testcaseworkaround; import junit.framework.TestCase; import org.junit.internal.runners.BeforeAndAfterRunner; import org.junit.internal.runners.TestIntrospector; import org.junit.internal.runners.TestMethodRunner; import org.junit.runner.Description; import org.junit.runner.notification.RunNotifier; import org.powermock.reflect.Whitebox; import org.powermock.tests.utils.PowerMockTestNotifier; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * This class is needed because the test method runner creates a new instance of * a {@link TestIntrospector} in its constructor. The TestIntrospector needs to * be changed in order to support methods not annotated with Test to avoid * NPE's. *

* This class also executes the setUp and tearDown methods if the test case * extends TestCase. Another thing it does is to invoke all PowerMock test * listeners for events. */ public class PowerMockJUnit4LegacyTestMethodRunner extends TestMethodRunner { private final PowerMockJUnit4LegacyTestIntrospector testIntrospector; private final Method method; private final Description description; private final RunNotifier notifier; private final PowerMockTestNotifier powerMockTestNotifier; public PowerMockJUnit4LegacyTestMethodRunner(Object test, Method method, RunNotifier notifier, Description description, PowerMockTestNotifier powerMockTestNotifier) { super(test, method, notifier, description); this.method = method; this.description = description; this.notifier = notifier; this.powerMockTestNotifier = powerMockTestNotifier; testIntrospector = new PowerMockJUnit4LegacyTestIntrospector(test.getClass()); Whitebox.setInternalState(this, "fTestIntrospector", testIntrospector, TestMethodRunner.class); Whitebox.setInternalState(this, "fTestIntrospector", testIntrospector, BeforeAndAfterRunner.class); } @Override public void run() { if (testIntrospector.isIgnored(method)) { notifier.fireTestIgnored(description); return; } notifier.fireTestStarted(description); try { powerMockTestNotifier.notifyBeforeTestMethod(Whitebox.getInternalState(this, "fTest"), method, new Object[0]); long timeout = testIntrospector.getTimeout(method); // Execute the the setUp method if needed executeMethodInTestInstance("setUp"); if (timeout > 0) { // The runWithTimeout method is private in the super class, // invoke it using reflection. Whitebox.invokeMethod(this, TestMethodRunner.class, "runWithTimeout", timeout); } else { Whitebox.invokeMethod(this, TestMethodRunner.class, "runMethod"); } } catch (Exception e) { throw new RuntimeException(e); } finally { try { executeMethodInTestInstance("tearDown"); } finally { notifier.fireTestFinished(description); } } } /** * This method takes care of executing a method in the test object if * this object extends from {@link TestCase}. It can be used to execute the * setUp and tearDown methods for example. */ private void executeMethodInTestInstance(String methodName) { if (TestCase.class.isAssignableFrom(Whitebox.getInternalState(this, "fTest").getClass())) { Object object = Whitebox.getInternalState(this, "fTest"); try { if (object != null) { Whitebox.invokeMethod(object, methodName); } } catch (Throwable e) { if (e instanceof RuntimeException) { throw (RuntimeException) e; } throw new RuntimeException(e); } } } @Override protected void runUnprotected() { try { executeMethodBody(); if (expectsException()) addFailure(new AssertionError("Expected exception: " + expectedException().getName())); } catch (InvocationTargetException e) { Throwable actual = e.getTargetException(); if (!expectsException()) addFailure(actual); else if (isUnexpected(actual)) { String message = "Unexpected exception, expected<" + expectedException().getName() + "> but was<" + actual.getClass().getName() + ">"; addFailure(new Exception(message, actual)); } } catch (Throwable e) { addFailure(e); } } private boolean isUnexpected(Throwable exception) { return !expectedException().isAssignableFrom(exception.getClass()); } private boolean expectsException() { return expectedException() != null; } private Class expectedException() { return testIntrospector.expectedException(method); } } ================================================ FILE: powermock-modules/powermock-module-junit4-rule/src/main/java/org/powermock/modules/junit4/rule/PowerMockRule.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.modules.junit4.rule; import org.junit.rules.MethodRule; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.Statement; import org.powermock.api.support.SafeExceptionRethrower; import org.powermock.classloading.ClassloaderExecutor; import org.powermock.classloading.SingleClassloaderExecutor; import org.powermock.classloading.spi.DoNotClone; import org.powermock.core.MockRepository; import org.powermock.tests.utils.MockPolicyInitializer; import org.powermock.tests.utils.TestChunk; import org.powermock.tests.utils.TestSuiteChunker; import org.powermock.tests.utils.impl.MockPolicyInitializerImpl; public class PowerMockRule implements MethodRule { private static Class previousTargetClass; private static MockPolicyInitializer mockPolicyInitializer; @DoNotClone private static TestSuiteChunker testSuiteChunker; @Override public Statement apply(final Statement base, final FrameworkMethod method, final Object target) { if (isNotRuleInitialized(target)) { init(target); } return new PowerMockStatement(base, testSuiteChunker.getTestChunk(method.getMethod()), mockPolicyInitializer); } protected boolean isNotRuleInitialized(Object target) {return testSuiteChunker == null || previousTargetClass != target.getClass();} protected void init(Object target) { final Class testClass = target.getClass(); try { mockPolicyInitializer = new MockPolicyInitializerImpl(testClass); testSuiteChunker = new PowerMockRuleTestSuiteChunker(testClass); previousTargetClass = target.getClass(); } catch (Exception e) { throw new RuntimeException(e); } } } class PowerMockStatement extends Statement { private final Statement fNext; private final ClassloaderExecutor classloaderExecutor; private final MockPolicyInitializer mockPolicyInitializer; public PowerMockStatement(Statement fNext, TestChunk testChunk, MockPolicyInitializer mockPolicyInitializer) { this.fNext = fNext; this.mockPolicyInitializer = mockPolicyInitializer; this.classloaderExecutor = new SingleClassloaderExecutor(testChunk.getClassLoader()); } @Override public void evaluate() throws Throwable { classloaderExecutor.execute(new Runnable() { @Override public void run() { try { // Re-executes the policy method that might initialize mocks that // were cleared after the previous statement. // This fixes https://github.com/jayway/powermock/issues/581 mockPolicyInitializer.refreshPolicies(getClass().getClassLoader()); fNext.evaluate(); } catch (Throwable e) { SafeExceptionRethrower.safeRethrow(e); } finally { // Clear the mock repository after each test MockRepository.clear(); } } }); } } ================================================ FILE: powermock-modules/powermock-module-junit4-rule/src/main/java/org/powermock/modules/junit4/rule/PowerMockRuleTestSuiteChunker.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.modules.junit4.rule; import org.powermock.modules.junit4.common.internal.impl.JUnit4TestMethodChecker; import org.powermock.tests.utils.impl.AbstractCommonTestSuiteChunkerImpl; import java.lang.reflect.Method; /** * */ public class PowerMockRuleTestSuiteChunker extends AbstractCommonTestSuiteChunkerImpl { public PowerMockRuleTestSuiteChunker(Class testClass) throws Exception { super(testClass); } @Override public boolean shouldExecuteTestForMethod(Class testClass, Method potentialTestMethod) { return new JUnit4TestMethodChecker(testClass, potentialTestMethod).isTestMethod(); } } ================================================ FILE: powermock-modules/powermock-module-junit4-rule-agent/src/main/java/org/powermock/modules/junit4/rule/PowerMockRule.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.modules.junit4.rule; import org.junit.rules.MethodRule; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.Statement; import org.powermock.core.MockRepository; import org.powermock.core.agent.JavaAgentClassRegister; import org.powermock.core.agent.JavaAgentFrameworkRegister; import org.powermock.core.agent.JavaAgentFrameworkRegisterFactory; import org.powermock.modules.agent.PowerMockAgent; import org.powermock.modules.agent.support.JavaAgentClassRegisterImpl; import org.powermock.modules.agent.support.PowerMockAgentTestInitializer; import org.powermock.reflect.Whitebox; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Set; public class PowerMockRule implements MethodRule { static { if (PowerMockRule.class.getClassLoader() != ClassLoader.getSystemClassLoader()) { throw new IllegalStateException("PowerMockRule can only be used with the system classloader but was loaded by " + PowerMockRule.class.getClassLoader()); } PowerMockAgent.initializeIfPossible(); } @Override public Statement apply(Statement base, FrameworkMethod method, Object target) { JavaAgentClassRegister agentClassRegister = new JavaAgentClassRegisterImpl(); PowerMockAgentTestInitializer.initialize(target.getClass(), agentClassRegister); return new PowerMockStatement(base, target, agentClassRegister); } } class PowerMockStatement extends Statement { private static final String ANNOTATION_ENABLER = "org.powermock.api.extension.listener.AnnotationEnabler"; private final Statement fNext; private final Object target; private final JavaAgentClassRegister agentClassRegister; private final JavaAgentFrameworkRegister javaAgentFrameworkRegister; public PowerMockStatement(Statement base, Object target, JavaAgentClassRegister agentClassRegister) { this.fNext = base; this.target = target; this.agentClassRegister = agentClassRegister; this.javaAgentFrameworkRegister = JavaAgentFrameworkRegisterFactory.create(); } @Override public void evaluate() throws Throwable { Object annotationEnabler = loadAnnotationEnableIfPresent(); try { injectMocksUsingAnnotationEnabler(target, annotationEnabler); setFrameworkAgentClassRegister(); fNext.evaluate(); } finally { // Clear the mock repository after each test MockRepository.clear(); clearMockFields(target, annotationEnabler); clearFrameworkAgentClassRegister(); } } private void clearFrameworkAgentClassRegister() { agentClassRegister.clear(); javaAgentFrameworkRegister.clear(); } private void setFrameworkAgentClassRegister() { javaAgentFrameworkRegister.set(agentClassRegister); } private Object loadAnnotationEnableIfPresent() { boolean hasAnnotationEnabler = hasAnnotationEnablerClass(); if (!hasAnnotationEnabler) { return null; } try { return Whitebox.invokeConstructor(Class.forName(ANNOTATION_ENABLER, true, Thread.currentThread().getContextClassLoader())); } catch (Exception e) { throw new RuntimeException("PowerMock internal error, failed to load annotation enabler."); } } private boolean hasAnnotationEnablerClass() { try { Class.forName(ANNOTATION_ENABLER, false, Thread.currentThread().getContextClassLoader()); return true; } catch (ClassNotFoundException e) { return false; } } private void clearMockFields(Object target, Object annotationEnabler) throws Exception { if (annotationEnabler != null) { Class[] mockAnnotations = Whitebox.invokeMethod(annotationEnabler, "getMockAnnotations"); Set mockFields = Whitebox.getFieldsAnnotatedWith(target, mockAnnotations); for (Field field : mockFields) { field.set(target, null); } } } private void injectMocksUsingAnnotationEnabler(Object target, Object annotationEnabler) throws Exception { if (annotationEnabler != null) { Whitebox.invokeMethod(annotationEnabler, "beforeTestMethod", new Class[]{Object.class, Method.class, Object[].class}, target, null, null); } } } ================================================ FILE: powermock-modules/powermock-module-testng/src/main/java/org/powermock/modules/testng/PowerMockObjectFactory.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.modules.testng; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor; import org.powermock.modules.testng.internal.PowerMockClassloaderObjectFactory; import org.testng.IObjectFactory; import org.testng.internal.ObjectFactoryImpl; import java.lang.reflect.Constructor; import java.lang.reflect.Method; /** * The PowerMock object factory. If the test class or any public method declared in the test class is annotated with * {@link PrepareForTest} or {@link SuppressStaticInitializationFor} the PowerMock classloader will enable the class * for PowerMock testing, otherwise a standard ObjectFactory is used. */ public class PowerMockObjectFactory implements IObjectFactory { private PowerMockClassloaderObjectFactory powerMockObjectFactory = new PowerMockClassloaderObjectFactory(); private ObjectFactoryImpl defaultObjectFactory = new ObjectFactoryImpl(); @Override public Object newInstance(Constructor constructor, Object... params) { final Object testInstance; Class testClass = constructor.getDeclaringClass(); if (hasPowerMockAnnotation(testClass)) { testInstance = powerMockObjectFactory.newInstance(constructor, params); } else { testInstance = defaultObjectFactory.newInstance(constructor, params); } return testInstance; } private boolean hasPowerMockAnnotation(Class testClass) { return isClassAnnotatedWithPowerMockAnnotation(testClass) || anyMethodInClassHasPowerMockAnnotation(testClass); } private boolean anyMethodInClassHasPowerMockAnnotation(Class testClass) { final Method[] methods = testClass.getMethods(); for (Method method : methods) { if(method.isAnnotationPresent(PrepareForTest.class) || method.isAnnotationPresent(SuppressStaticInitializationFor.class)) { return true; } } return false; } private boolean isClassAnnotatedWithPowerMockAnnotation(Class testClass) { return testClass.isAnnotationPresent(PrepareForTest.class) || testClass.isAnnotationPresent(SuppressStaticInitializationFor.class); } } ================================================ FILE: powermock-modules/powermock-module-testng/src/main/java/org/powermock/modules/testng/internal/Assumes.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.modules.testng.internal; import org.testng.SkipException; /** * */ public class Assumes { public static void assumeTrue(String reason, boolean assertion) { if (!assertion) { throw new SkipException(reason); } } } ================================================ FILE: powermock-modules/powermock-module-testng/src/main/java/org/powermock/modules/testng/internal/PowerMockClassloaderObjectFactory.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.modules.testng.internal; import org.powermock.core.MockRepository; import org.testng.IObjectFactory; import java.lang.reflect.Constructor; public class PowerMockClassloaderObjectFactory implements IObjectFactory { private final TestNGMockClassLoaderFactory classLoaderFactory; public PowerMockClassloaderObjectFactory() { classLoaderFactory = new TestNGMockClassLoaderFactory(); } @Override public Object newInstance(Constructor constructor, Object... params) { /* * For extra safety clear the MockitoRepository on each new * instantiation of the object factory. This is good in cases where a * previous test has used e.g. PowerMock#createMock(..) to create a mock * without using this factory. That means that there's some state left in * the MockRepository that hasn't been cleared. Currently clearing the * MockRepository from any classloader will clear the previous state but * it's not certain that this is always the case. */ MockRepository.clear(); return new TestClassInstanceFactory(constructor, classLoaderFactory, params).create(); } } ================================================ FILE: powermock-modules/powermock-module-testng/src/main/java/org/powermock/modules/testng/internal/PowerMockExpectedExceptionsExtractorImpl.java ================================================ /* * Copyright 2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.modules.testng.internal; import org.powermock.tests.utils.IgnorePackagesExtractor; import org.testng.annotations.Test; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Method; import java.util.Arrays; import java.util.LinkedList; import java.util.List; public class PowerMockExpectedExceptionsExtractorImpl implements IgnorePackagesExtractor { public String[] getPackagesToIgnore(AnnotatedElement element) { List ignoredPackages = new LinkedList(); if (element instanceof Class) { Class klazz = (Class) element; for (Method method : klazz.getMethods()) { Test annotation = method.getAnnotation(Test.class); if (annotation != null) { Class[] ignores = annotation.expectedExceptions(); if (ignores != null) { for (Class ignorePackage : ignores) { ignoredPackages.add(ignorePackage.getName()); } } } } Class superclass = klazz.getSuperclass(); if (superclass != null && !superclass.equals(Object.class)) { String[] packagesToIgnore = getPackagesToIgnore(superclass); ignoredPackages.addAll(Arrays.asList(packagesToIgnore)); } } return ignoredPackages.toArray(new String[ignoredPackages.size()]); } } ================================================ FILE: powermock-modules/powermock-module-testng/src/main/java/org/powermock/modules/testng/internal/PowerMockTestNGMethodHandler.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.modules.testng.internal; import javassist.util.proxy.MethodHandler; import org.powermock.core.MockRepository; import org.powermock.reflect.Whitebox; import org.testng.annotations.Test; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Set; /* * Javassist handler that takes care of cleaning up {@link MockRepository} state * after each method annotated with {@link Test}. */ public class PowerMockTestNGMethodHandler implements MethodHandler { private Object annotationEnabler; public PowerMockTestNGMethodHandler(Class testClass) { try { Class annotationEnablerClass = Class.forName("org.powermock.api.extension.listener.AnnotationEnabler"); annotationEnabler = Whitebox.newInstance(annotationEnablerClass); } catch (ClassNotFoundException e) { annotationEnabler = null; } } @Override public Object invoke(Object self, Method thisMethod, Method proceed, Object[] args) throws Throwable { injectMocksUsingAnnotationEnabler(self); try { final Object result = proceed.invoke(self, args); return result; } catch (InvocationTargetException e) { throw e.getTargetException(); } finally { if (thisMethod.isAnnotationPresent(Test.class)) { clearMockFields(); MockRepository.clear(); } } } private void clearMockFields() throws Exception, IllegalAccessException { if (annotationEnabler != null) { Set mockFields = Whitebox.getFieldsAnnotatedWith(this, Whitebox .[]> invokeMethod(annotationEnabler, "getMockAnnotations")); for (Field field : mockFields) { field.set(this, null); } } } private void injectMocksUsingAnnotationEnabler(Object self) throws Exception { if (annotationEnabler != null) { Whitebox.invokeMethod(annotationEnabler, "beforeTestMethod", new Class[] { Object.class, Method.class, Object[].class }, self, null, null); } } } ================================================ FILE: powermock-modules/powermock-module-testng/src/main/java/org/powermock/modules/testng/internal/TestClassInstanceFactory.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.modules.testng.internal; import javassist.util.proxy.ProxyFactory; import org.powermock.modules.testng.PowerMockTestCase; import org.powermock.reflect.Whitebox; import org.powermock.tests.utils.impl.MockPolicyInitializerImpl; import java.lang.reflect.Constructor; class TestClassInstanceFactory { private final Constructor constructor; private final Class testClass; private final Object[] params; private final ClassLoader mockLoader; TestClassInstanceFactory(Constructor constructor, TestNGMockClassLoaderFactory classLoaderFactory, Object... params) { this.constructor = constructor; this.params = params; this.testClass = constructor.getDeclaringClass(); this.mockLoader = classLoaderFactory.createClassLoader(testClass); } Object create() { try { initializeMockPolicy(); final Class testClassLoadedByMockedClassLoader = createTestClass(testClass); final Constructor con = testClassLoadedByMockedClassLoader.getConstructor(constructor.getParameterTypes()); final Object testInstance = con.newInstance(params); if (!extendsPowerMockTestCase(testClass)) { setInvocationHandler(testInstance); } return testInstance; } catch (Exception e) { throw new RuntimeException(String.format("Cannot create a new instance of test class %s", testClass), e); } } private void initializeMockPolicy() {new MockPolicyInitializerImpl(testClass).initialize(mockLoader);} /** * We proxy the test class in order to be able to clear state after each * test method invocation. It would be much better to be able to register a * testng listener programmtically but I cannot find a way to do so. */ private Class createTestClass(Class actualTestClass) throws Exception { final Class testClassLoadedByMockedClassLoader = Class.forName(actualTestClass.getName(), false, mockLoader); if (extendsPowerMockTestCase(actualTestClass)) { return testClassLoadedByMockedClassLoader; } else { return createProxyTestClass(testClassLoadedByMockedClassLoader); } } private Class createProxyTestClass(Class testClassLoadedByMockedClassLoader) throws Exception { Class proxyFactoryClass = Class.forName(ProxyFactory.class.getName(), false, mockLoader); final Class testNGMethodFilterByMockedClassLoader = Class.forName(TestNGMethodFilter.class.getName(), false, mockLoader); Object f = proxyFactoryClass.newInstance(); Object filter = testNGMethodFilterByMockedClassLoader.newInstance(); Whitebox.invokeMethod(f, "setFilter", filter); Whitebox.invokeMethod(f, "setSuperclass", testClassLoadedByMockedClassLoader); return Whitebox.invokeMethod(f, "createClass"); } private void setInvocationHandler(Object testInstance) throws Exception { Class powerMockTestNGMethodHandlerClass = Class.forName(PowerMockTestNGMethodHandler.class.getName(), false, mockLoader); Object powerMockTestNGMethodHandlerInstance = powerMockTestNGMethodHandlerClass.getConstructor(Class.class) .newInstance( testInstance.getClass()); Whitebox.invokeMethod(testInstance, "setHandler", powerMockTestNGMethodHandlerInstance); } private boolean extendsPowerMockTestCase(Class actualTestClass) { return PowerMockTestCase.class.isAssignableFrom(actualTestClass); } } ================================================ FILE: powermock-modules/powermock-module-testng/src/main/java/org/powermock/modules/testng/internal/TestNGMethodFilter.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.modules.testng.internal; import javassist.util.proxy.MethodFilter; import java.lang.reflect.Method; /** * Javassist method filter that ignores the toString, equals, finalize and * hashCode method otherwise the test output in Maven looks strange and * replayAll/verifyAll doesn't work as expected. */ public class TestNGMethodFilter implements MethodFilter { @Override public boolean isHandled(Method method) { return !isToString(method) && !isHashCode(method) && !isFinalize(method) && !isEquals(method); } private boolean isEquals(Method method) { return method.getName().equals("equals") && isOneArgumentMethodOfType(method, Object.class); } private boolean isFinalize(Method method) { return method.getName().equals("finalize") && isZeroArgumentMethod(method); } private boolean isHashCode(Method method) { return method.getName().equals("hashCode") && isZeroArgumentMethod(method); } private boolean isToString(Method method) { return (method.getName().equals("toString") && isZeroArgumentMethod(method)); } private boolean isZeroArgumentMethod(Method method) { return hasArgumentLength(method, 0); } private boolean hasArgumentLength(Method method, int length) { return method.getParameterTypes().length == length; } private boolean isOneArgumentMethodOfType(Method method, Class type) { return hasArgumentLength(method, 1) && Object.class.equals(method.getParameterTypes()[0]); } } ================================================ FILE: powermock-modules/powermock-module-testng/src/main/java/org/powermock/modules/testng/internal/TestNGMockClassLoaderFactory.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.modules.testng.internal; import org.powermock.core.classloader.MockClassLoaderFactory; import org.powermock.tests.utils.ArrayMerger; import org.powermock.tests.utils.IgnorePackagesExtractor; import org.powermock.tests.utils.impl.ArrayMergerImpl; import org.powermock.tests.utils.impl.PowerMockIgnorePackagesExtractorImpl; class TestNGMockClassLoaderFactory { private final IgnorePackagesExtractor ignorePackagesExtractor; private final IgnorePackagesExtractor expectedExceptionsExtractor; private final ArrayMerger arrayMerger; TestNGMockClassLoaderFactory() { ignorePackagesExtractor = new PowerMockIgnorePackagesExtractorImpl(); expectedExceptionsExtractor = new PowerMockExpectedExceptionsExtractorImpl(); arrayMerger = new ArrayMergerImpl(); } ClassLoader createClassLoader(Class testClass) { final String[] packagesToIgnore = arrayMerger.mergeArrays( String.class, ignorePackagesExtractor.getPackagesToIgnore(testClass), expectedExceptionsExtractor.getPackagesToIgnore(testClass) ); return new MockClassLoaderFactory(testClass, packagesToIgnore).createForClass(null); } } ================================================ FILE: powermock-modules/powermock-module-testng-agent/src/main/java/org/powermock/modules/testng/PowerMockObjectFactory.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.modules.testng; import org.powermock.core.agent.JavaAgentClassRegister; import org.powermock.modules.agent.PowerMockAgent; import org.powermock.modules.agent.support.JavaAgentClassRegisterImpl; import org.powermock.modules.agent.support.PowerMockAgentTestInitializer; import org.testng.IObjectFactory; import org.testng.internal.ObjectFactoryImpl; import java.lang.reflect.Constructor; /** * The PowerMock object factory for PowerMock java agent. */ public class PowerMockObjectFactory implements IObjectFactory { static { if (PowerMockObjectFactory.class.getClassLoader() != ClassLoader.getSystemClassLoader()) { throw new IllegalStateException("PowerMockObjectFactory can only be used with the system classloader but was loaded by " + PowerMockObjectFactory.class.getClassLoader()); } PowerMockAgent.initializeIfPossible(); } private final ObjectFactoryImpl defaultObjectFactory; public PowerMockObjectFactory() { defaultObjectFactory = new ObjectFactoryImpl(); } @Override public Object newInstance(Constructor constructor, Object... params) { final Class testClass = constructor.getDeclaringClass(); JavaAgentClassRegister agentClassRegister = new JavaAgentClassRegisterImpl(); PowerMockAgentTestInitializer.initialize(testClass, agentClassRegister); return defaultObjectFactory.newInstance(constructor, params); } } ================================================ FILE: powermock-modules/powermock-module-testng-common/src/main/java/org/powermock/modules/testng/PowerMockTestCase.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.modules.testng; import org.powermock.core.MockRepository; import org.powermock.core.classloader.MockClassLoader; import org.powermock.reflect.Whitebox; import org.testng.IObjectFactory; import org.testng.ITestContext; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.ObjectFactory; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Set; /** * A PowerMock base class that may be used as a base class for all TestNG * test cases that uses PowerMock. */ public class PowerMockTestCase { private Object annotationEnabler; private ClassLoader previousCl = null; public PowerMockTestCase() { try { Class annotationEnablerClass = Class.forName("org.powermock.api.extension.listener.AnnotationEnabler"); annotationEnabler = Whitebox.newInstance(annotationEnablerClass); } catch (ClassNotFoundException e) { annotationEnabler = null; } } @BeforeClass protected void beforePowerMockTestClass() throws Exception { // To make sure that the mock repository is not in an incorrect state when the test begins MockRepository.clear(); if(isLoadedByPowerMockClassloader()) { final Thread thread = Thread.currentThread(); previousCl = thread.getContextClassLoader(); thread.setContextClassLoader(this.getClass().getClassLoader()); } } @AfterClass protected void afterPowerMockTestClass() throws Exception { if(previousCl != null) { Thread.currentThread().setContextClassLoader(previousCl); } } /** * Must be executed before each test method. This method does the following: *

    *
  1. Injects all mock fields (if they haven't been injected already)
  2. *
* * * * @throws Exception * If something unexpected goes wrong. */ @BeforeMethod protected void beforePowerMockTestMethod() throws Exception { injectMocks(); } /** * Must be executed after each test method. This method does the following: *
    *
  1. Clear all injection fields (those annotated with a Mock annotation)
  2. *
  3. Clears the PowerMock MockRepository
  4. *
* * @throws Exception if something unexpected goes wrong. */ @AfterMethod protected void afterPowerMockTestMethod() throws Exception { try { clearMockFields(); } finally { MockRepository.clear(); } } /** * @param context the test context. * @return The PowerMock object factory. */ @ObjectFactory public IObjectFactory create(ITestContext context) { try { final Class powerMockObjectFactory = Class.forName("org.powermock.modules.testng.PowerMockObjectFactory"); return (IObjectFactory) powerMockObjectFactory.newInstance(); } catch (ClassNotFoundException e) { throw new IllegalStateException("Missing org.powermock.modules.testng.PowerMockObjectFactory in classpath."); } catch (Exception e) { throw new RuntimeException("PowerMock internal error", e); } } private void clearMockFields() throws Exception { if (annotationEnabler != null) { final Class[] mockAnnotations = Whitebox.invokeMethod(annotationEnabler, "getMockAnnotations"); Set mockFields = Whitebox.getFieldsAnnotatedWith(this, mockAnnotations); for (Field field : mockFields) { field.set(this, null); } } } private void injectMocks() throws Exception { if (annotationEnabler != null) { Whitebox.invokeMethod(annotationEnabler, "beforeTestMethod", new Class[] { Object.class, Method.class, Object[].class }, this, null, null); } } private boolean isLoadedByPowerMockClassloader() { return this.getClass().getClassLoader() instanceof MockClassLoader; } } ================================================ FILE: powermock-reflect/build.gradle ================================================ ================================================ FILE: powermock-reflect/src/main/java/org/powermock/reflect/Whitebox.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.reflect; import org.powermock.reflect.exceptions.ConstructorNotFoundException; import org.powermock.reflect.exceptions.FieldNotFoundException; import org.powermock.reflect.exceptions.MethodNotFoundException; import org.powermock.reflect.exceptions.TooManyMethodsFoundException; import org.powermock.reflect.internal.WhiteboxImpl; import org.powermock.reflect.matching.FieldMatchingStrategy; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Set; /** * Various utilities for accessing internals of a class. Basically a simplified * reflection utility intended for tests. */ public class Whitebox { /** * Convenience method to get a field from a class type. *

* The method will first try to look for a declared field in the same class. * If the field is not declared in this class it will look for the field in * the super class. This will continue throughout the whole class hierarchy. * If the field is not found an {@link IllegalArgumentException} is thrown. * * @param type * The type of the class where the method is located. * @param fieldName * The method names. * @return A {@code java.lang.reflect.Field}. * @throws FieldNotFoundException * If a field cannot be found in the hierarchy. */ public static Field getField(Class type, String fieldName) { return WhiteboxImpl.getField(type, fieldName); } /** * Get an array of {@link Field}'s that matches the supplied list of field * names. * * @param clazz * The class that should contain the fields. * @param fieldNames * The names of the fields that will be returned. * @return An array of Field's. May be of length 0 but not {@code null} * */ public static Field[] getFields(Class clazz, String... fieldNames) { return WhiteboxImpl.getFields(clazz, fieldNames); } /** * Convenience method to get a method from a class type without having to * catch the checked exceptions otherwise required. These exceptions are * wrapped as runtime exceptions. *

* The method will first try to look for a declared method in the same * class. If the method is not declared in this class it will look for the * method in the super class. This will continue throughout the whole class * hierarchy. If the method is not found an {@link IllegalArgumentException} * is thrown. * * @param type * The type of the class where the method is located. * @param methodName * The method names. * @param parameterTypes * All parameter types of the method (may be {@code null}). * @return A {@code java.lang.reflect.Method}. * @throws MethodNotFoundException * If a method cannot be found in the hierarchy. */ public static Method getMethod(Class type, String methodName, Class... parameterTypes) { return WhiteboxImpl.getMethod(type, methodName, parameterTypes); } /** * Convenience method to get a method from a class type without having to * catch the checked exceptions otherwise required. These exceptions are * wrapped as runtime exceptions. *

* The method will first try to look for a declared method in the same * class. If the method is not declared in this class it will look for the * method in the super class. This will continue throughout the whole class * hierarchy. If the method is not found an {@link MethodNotFoundException} * is thrown. Since the method name is not specified an * {@link TooManyMethodsFoundException} is thrown if two or more methods * matches the same parameter types in the same class. * * @param type * The type of the class where the method is located. * @param parameterTypes * All parameter types of the method (may be {@code null}). * @return A {@code java.lang.reflect.Method}. * @throws MethodNotFoundException * If a method cannot be found in the hierarchy. * @throws TooManyMethodsFoundException * If several methods were found. */ public static Method getMethod(Class type, Class... parameterTypes) { return WhiteboxImpl.getMethod(type, parameterTypes); } /** * Create a new instance of a class without invoking its constructor. *

* No byte-code manipulation is needed to perform this operation and thus * it's not necessary use the {@code PowerMockRunner} or * {@code PrepareForTest} annotation to use this functionality. * * @param * The type of the instance to create. * @param classToInstantiate * The type of the instance to create. * @return A new instance of type T, created without invoking the * constructor. */ public static T newInstance(Class classToInstantiate) { return WhiteboxImpl.newInstance(classToInstantiate); } /** * Convenience method to get a (declared) constructor from a class type * without having to catch the checked exceptions otherwise required. These * exceptions are wrapped as runtime exceptions. The constructor is also set * to accessible. * * @param type * The type of the class where the constructor is located. * @param parameterTypes * All parameter types of the constructor (may be * {@code null}). * @return A {@code java.lang.reflect.Constructor}. * @throws ConstructorNotFoundException * if the constructor cannot be found. */ public static Constructor getConstructor(Class type, Class... parameterTypes) { return (Constructor) WhiteboxImpl.getConstructor(type, parameterTypes); } /** * Set the value of a field using reflection. This method will traverse the * super class hierarchy until a field with name fieldName is * found. * * @param object * the object whose field to modify * @param fieldName * the name of the field * @param value * the new value of the field */ public static void setInternalState(Object object, String fieldName, Object value) { WhiteboxImpl.setInternalState(object, fieldName, value); } /** * Set an array value of a field using reflection. This method will traverse * the super class hierarchy until a field with name fieldName is * found. * * @param object * the object to modify * @param fieldName * the name of the field * @param value * the new value of the field */ public static void setInternalState(Object object, String fieldName, Object[] value) { WhiteboxImpl.setInternalState(object, fieldName, value); } /** * Set the value of a field using reflection. This method will traverse the * super class hierarchy until the first field assignable to the * value type is found. The value (or * additionaValues if present) will then be assigned to this field. * * @param object * the object to modify * @param value * the new value of the field * @param additionalValues * Additional values to set on the object */ public static void setInternalState(Object object, Object value, Object... additionalValues) { WhiteboxImpl.setInternalState(object, value, additionalValues); } /** * Set the value of a field using reflection at at specific place in the * class hierarchy (where). This first field assignable to * object will then be set to value. * * @param object * the object to modify * @param value * the new value of the field * @param where * the class in the hierarchy where the field is defined */ public static void setInternalState(Object object, Object value, Class where) { WhiteboxImpl.setInternalState(object, value, where); } /** * Set the value of a field using reflection. Use this method when you need * to specify in which class the field is declared. This might be useful * when you have mocked the instance you are trying to modify. * * @param object * the object to modify * @param fieldName * the name of the field * @param value * the new value of the field * @param where * the class in the hierarchy where the field is defined */ public static void setInternalState(Object object, String fieldName, Object value, Class where) { WhiteboxImpl.setInternalState(object, fieldName, value, where); } /** * Set the value of a field using reflection. This method will traverse the * super class hierarchy until the first field of type fieldType is * found. The value will then be assigned to this field. * * @param object * the object to modify * @param fieldType * the type of the field * @param value * the new value of the field */ public static void setInternalState(Object object, Class fieldType, Object value) { WhiteboxImpl.setInternalState(object, fieldType, value); } /** * Set the value of a field using reflection at a specific location ( * where) in the class hierarchy. The value will then be * assigned to this field. The first field matching the fieldType * in the hierarchy will be set. * * @param object * the object to modify * @param fieldType * the type of the field the should be set. * @param value * the new value of the field * @param where * which class in the hierarchy defining the field */ public static void setInternalState(Object object, Class fieldType, Object value, Class where) { WhiteboxImpl.setInternalState(object, fieldType, value, where); } /** * Get the value of a field using reflection. This method will iterate * through the entire class hierarchy and return the value of the first * field named fieldName. If you want to get a specific field value * at specific place in the class hierarchy please refer to * {@link #getInternalState(Object, String, Class)}. * * @param object * the object to modify * @param fieldName * the name of the field */ public static T getInternalState(Object object, String fieldName) { return WhiteboxImpl.getInternalState(object, fieldName); } /** * Get the value of a field using reflection. Use this method when you need * to specify in which class the field is declared. This might be useful * when you have mocked the instance you are trying to access. * * @param object * the object to modify * @param fieldName * the name of the field * @param where * which class the field is defined */ public static T getInternalState(Object object, String fieldName, Class where) { return WhiteboxImpl.getInternalState(object, fieldName, where); } /** * Get the value of a field using reflection. Use this method when you need * to specify in which class the field is declared. This might be useful * when you have mocked the instance you are trying to access. Use this * method to avoid casting. * * @deprecated Use {@link #getInternalState(Object, String, Class)} instead. * * @param * the expected type of the field * @param object * the object to modify * @param fieldName * the name of the field * @param where * which class the field is defined * @param type * the expected type of the field */ @Deprecated public static T getInternalState(Object object, String fieldName, Class where, Class type) { return Whitebox.getInternalState(object, fieldName, where); } /** * Get the value of a field using reflection based on the fields type. This * method will traverse the super class hierarchy until the first field of * type fieldType is found. The value of this field will be * returned. * * @param object * the object to modify * @param fieldType * the type of the field */ public static T getInternalState(Object object, Class fieldType) { return WhiteboxImpl.getInternalState(object, fieldType); } /** * Get the value of a field using reflection based on the field type. Use * this method when you need to specify in which class the field is * declared. The first field matching the fieldType in * where is the field whose value will be returned. * * @param * the expected type of the field * @param object * the object to modify * @param fieldType * the type of the field * @param where * which class the field is defined */ public static T getInternalState(Object object, Class fieldType, Class where) { return WhiteboxImpl.getInternalState(object, fieldType, where); } /** * Invoke a private or inner class method without the need to specify the * method name. This is thus a more refactor friendly version of the * {@link #invokeMethod(Object, String, Object...)} method and is recommend * over this method for that reason. This method might be useful to test * private methods. * * @throws Exception if something wrong. */ public static synchronized T invokeMethod(Object instance, Object... arguments) throws Exception { return WhiteboxImpl.invokeMethod(instance, arguments); } /** * Invoke a private or inner class static method without the need to specify * the method name. This is thus a more refactor friendly version of the * {@link #invokeMethod(Class, String, Object...)} method and is recommend * over this method for that reason. This method might be useful to test * private methods. * */ public static synchronized T invokeMethod(Class klass, Object... arguments) throws Exception { return WhiteboxImpl.invokeMethod(klass, arguments); } /** * Invoke a private or inner class method. This might be useful to test * private methods. */ public static synchronized T invokeMethod(Object instance, String methodToExecute, Object... arguments) throws Exception { return WhiteboxImpl.invokeMethod(instance, methodToExecute, arguments); } /** * Invoke a private or inner class method in cases where PowerMock cannot * automatically determine the type of the parameters, for example when * mixing primitive types and wrapper types in the same method. For most * situations use {@link #invokeMethod(Object, Object...)} instead. * * @throws Exception * Exception that may occur when invoking this method. */ public static synchronized T invokeMethod(Object instance, String methodToExecute, Class[] argumentTypes, Object... arguments) throws Exception { return WhiteboxImpl.invokeMethod(instance, methodToExecute, argumentTypes, arguments); } /** * Invoke a private or inner class method in a subclass (defined by * {@code definedIn}) in cases where PowerMock cannot automatically * determine the type of the parameters, for example when mixing primitive * types and wrapper types in the same method. For most situations use * {@link #invokeMethod(Object, Object...)} instead. * * @throws Exception * Exception that may occur when invoking this method. */ public static synchronized T invokeMethod(Object instance, String methodToExecute, Class definedIn, Class[] argumentTypes, Object... arguments) throws Exception { return WhiteboxImpl.invokeMethod(instance, methodToExecute, definedIn, argumentTypes, arguments); } /** * Invoke a private or inner class method in that is located in a subclass * of the instance. This might be useful to test private methods. * * @throws Exception * Exception that may occur when invoking this method. */ public static synchronized T invokeMethod(Object instance, Class declaringClass, String methodToExecute, Object... arguments) throws Exception { return WhiteboxImpl.invokeMethod(instance, declaringClass, methodToExecute, arguments); } /** * Invoke a private or inner class method in that is located in a subclass * of the instance. This might be useful to test private methods. *

* Use this for overloaded methods. * * @throws Exception * Exception that may occur when invoking this method. */ public static synchronized T invokeMethod(Object object, Class declaringClass, String methodToExecute, Class[] parameterTypes, Object... arguments) throws Exception { return WhiteboxImpl.invokeMethod(object, declaringClass, methodToExecute, parameterTypes, arguments); } /** * Invoke a static private or inner class method. This may be useful to test * private methods. * */ public static synchronized T invokeMethod(Class clazz, String methodToExecute, Object... arguments) throws Exception { return WhiteboxImpl.invokeMethod(clazz, methodToExecute, arguments); } /** * Invoke a constructor. Useful for testing classes with a private * constructor when PowerMock cannot determine which constructor to invoke. * This only happens if you have two constructors with the same number of * arguments where one is using primitive data types and the other is using * the wrapped counter part. For example: * *

	 * public class MyClass {
	 *     private MyClass(Integer i) {
	 *         ...
	 *     } 
	 * 
	 *     private MyClass(int i) {
	 *         ...
	 *     }
	 * 
* * This ought to be a really rare case. So for most situation, use * {@link #invokeConstructor(Class, Object...)} instead. * * * @return The object created after the constructor has been invoked. * @throws Exception * If an exception occur when invoking the constructor. */ public static T invokeConstructor(Class classThatContainsTheConstructorToTest, Class[] parameterTypes, Object[] arguments) throws Exception { return WhiteboxImpl.invokeConstructor(classThatContainsTheConstructorToTest, parameterTypes, arguments); } /** * Invoke a constructor. Useful for testing classes with a private * constructor. * * * @return The object created after the constructor has been invoked. * @throws Exception * If an exception occur when invoking the constructor. */ public static T invokeConstructor(Class classThatContainsTheConstructorToTest, Object... arguments) throws Exception { return WhiteboxImpl.invokeConstructor(classThatContainsTheConstructorToTest, arguments); } /** * Get the first parent constructor defined in a super class of * {@code klass}. * * @param klass * The class where the constructor is located. {@code null} * ). * @return A {@code java.lang.reflect.Constructor}. */ public static Constructor getFirstParentConstructor(Class klass) { return WhiteboxImpl.getFirstParentConstructor(klass); } /** * Get an array of {@link Method}'s that matches the supplied list of method * names. Both instance and static methods are taken into account. * * @param clazz * The class that should contain the methods. * @param methodNames * Names of the methods that will be returned. * @return An array of Method's. * @throws MethodNotFoundException * If no method was found. */ public static Method[] getMethods(Class clazz, String... methodNames) { return WhiteboxImpl.getMethods(clazz, methodNames); } /** * @return The type of the of an object. */ public static Class getType(Object object) { return WhiteboxImpl.getType(object); } /** * Gets the type. * * @param object the object * @return The type of the of an object. */ public static Class getUnproxyType(Object object) { return WhiteboxImpl.getUnproxyType(object); } /** * Get all fields annotated with a particular annotation. This method * traverses the class hierarchy when checking for the annotation. * * @param object * The object to look for annotations. Note that if're you're * passing an object only instance fields are checked, passing a * class will only check static fields. * @param annotation * The annotation type to look for. * @param additionalAnnotations * Optionally more annotations to look for. If any of the * annotations are associated with a particular field it will be * added to the resulting {@code Set}. * @return A set of all fields containing the particular annotation. */ public static Set getFieldsAnnotatedWith(Object object, Class annotation, Class... additionalAnnotations) { return WhiteboxImpl.getFieldsAnnotatedWith(object, annotation, additionalAnnotations); } /** * Get all fields annotated with a particular annotation. This method * traverses the class hierarchy when checking for the annotation. * * @param object * The object to look for annotations. Note that if're you're * passing an object only instance fields are checked, passing a * class will only check static fields. * @param annotationTypes * The annotation types to look for * @return A set of all fields containing the particular annotation(s). * @since 1.3 */ public static Set getFieldsAnnotatedWith(Object object, Class[] annotationTypes) { return WhiteboxImpl.getFieldsAnnotatedWith(object, annotationTypes); } /** * Get all instance fields for a particular object. It returns all fields * regardless of the field modifier and regardless of where in the class * hierarchy a field is located. * * @param object * The object whose instance fields to get. * @return All instance fields in the hierarchy. All fields are set to * accessible */ public static Set getAllInstanceFields(Object object) { return WhiteboxImpl.getAllInstanceFields(object); } /** * Get all static fields for a particular type. * * @param type * The class whose static fields to get. * @return All static fields in {@code type}. All fields are set to * accessible. */ public static Set getAllStaticFields(Class type) { return WhiteboxImpl.getAllStaticFields(type); } /** * Get all fields assignable from a particular type. This method traverses * the class hierarchy when checking for the type. * * @param object * The object to look for type. Note that if're you're passing an * object only instance fields are checked, passing a class will * only check static fields. * @param type * The type to look for. * @return A set of all fields of the particular type. */ public static Set getFieldsOfType(Object object, Class type) { return WhiteboxImpl.getFieldsOfType(object, type); } /** * Get an inner class type * * @param declaringClass * The class in which the inner class is declared. * @param name * The unqualified name (simple name) of the inner class. * @return The type. */ public static Class getInnerClassType(Class declaringClass, String name) throws ClassNotFoundException { return WhiteboxImpl.getInnerClassType(declaringClass, name); } /** * Get the type of a local inner class. * * @param declaringClass * The class in which the local inner class is declared. * @param occurrence * The occurrence of the local class. For example if you have two * local classes in the {@code declaringClass} you must pass * in {@code 1} if you want to get the type for the first * one or {@code 2} if you want the second one. * @param name * The unqualified name (simple name) of the local class. * @return The type. */ public static Class getLocalClassType(Class declaringClass, int occurrence, String name) throws ClassNotFoundException { return WhiteboxImpl.getLocalClassType(declaringClass, occurrence, name); } /** * Get the type of an anonymous inner class. * * @param declaringClass * The class in which the anonymous inner class is declared. * @param occurrence * The occurrence of the anonymous inner class. For example if * you have two anonymous inner classes classes in the * {@code declaringClass} you must pass in {@code 1} if * you want to get the type for the first one or {@code 2} * if you want the second one. * @return The type. */ public static Class getAnonymousInnerClassType(Class declaringClass, int occurrence) throws ClassNotFoundException { return WhiteboxImpl.getAnonymousInnerClassType(declaringClass, occurrence); } /** * Set the values of multiple instance fields defined in a context using * reflection. The values in the context will be assigned to values on the * {@code instance}. This method will traverse the class hierarchy when * searching for the fields. Example usage: *

* Given: * *

	 * public class MyContext {
	 * 	private String myString = "myString";
	 * 	protected int myInt = 9;
	 * }
	 * 
	 * public class MyInstance {
	 * 	private String myInstanceString;
	 * 	private int myInstanceInt;
	 * 
	 * }
	 * 
* * then * *
	 * Whitebox.setInternalStateFromContext(new MyInstance(), new MyContext());
	 * 
* * will set the instance variables of {@code myInstance} to the values * specified in {@code MyContext}. *

* By default the {@link FieldMatchingStrategy#MATCHING} strategy is used * which means that the fields defined in the context but not found in the * classOrInstance are silently ignored. * * * * @param instance * the object whose fields to modify. * @param context * The context where the fields are defined. * @param additionalContexts * Optionally more additional contexts. */ public static void setInternalStateFromContext(Object instance, Object context, Object... additionalContexts) { WhiteboxImpl.setInternalStateFromContext(instance, context, additionalContexts); } /** * Set the values of multiple static fields defined in a context using * reflection. The values in the context will be assigned to values on the * {@code classOrInstance}. This method will traverse the class * hierarchy when searching for the fields. Example usage: *

* Given: * *

	 * public class MyContext {
	 * 	private static String myString = "myString";
	 * 	protected static int myInt = 9;
	 * }
	 * 
	 * public class MyInstance {
	 * 	private static String myInstanceString;
	 * 	private static int myInstanceInt;
	 * 
	 * }
	 * 
* * then * *
	 * Whitebox.setInternalStateFromContext(MyInstance.class, MyContext.class);
	 * 
* * will set the static variables of {@code MyInstance} to the values * specified in {@code MyContext}. *

* By default the {@link FieldMatchingStrategy#MATCHING} strategy is used * which means that the fields defined in the context but not found in the * classOrInstance are silently ignored. * * @param classOrInstance * The object or class whose fields to set. * @param context * The context where the fields are defined. * @param additionalContexts * Optionally more additional contexts. */ public static void setInternalStateFromContext(Object classOrInstance, Class context, Class... additionalContexts) { WhiteboxImpl.setInternalStateFromContext(classOrInstance, context, additionalContexts); } /** * Set the values of multiple instance fields defined in a context using * reflection and using an explicit {@link FieldMatchingStrategy}. The * values in the context will be assigned to values on the * {@code instance}. This method will traverse the class hierarchy when * searching for the fields. Example usage: *

* Given: * *

	 * public class MyContext {
	 * 	private String myString = "myString";
	 * 	protected int myInt = 9;
	 * }
	 * 
	 * public class MyInstance {
	 * 	private String myInstanceString;
	 * 	private int myInstanceInt;
	 * 
	 * }
	 * 
* * then * *
	 * Whitebox.setInternalStateFromContext(new MyInstance(), new MyContext());
	 * 
* * will set the instance variables of {@code myInstance} to the values * specified in {@code MyContext}. * * @param instance * the object whose fields to modify. * @param context * The context where the fields are defined. * @param strategy * Which field matching strategy to use. */ public static void setInternalStateFromContext(Object instance, Object context, FieldMatchingStrategy strategy) { WhiteboxImpl.setInternalStateFromContext(instance, context, strategy); } /** * Set the values of multiple static fields defined in a context using * reflection and using an explicit {@link FieldMatchingStrategy}. The * values in the context will be assigned to values on the * {@code classOrInstance}. This method will traverse the class * hierarchy when searching for the fields. Example usage: *

* Given: * *

	 * public class MyContext {
	 * 	private static String myString = "myString";
	 * 	protected static int myInt = 9;
	 * }
	 * 
	 * public class MyInstance {
	 * 	private static String myInstanceString;
	 * 	private static int myInstanceInt;
	 * 
	 * }
	 * 
* * then * *
	 * Whitebox.setInternalStateFromContext(MyInstance.class, MyContext.class);
	 * 
* * will set the static variables of {@code MyInstance} to the values * specified in {@code MyContext}. *

* * @param instance * The object or class whose fields to set. * @param context * The context where the fields are defined. * @param strategy * Which field matching strategy to use. */ public static void setInternalStateFromContext(Object instance, Class context, FieldMatchingStrategy strategy) { WhiteboxImpl.setInternalStateFromContext(instance, context, strategy); } } ================================================ FILE: powermock-reflect/src/main/java/org/powermock/reflect/exceptions/ConstructorNotFoundException.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.reflect.exceptions; /** * A run-time exception that may be thrown to indicate that a constructor was * not found. */ public class ConstructorNotFoundException extends RuntimeException { private static final long serialVersionUID = -7329106318739007850L; /** * Constructs a new exception with the specified detail message. The cause * is not initialized, and may subsequently be initialized by a call to * {@link #initCause}. * * @param message * the detail message. The detail message is saved for later * retrieval by the {@link #getMessage()} method. */ public ConstructorNotFoundException(String message) { super(message); } /** * Constructs a new runtime exception with the specified detail message and * cause. *

* Note that the detail message associated with {@code cause} is * not automatically incorporated in this exception's detail message. * * @param message * the detail message (which is saved for later retrieval by the * {@link #getMessage()} method). * @param cause * the cause (which is saved for later retrieval by the * {@link #getCause()} method). (A null value is * permitted, and indicates that the cause is nonexistent or * unknown.) */ public ConstructorNotFoundException(String message, Throwable cause) { super(message, cause); } } ================================================ FILE: powermock-reflect/src/main/java/org/powermock/reflect/exceptions/FieldNotFoundException.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.reflect.exceptions; /** * A run-time exception that may be thrown to indicate that a field was not * found. */ public class FieldNotFoundException extends RuntimeException { private static final long serialVersionUID = 5420195402982130931L; /** * Constructs a new exception with the specified detail message. The cause * is not initialized, and may subsequently be initialized by a call to * {@link #initCause}. * * @param message * the detail message. The detail message is saved for later * retrieval by the {@link #getMessage()} method. */ public FieldNotFoundException(String message) { super(message); } } ================================================ FILE: powermock-reflect/src/main/java/org/powermock/reflect/exceptions/MethodInvocationException.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.reflect.exceptions; /** * A run-time exception that may be thrown to indicate that a method invocation * failed. */ public class MethodInvocationException extends RuntimeException { private static final long serialVersionUID = 4051932931902248488L; /** * Constructs a new exception with the specified detail message. The cause * is not initialized, and may subsequently be initialized by a call to * {@link #initCause}. * * @param message * the detail message. The detail message is saved for later * retrieval by the {@link #getMessage()} method. */ public MethodInvocationException(String message) { super(message); } /** * Constructs a new runtime exception with the specified detail message and * cause. *

* Note that the detail message associated with {@code cause} is * not automatically incorporated in this exception's detail message. * * @param message * the detail message (which is saved for later retrieval by the * {@link #getMessage()} method). * @param cause * the cause (which is saved for later retrieval by the * {@link #getCause()} method). (A null value is * permitted, and indicates that the cause is nonexistent or * unknown.) */ public MethodInvocationException(String message, Throwable cause) { super(message, cause); } /** * Constructs a new exception with the specified cause and a detail message * of (cause==null ? null : cause.toString()) (which typically * contains the class and detail message of cause). This * constructor is useful for runtime exceptions that are little more than * wrappers for other throwables. * * @param cause * the cause (which is saved for later retrieval by the * {@link #getCause()} method). (A null value is * permitted, and indicates that the cause is nonexistent or * unknown.) * @since 1.4 */ public MethodInvocationException(Throwable cause) { super(cause); } } ================================================ FILE: powermock-reflect/src/main/java/org/powermock/reflect/exceptions/MethodNotFoundException.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.reflect.exceptions; /** * A run-time exception that may be thrown to indicate that a method was not * found. */ public class MethodNotFoundException extends RuntimeException { private static final long serialVersionUID = -1617211962548265914L; /** * Constructs a new exception with the specified detail message. The cause * is not initialized, and may subsequently be initialized by a call to * {@link #initCause}. * * @param message * the detail message. The detail message is saved for later * retrieval by the {@link #getMessage()} method. */ public MethodNotFoundException(String message) { super(message); } } ================================================ FILE: powermock-reflect/src/main/java/org/powermock/reflect/exceptions/TooManyConstructorsFoundException.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.reflect.exceptions; /** * A run-time exception that may be thrown to indicate that too many * constructors were found. */ public class TooManyConstructorsFoundException extends RuntimeException { private static final long serialVersionUID = 1365925879589152290L; /** * Constructs a new exception with the specified detail message. The cause * is not initialized, and may subsequently be initialized by a call to * {@link #initCause}. * * @param message * the detail message. The detail message is saved for later * retrieval by the {@link #getMessage()} method. */ public TooManyConstructorsFoundException(String message) { super(message); } } ================================================ FILE: powermock-reflect/src/main/java/org/powermock/reflect/exceptions/TooManyFieldsFoundException.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.reflect.exceptions; /** * A run-time exception that may be thrown to indicate that too many fields were * found. */ public class TooManyFieldsFoundException extends RuntimeException { private static final long serialVersionUID = 1564231184610341053L; /** * Constructs a new exception with the specified detail message. The cause * is not initialized, and may subsequently be initialized by a call to * {@link #initCause}. * * @param message * the detail message. The detail message is saved for later * retrieval by the {@link #getMessage()} method. */ public TooManyFieldsFoundException(String message) { super(message); } } ================================================ FILE: powermock-reflect/src/main/java/org/powermock/reflect/exceptions/TooManyMethodsFoundException.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.reflect.exceptions; /** * A run-time exception that may be thrown to indicate that too many methods * were found. */ public class TooManyMethodsFoundException extends RuntimeException { private static final long serialVersionUID = -3267907243933066607L; /** * Constructs a new exception with the specified detail message. The cause * is not initialized, and may subsequently be initialized by a call to * {@link #initCause}. * * @param message * the detail message. The detail message is saved for later * retrieval by the {@link #getMessage()} method. */ public TooManyMethodsFoundException(String message) { super(message); } } ================================================ FILE: powermock-reflect/src/main/java/org/powermock/reflect/internal/CandidateConstructorSearcher.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.reflect.internal; import org.powermock.reflect.internal.comparator.ComparatorFactory; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * This class search the best candidate in the given class to invoke constructor with given parameters. */ class CandidateConstructorSearcher { private final Class classThatContainsTheConstructorToTest; private final Class[] argumentTypes; public CandidateConstructorSearcher(Class classThatContainsTheConstructorToTest, Class[] argumentTypes) { this.classThatContainsTheConstructorToTest = classThatContainsTheConstructorToTest; this.argumentTypes = argumentTypes; } public Constructor findConstructor() { final Constructor[] constructors = getConstructors(); if (constructors.length == 0) { return null; } if (constructors.length == 1) { return constructors[0]; } else { return findBestCandidate(constructors); } } private Constructor findBestCandidate(Constructor[] constructors) { //We've found overloaded constructor, we need to find the best one to invoke. Arrays.sort(constructors, ComparatorFactory.createConstructorComparator()); return constructors[0]; } @SuppressWarnings("unchecked") private Constructor[] getConstructors() { try { Constructor[] declaredConstructors = classThatContainsTheConstructorToTest.getDeclaredConstructors(); List> constructors = new ArrayList>(); for (Constructor constructor : declaredConstructors) { if (argumentsApplied(constructor)) { constructors.add(constructor); } } return constructors.toArray(new Constructor[constructors.size()]); } catch (Exception e) { return new Constructor[0]; } } private boolean argumentsApplied(Constructor constructor) { Class[] constructorArgumentTypes = constructor.getParameterTypes(); if (constructorArgumentTypes.length != argumentTypes.length) { return false; } for (int index = 0; index < argumentTypes.length; index++) { if (!constructorArgumentTypes[index].isAssignableFrom(argumentTypes[index])) { return false; } } return true; } } ================================================ FILE: powermock-reflect/src/main/java/org/powermock/reflect/internal/Constructor.java ================================================ package org.powermock.reflect.internal; class Constructor { private final Class[] parameterTypes; private java.lang.reflect.Constructor constructor; private boolean isVarArgs; Constructor(java.lang.reflect.Constructor constructor) { this.constructor = constructor; this.parameterTypes = constructor.getParameterTypes(); this.isVarArgs = constructor.isVarArgs(); } boolean canBeInvokeWith(Object[] arguments) { return new ParametersMatcher(isVarArgs, parameterTypes, arguments).match(); } public java.lang.reflect.Constructor getJavaConstructor() { return constructor; } public boolean isVarArg() { return isVarArgs; } } ================================================ FILE: powermock-reflect/src/main/java/org/powermock/reflect/internal/ConstructorFinder.java ================================================ package org.powermock.reflect.internal; import org.powermock.reflect.exceptions.ConstructorNotFoundException; import org.powermock.reflect.exceptions.TooManyConstructorsFoundException; import java.lang.reflect.Modifier; import java.util.HashSet; import java.util.Set; class ConstructorFinder { private Class type; private Object[] arguments; private Class unmockedType; private Constructor potentialConstructor; ConstructorFinder(Class type, Object... arguments) { if (type == null) { throw new IllegalArgumentException("Class type cannot be null."); } this.type = type; this.arguments = arguments; this.unmockedType = WhiteboxImpl.getOriginalUnmockedType(type); if (isNestedClass() && arguments != null) { addArgumentForNestedClass(); } } public java.lang.reflect.Constructor findConstructor() { lookupPotentialConstructor(); throwExceptionIfConstructorWasNotFound(); return potentialConstructor.getJavaConstructor(); } private void lookupPotentialConstructor() {Set constructors = getDeclaredConstructorsWithoutPowerMockConstructor(); for (Constructor constructor : constructors) { if (constructor.canBeInvokeWith(arguments)) { setPotentialConstructor(constructor); } // if a constructor is found and it has varargs parameters then the constructor will be used even if // other constructor is matcher the given arguments. It is done, because when Argument Matchers are used // arguments passed to the method are null value and it's imposable to determinate whether parameters // match to arguments or not. if (isVarArgConstructorFound()){ return; } } } private boolean isVarArgConstructorFound() {return potentialConstructor!=null && potentialConstructor.isVarArg();} private void setPotentialConstructor(Constructor constructor) { if (potentialConstructor == null) { potentialConstructor = constructor; }else{ /* * We've already found a constructor match before, this * means that PowerMock cannot determine which method to * expect since there are two methods with the same name * and the same number of arguments but one is using * wrapper types. */ throwExceptionWhenMultipleConstructorMatchesFound(new java.lang.reflect.Constructor[]{potentialConstructor.getJavaConstructor(), constructor.getJavaConstructor()}); } } public void throwExceptionWhenMultipleConstructorMatchesFound(java.lang.reflect.Constructor[] constructors) { if (constructors == null || constructors.length < 2) { throw new IllegalArgumentException("Internal error: throwExceptionWhenMultipleConstructorMatchesFound needs at least two constructors."); } StringBuilder sb = new StringBuilder(); sb.append("Several matching constructors found, please specify the argument parameter types so that PowerMock can determine which method you're referring to.\n"); sb.append("Matching constructors in class ").append(constructors[0].getDeclaringClass().getName()) .append(" were:\n"); for (java.lang.reflect.Constructor constructor : constructors) { sb.append(constructor.getName()).append("( "); final Class[] parameterTypes = constructor.getParameterTypes(); for (Class paramType : parameterTypes) { sb.append(paramType.getName()).append(".class "); } sb.append(")\n"); } throw new TooManyConstructorsFoundException(sb.toString()); } private void addArgumentForNestedClass() { Object[] argumentsForLocalClass = new Object[arguments.length + 1]; argumentsForLocalClass[0] = unmockedType.getEnclosingClass(); System.arraycopy(arguments, 0, argumentsForLocalClass, 1, arguments.length); arguments = argumentsForLocalClass; } private boolean isNestedClass() { return (unmockedType.isLocalClass() || unmockedType.isAnonymousClass() || unmockedType.isMemberClass()) && !Modifier.isStatic(unmockedType.getModifiers()); } private Set getDeclaredConstructorsWithoutPowerMockConstructor() { Set constructors = new HashSet(); for (java.lang.reflect.Constructor constructor : unmockedType.getDeclaredConstructors()) { if (!isPowerMockConstructor(constructor.getParameterTypes())) { constructors.add(new Constructor(constructor)); } } return constructors; } private boolean isPowerMockConstructor(Class[] parameterTypes) { return parameterTypes.length >= 1 && parameterTypes[parameterTypes.length - 1].getName().equals( "org.powermock.core.IndicateReloadClass"); } private void throwExceptionIfConstructorWasNotFound() { if (potentialConstructor == null) { String message = "No constructor found in class '" + WhiteboxImpl.getOriginalUnmockedType(type).getName() + "' " + "with " + "parameter types: [ " + WhiteboxImpl.getArgumentTypesAsString(arguments) + " ]."; throw new ConstructorNotFoundException(message); } } } ================================================ FILE: powermock-reflect/src/main/java/org/powermock/reflect/internal/ParameterTypesMatcher.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.reflect.internal; /** * */ class ParameterTypesMatcher { private boolean isVarArgs; private Class[] expectedParameterTypes; private Class[] actualParameterTypes; public ParameterTypesMatcher(boolean isVarArgs, Class[] expectedParameterTypes, Class... actualParameterTypes) { this.isVarArgs = isVarArgs; this.expectedParameterTypes = expectedParameterTypes; this.actualParameterTypes = actualParameterTypes; } private boolean isRemainParamsVarArgs(int index, Class actualParameterType) { return isVarArgs && index == expectedParameterTypes.length - 1 && actualParameterType.getComponentType().isAssignableFrom(expectedParameterTypes[index]); } private boolean isParameterTypesNotMatch(Class actualParameterType, Class expectedParameterType) { if (actualParameterType == null){ return false; } if (expectedParameterType == null){ return false; } return !actualParameterType.isAssignableFrom(expectedParameterType); } public boolean match() { assertParametersTypesNotNull(); if (isParametersLengthMatch()) { return false; } else { return isParametersMatch(); } } private boolean isParametersLengthMatch() {return expectedParameterTypes.length != actualParameterTypes.length;} private void assertParametersTypesNotNull() { if (expectedParameterTypes == null || actualParameterTypes == null) { throw new IllegalArgumentException("parameter types cannot be null"); } } private Boolean isParametersMatch() { for (int index = 0; index < expectedParameterTypes.length; index++) { final Class actualParameterType = actualParameterTypes[index]; if (isRemainParamsVarArgs(index, actualParameterType)) { return true; } else { final Class expectedParameterType = expectedParameterTypes[index]; if (isParameterTypesNotMatch(actualParameterType, expectedParameterType)) { return false; } } } return true; } } ================================================ FILE: powermock-reflect/src/main/java/org/powermock/reflect/internal/ParametersMatcher.java ================================================ package org.powermock.reflect.internal; /** * */ class ParametersMatcher { private final Class[] parameterTypes; private final Object[] arguments; private boolean isVarArgs; public ParametersMatcher(boolean isVarArgs, Class[] parameterTypes, Object[] arguments) { this.isVarArgs = isVarArgs; this.parameterTypes = parameterTypes; this.arguments = arguments; } public boolean match() { if ((arguments != null && (parameterTypes.length == arguments.length))) { if (parameterTypes.length == 0) { return true; } return checkArgumentTypesMatchParameterTypes(isVarArgs, parameterTypes, arguments); } else if (doesParameterTypesMatchForVarArgsInvocation(arguments)) { return true; } else { return false; } } boolean checkArgumentTypesMatchParameterTypes(boolean isVarArgs, Class[] parameterTypes, Object[] arguments) { if (parameterTypes == null) { throw new IllegalArgumentException("parameter types cannot be null"); } else if (!isVarArgs && arguments.length != parameterTypes.length) { return false; } for (int i = 0; i < arguments.length; i++) { Object argument = arguments[i]; if (argument == null) { final int index; if (i >= parameterTypes.length) { index = parameterTypes.length - 1; } else { index = i; } final Class type = parameterTypes[index]; if (type.isPrimitive()) { // Primitives cannot be null return false; } else { continue; } } else if (i >= parameterTypes.length) { if (WhiteboxImpl.isAssignableFrom(parameterTypes[parameterTypes.length - 1], WhiteboxImpl.getType( argument))) { continue; } else { return false; } } else { boolean assignableFrom = WhiteboxImpl.isAssignableFrom(parameterTypes[i], WhiteboxImpl.getType( argument)); final boolean isClass = parameterTypes[i].equals(Class.class) && WhiteboxImpl.isClass(argument); if (!assignableFrom && !isClass) { return false; } } } return true; } boolean doesParameterTypesMatchForVarArgsInvocation(Object[] arguments) { if (isVarArgs && arguments != null && arguments.length >= 1 && parameterTypes != null && parameterTypes.length >= 1) { final Class componentType = parameterTypes[parameterTypes.length - 1].getComponentType(); final Object lastArgument = arguments[arguments.length - 1]; if (lastArgument != null) { final Class lastArgumentTypeAsPrimitive = WhiteboxImpl.getTypeAsPrimitiveIfWrapped(lastArgument); final Class varArgsParameterTypeAsPrimitive = WhiteboxImpl.getTypeAsPrimitiveIfWrapped(componentType); isVarArgs = varArgsParameterTypeAsPrimitive.isAssignableFrom(lastArgumentTypeAsPrimitive); } } return isVarArgs && checkArgumentTypesMatchParameterTypes(isVarArgs, parameterTypes, arguments); } } ================================================ FILE: powermock-reflect/src/main/java/org/powermock/reflect/internal/TypeUtils.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.reflect.internal; /** * Utilities for types. */ public class TypeUtils { /** * Get the default value for a type. * * @param type * The type whose default value to get. * @return The default return type of {@code type}. */ public static Object getDefaultValue(Class type) { return getDefaultValue(type.getName()); } /** * Get the default value of a type with based on its fully-qualified name. * * @param fullyQualifiedTypeName * The name of the type whose default value to get. * @return The default value of {@code fullyQualifiedTypeName}. */ public static Object getDefaultValue(String fullyQualifiedTypeName) { if (fullyQualifiedTypeName == null) { // Void return ""; } else if (fullyQualifiedTypeName.equals(byte.class.getName())) { return (byte) 0; } else if (fullyQualifiedTypeName.equals(int.class.getName())) { return 0; } else if (fullyQualifiedTypeName.equals(short.class.getName())) { return (short) 0; } else if (fullyQualifiedTypeName.equals(long.class.getName())) { return 0L; } else if (fullyQualifiedTypeName.equals(float.class.getName())) { return 0.0F; } else if (fullyQualifiedTypeName.equals(double.class.getName())) { return 0.0D; } else if (fullyQualifiedTypeName.equals(boolean.class.getName())) { return false; } else if (fullyQualifiedTypeName.equals(char.class.getName())) { return ' '; } else { return null; } } /** * Get the default value of a type with based on its fully-qualified name. * * @param fullyQualifiedTypeName * The name of the type whose default value to get. * @return The default value of {@code fullyQualifiedTypeName}. */ public static String getDefaultValueAsString(String fullyQualifiedTypeName) { if (fullyQualifiedTypeName == null) { // Void return ""; } else if (fullyQualifiedTypeName.equals(byte.class.getName())) { return "(byte) 0"; } else if (fullyQualifiedTypeName.equals(int.class.getName())) { return "0"; } else if (fullyQualifiedTypeName.equals(short.class.getName())) { return "(short) 0"; } else if (fullyQualifiedTypeName.equals(long.class.getName())) { return "0L"; } else if (fullyQualifiedTypeName.equals(float.class.getName())) { return "0.0F"; } else if (fullyQualifiedTypeName.equals(double.class.getName())) { return "0.0D"; } else if (fullyQualifiedTypeName.equals(boolean.class.getName())) { return "false"; } else if (fullyQualifiedTypeName.equals(char.class.getName())) { return "' '"; } else { return "null"; } } } ================================================ FILE: powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.reflect.internal; import org.objenesis.Objenesis; import org.objenesis.ObjenesisStd; import org.objenesis.instantiator.ObjectInstantiator; import org.powermock.reflect.exceptions.ConstructorNotFoundException; import org.powermock.reflect.exceptions.FieldNotFoundException; import org.powermock.reflect.exceptions.MethodInvocationException; import org.powermock.reflect.exceptions.MethodNotFoundException; import org.powermock.reflect.exceptions.TooManyConstructorsFoundException; import org.powermock.reflect.exceptions.TooManyFieldsFoundException; import org.powermock.reflect.exceptions.TooManyMethodsFoundException; import org.powermock.reflect.internal.comparator.ComparatorFactory; import org.powermock.reflect.internal.matcherstrategies.AllFieldsMatcherStrategy; import org.powermock.reflect.internal.matcherstrategies.AssignableFromFieldTypeMatcherStrategy; import org.powermock.reflect.internal.matcherstrategies.AssignableToFieldTypeMatcherStrategy; import org.powermock.reflect.internal.matcherstrategies.FieldAnnotationMatcherStrategy; import org.powermock.reflect.internal.matcherstrategies.FieldMatcherStrategy; import org.powermock.reflect.internal.matcherstrategies.FieldNameMatcherStrategy; import org.powermock.reflect.internal.primitivesupport.BoxedWrapper; import org.powermock.reflect.internal.primitivesupport.PrimitiveWrapper; import org.powermock.reflect.internal.proxy.ProxyFrameworks; import org.powermock.reflect.internal.proxy.UnproxiedType; import org.powermock.reflect.matching.FieldMatchingStrategy; import java.lang.annotation.Annotation; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Proxy; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import sun.misc.Unsafe; /** * Various utilities for accessing internals of a class. Basically a simplified * reflection utility intended for tests. */ public class WhiteboxImpl { /** * The proxy framework. */ private static ProxyFrameworks proxyFrameworks = new ProxyFrameworks(); /** * "Strong" map prevent class and method objects from being GCed and unloaded. * TODO replace with ClassValue when Powermock drops Java 6 support. */ private static ConcurrentMap allClassMethodsCache = new ConcurrentHashMap(); /** * Convenience method to get a method from a class type without having to * catch the checked exceptions otherwise required. These exceptions are * wrapped as runtime exceptions. * * The method will first try to look for a declared method in the same * class. If the method is not declared in this class it will look for the * method in the super class. This will continue throughout the whole class * hierarchy. If the method is not found an {@link MethodNotFoundException} * is thrown. Since the method name is not specified an * * @param type The type of the class where the method is located. * @param parameterTypes All parameter types of the method (may be {@code null}). * @return A . {@link TooManyMethodsFoundException} is thrown if two or more * methods matches the same parameter types in the same class. */ public static Method getMethod(Class type, Class... parameterTypes) { Class thisType = type; if (parameterTypes == null) { parameterTypes = new Class[0]; } List foundMethods = new LinkedList(); while (thisType != null) { Method[] methodsToTraverse = null; if (thisType.isInterface()) { // Interfaces only contain public (and abstract) methods, no // need to traverse the hierarchy. methodsToTraverse = getAllPublicMethods(thisType); } else { methodsToTraverse = thisType.getDeclaredMethods(); } for (Method method : methodsToTraverse) { if (checkIfParameterTypesAreSame(method.isVarArgs(), parameterTypes, method.getParameterTypes())) { foundMethods.add(method); if (foundMethods.size() == 1) { method.setAccessible(true); } } } if (foundMethods.size() == 1) { return foundMethods.get(0); } else if (foundMethods.size() > 1) { break; } thisType = thisType.getSuperclass(); } if (foundMethods.isEmpty()) { throw new MethodNotFoundException("No method was found with parameter types: [ " + getArgumentTypesAsString((Object[]) parameterTypes) + " ] in class " + getOriginalUnmockedType(type).getName() + "."); } else { throwExceptionWhenMultipleMethodMatchesFound("method name", foundMethods.toArray(new Method[foundMethods.size()])); } // Will never happen return null; } /** * Convenience method to get a method from a class type without having to * catch the checked exceptions otherwise required. These exceptions are * wrapped as runtime exceptions. * * The method will first try to look for a declared method in the same * class. If the method is not declared in this class it will look for the * method in the super class. This will continue throughout the whole class * hierarchy. If the method is not found an {@link IllegalArgumentException} * is thrown. * * @param type The type of the class where the method is located. * @param methodName The method names. * @param parameterTypes All parameter types of the method (may be {@code null}). * @return A . */ public static Method getMethod(Class type, String methodName, Class... parameterTypes) { Class thisType = type; if (parameterTypes == null) { parameterTypes = new Class[0]; } while (thisType != null) { Method[] methodsToTraverse = null; if (thisType.isInterface()) { // Interfaces only contain public (and abstract) methods, no // need to traverse the hierarchy. methodsToTraverse = getAllPublicMethods(thisType); } else { methodsToTraverse = thisType.getDeclaredMethods(); } for (Method method : methodsToTraverse) { if (methodName.equals(method.getName()) && checkIfParameterTypesAreSame(method.isVarArgs(), parameterTypes, method.getParameterTypes())) { method.setAccessible(true); return method; } } thisType = thisType.getSuperclass(); } throwExceptionIfMethodWasNotFound(type, methodName, null, new Object[]{parameterTypes}); return null; } /** * Convenience method to get a field from a class type. * * The method will first try to look for a declared field in the same class. * If the method is not declared in this class it will look for the field in * the super class. This will continue throughout the whole class hierarchy. * If the field is not found an {@link IllegalArgumentException} is thrown. * * @param type The type of the class where the method is located. * @param fieldName The method names. * @return A . */ @SuppressWarnings({"unchecked", "rawtypes"}) public static Field getField(Class type, String fieldName) { LinkedList> examine = new LinkedList>(); examine.add(type); Set> done = new HashSet>(); while (!examine.isEmpty()) { Class thisType = examine.removeFirst(); done.add(thisType); final Field[] declaredField = thisType.getDeclaredFields(); for (Field field : declaredField) { if (fieldName.equals(field.getName())) { field.setAccessible(true); return field; } } Set> potential = new HashSet>(); final Class clazz = thisType.getSuperclass(); if (clazz != null) { potential.add(thisType.getSuperclass()); } potential.addAll((Collection) Arrays.asList(thisType.getInterfaces())); potential.removeAll(done); examine.addAll(potential); } throwExceptionIfFieldWasNotFound(type, fieldName, null); return null; } /** * Create a new instance of a class without invoking its constructor. * * No byte-code manipulation is needed to perform this operation and thus * it's not necessary use the {@code PowerMockRunner} or * {@code PrepareForTest} annotation to use this functionality. * * @param The type of the instance to create. * @param classToInstantiate The type of the instance to create. * @return A new instance of type T, created without invoking the * constructor. */ @SuppressWarnings("unchecked") public static T newInstance(Class classToInstantiate) { int modifiers = classToInstantiate.getModifiers(); final Object object; if (Modifier.isInterface(modifiers)) { object = Proxy.newProxyInstance(WhiteboxImpl.class.getClassLoader(), new Class[]{classToInstantiate}, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return TypeUtils.getDefaultValue(method.getReturnType()); } }); } else if (classToInstantiate.isArray()) { object = Array.newInstance(classToInstantiate.getComponentType(), 0); } else if (Modifier.isAbstract(modifiers)) { throw new IllegalArgumentException( "Cannot instantiate an abstract class. Please use the ConcreteClassGenerator in PowerMock support to generate a concrete class first."); } else { Objenesis objenesis = new ObjenesisStd(); ObjectInstantiator thingyInstantiator = objenesis.getInstantiatorOf(classToInstantiate); object = thingyInstantiator.newInstance(); } return (T) object; } /** * Convenience method to get a (declared) constructor from a class type * without having to catch the checked exceptions otherwise required. These * exceptions are wrapped as runtime exceptions. The constructor is also set * to accessible. * * @param type The type of the class where the constructor is located. * @param parameterTypes All parameter types of the constructor (may be * {@code null}). * @return A . */ public static Constructor getConstructor(Class type, Class... parameterTypes) { Class unmockedType = WhiteboxImpl.getOriginalUnmockedType(type); try { final Constructor constructor = unmockedType.getDeclaredConstructor(parameterTypes); constructor.setAccessible(true); return constructor; } catch (RuntimeException e) { throw e; } catch (Error e) { throw e; } catch (Throwable e) { throw new ConstructorNotFoundException(String.format( "Failed to lookup constructor with parameter types [ %s ] in class %s.", getArgumentTypesAsString((Object[]) parameterTypes), unmockedType.getName()), e); } } /** * Set the value of a field using reflection. This method will traverse the * super class hierarchy until a field with name fieldName is * found. * * @param object the object whose field to modify * @param fieldName the name of the field * @param value the new value of the field */ public static void setInternalState(Object object, String fieldName, Object value) { Field foundField = findFieldInHierarchy(object, fieldName); setField(object, value, foundField); } /** * Set the value of a field using reflection. This method will traverse the * super class hierarchy until a field with name fieldName is * found. * * @param object the object to modify * @param fieldName the name of the field * @param value the new value of the field */ public static void setInternalState(Object object, String fieldName, Object[] value) { setInternalState(object, fieldName, (Object) value); } /** * Set the value of a field using reflection. This method will traverse the * super class hierarchy until the first field of type fieldType is * found. The value will then be assigned to this field. * * @param object the object to modify * @param fieldType the type of the field * @param value the new value of the field */ public static void setInternalState(Object object, Class fieldType, Object value) { setField(object, value, findFieldInHierarchy(object, new AssignableFromFieldTypeMatcherStrategy(fieldType))); } /** * Set the value of a field using reflection. This method will traverse the * super class hierarchy until the first field assignable to the * value type is found. The value (or * additionaValues if present) will then be assigned to this field. * * @param object the object to modify * @param value the new value of the field * @param additionalValues Additional values to set on the object */ public static void setInternalState(Object object, Object value, Object... additionalValues) { setField(object, value, findFieldInHierarchy(object, new AssignableFromFieldTypeMatcherStrategy(getType(value)))); if (additionalValues != null && additionalValues.length > 0) { for (Object additionalValue : additionalValues) { setField( object, additionalValue, findFieldInHierarchy(object, new AssignableFromFieldTypeMatcherStrategy( getType(additionalValue)))); } } } /** * Set the value of a field using reflection at at specific place in the * class hierarchy (where). This first field assignable to * object will then be set to value. * * @param object the object to modify * @param value the new value of the field * @param where the class in the hierarchy where the field is defined */ public static void setInternalState(Object object, Object value, Class where) { setField(object, value, findField(object, new AssignableFromFieldTypeMatcherStrategy(getType(value)), where)); } /** * Set the value of a field using reflection at a specific location ( * where) in the class hierarchy. The value will then be * assigned to this field. * * @param object the object to modify * @param fieldType the type of the field the should be set. * @param value the new value of the field * @param where which class in the hierarchy defining the field */ public static void setInternalState(Object object, Class fieldType, Object value, Class where) { if (fieldType == null || where == null) { throw new IllegalArgumentException("fieldType and where cannot be null"); } setField(object, value, findFieldOrThrowException(fieldType, where)); } /** * Set the value of a field using reflection. Use this method when you need * to specify in which class the field is declared. This is useful if you * have two fields in a class hierarchy that has the same name but you like * to modify the latter. * * @param object the object to modify * @param fieldName the name of the field * @param value the new value of the field * @param where which class the field is defined */ public static void setInternalState(Object object, String fieldName, Object value, Class where) { if (object == null || fieldName == null || fieldName.equals("") || fieldName.startsWith(" ")) { throw new IllegalArgumentException("object, field name, and \"where\" must not be empty or null."); } final Field field = getField(fieldName, where); try { field.set(object, value); } catch (Exception e) { throw new RuntimeException("Internal Error: Failed to set field in method setInternalState.", e); } } /** * Get the value of a field using reflection. This method will iterate * through the entire class hierarchy and return the value of the first * field named fieldName. If you want to get a specific field value * at specific place in the class hierarchy please refer to * * @param the generic type * @param object the object to modify * @param fieldName the name of the field * @return the internal state * {@link #getInternalState(Object, String, Class)}. */ @SuppressWarnings("unchecked") public static T getInternalState(Object object, String fieldName) { Field foundField = findFieldInHierarchy(object, fieldName); try { return (T) foundField.get(object); } catch (IllegalAccessException e) { throw new RuntimeException("Internal error: Failed to get field in method getInternalState.", e); } } /** * Find field in hierarchy. * * @param object the object * @param fieldName the field name * @return the field */ private static Field findFieldInHierarchy(Object object, String fieldName) { return findFieldInHierarchy(object, new FieldNameMatcherStrategy(fieldName)); } /** * Find field in hierarchy. * * @param object the object * @param strategy the strategy * @return the field */ private static Field findFieldInHierarchy(Object object, FieldMatcherStrategy strategy) { assertObjectInGetInternalStateIsNotNull(object); return findSingleFieldUsingStrategy(strategy, object, true, getType(object)); } /** * Find field. * * @param object the object * @param strategy the strategy * @param where the where * @return the field */ private static Field findField(Object object, FieldMatcherStrategy strategy, Class where) { return findSingleFieldUsingStrategy(strategy, object, false, where); } /** * Find single field using strategy. * * @param strategy the strategy * @param object the object * @param checkHierarchy the check hierarchy * @param startClass the start class * @return the field */ private static Field findSingleFieldUsingStrategy(FieldMatcherStrategy strategy, Object object, boolean checkHierarchy, Class startClass) { assertObjectInGetInternalStateIsNotNull(object); Field foundField = null; final Class originalStartClass = startClass; while (startClass != null) { final Field[] declaredFields = startClass.getDeclaredFields(); for (Field field : declaredFields) { if (strategy.matches(field) && hasFieldProperModifier(object, field, false)) { if (foundField != null) { throw new TooManyFieldsFoundException("Two or more fields matching " + strategy + "."); } foundField = field; } } if (foundField != null) { break; } else if (!checkHierarchy) { break; } startClass = startClass.getSuperclass(); } if (foundField == null) { strategy.notFound(originalStartClass, !isClass(object)); } foundField.setAccessible(true); return foundField; } /** * Find all fields using strategy. * * @param strategy the strategy * @param object the object * @param checkHierarchy the check hierarchy * @param onlyInstanceFields whether to only allow instance fields * @param startClass the start class * @return the set */ private static Set findAllFieldsUsingStrategy(FieldMatcherStrategy strategy, Object object, boolean checkHierarchy, boolean onlyInstanceFields, Class startClass) { assertObjectInGetInternalStateIsNotNull(object); final Set foundFields = new LinkedHashSet(); while (startClass != null) { final Field[] declaredFields = startClass.getDeclaredFields(); for (Field field : declaredFields) { if (strategy.matches(field) && hasFieldProperModifier(object, field, onlyInstanceFields)) { // TODO replace by the class try { field.setAccessible(true); foundFields.add(field); } catch (Exception ignored) { // the InaccessibleObjectException is thrown in Java 9 in case // if a field is private and a module is not open } } } if (!checkHierarchy) { break; } startClass = startClass.getSuperclass(); } return Collections.unmodifiableSet(foundFields); } /** * Checks for field proper modifier. * * @param object the object * @param field the field * @param onlyInstanceFields whether to only allow instance fields * @return true, if successful */ private static boolean hasFieldProperModifier(Object object, Field field, boolean onlyInstanceFields) { if (onlyInstanceFields) { return !Modifier.isStatic(field.getModifiers()); } else if (object instanceof Class) { return Modifier.isStatic(field.getModifiers()); } else { return !Modifier.isStatic(field.getModifiers()); } } /** * Get the value of a field using reflection. This method will traverse the * super class hierarchy until the first field of type fieldType is * found. The value of this field will be returned. * * @param the generic type * @param object the object to modify * @param fieldType the type of the field * @return the internal state */ @SuppressWarnings("unchecked") public static T getInternalState(Object object, Class fieldType) { Field foundField = findFieldInHierarchy(object, new AssignableToFieldTypeMatcherStrategy(fieldType)); try { return (T) foundField.get(object); } catch (IllegalAccessException e) { throw new RuntimeException("Internal error: Failed to get field in method getInternalState.", e); } } /** * Get the value of a field using reflection. Use this method when you need * to specify in which class the field is declared. The first field matching * the fieldType in where will is the field whose value * will be returned. * * @param the expected type of the field * @param object the object to modify * @param fieldType the type of the field * @param where which class the field is defined * @return the internal state */ @SuppressWarnings("unchecked") public static T getInternalState(Object object, Class fieldType, Class where) { if (object == null) { throw new IllegalArgumentException("object and type are not allowed to be null"); } try { return (T) findFieldOrThrowException(fieldType, where).get(object); } catch (IllegalAccessException e) { throw new RuntimeException("Internal error: Failed to get field in method getInternalState.", e); } } /** * Get the value of a field using reflection. Use this method when you need * to specify in which class the field is declared. This might be useful * when you have mocked the instance you are trying to access. Use this * method to avoid casting. * * @param the expected type of the field * @param object the object to modify * @param fieldName the name of the field * @param where which class the field is defined * @return the internal state */ @SuppressWarnings("unchecked") public static T getInternalState(Object object, String fieldName, Class where) { if (object == null || fieldName == null || fieldName.equals("") || fieldName.startsWith(" ")) { throw new IllegalArgumentException("object, field name, and \"where\" must not be empty or null."); } Field field = null; try { field = where.getDeclaredField(fieldName); field.setAccessible(true); return (T) field.get(object); } catch (NoSuchFieldException e) { throw new FieldNotFoundException("Field '" + fieldName + "' was not found in class " + where.getName() + "."); } catch (Exception e) { throw new RuntimeException("Internal error: Failed to get field in method getInternalState.", e); } } /** * Invoke a private or inner class method without the need to specify the * method name. This is thus a more refactor friendly version of the * * @param the generic type * @param tested the tested * @param arguments the arguments * @return the t * @throws Exception the exception * {@link #invokeMethod(Object, String, Object...)} method and * is recommend over this method for that reason. This method * might be useful to test private methods. */ @SuppressWarnings("unchecked") public static synchronized T invokeMethod(Object tested, Object... arguments) throws Exception { return (T) doInvokeMethod(tested, null, null, arguments); } /** * Invoke a private or inner class method without the need to specify the * method name. This is thus a more refactor friendly version of the * * @param the generic type * @param tested the tested * @param arguments the arguments * @return the t * @throws Exception the exception * {@link #invokeMethod(Object, String, Object...)} method and * is recommend over this method for that reason. This method * might be useful to test private methods. */ @SuppressWarnings("unchecked") public static synchronized T invokeMethod(Class tested, Object... arguments) throws Exception { return (T) doInvokeMethod(tested, null, null, arguments); } /** * Invoke a private or inner class method. This might be useful to test * private methods. * * @param the generic type * @param tested the tested * @param methodToExecute the method to execute * @param arguments the arguments * @return the t * @throws Exception the exception */ @SuppressWarnings("unchecked") public static synchronized T invokeMethod(Object tested, String methodToExecute, Object... arguments) throws Exception { return (T) doInvokeMethod(tested, null, methodToExecute, arguments); } /** * Invoke a private or inner class method in cases where power mock cannot * automatically determine the type of the parameters, for example when * mixing primitive types and wrapper types in the same method. For most * situations use {@link #invokeMethod(Class, String, Object...)} instead. * * @param the generic type * @param tested the tested * @param methodToExecute the method to execute * @param argumentTypes the argument types * @param arguments the arguments * @return the t * @throws Exception Exception that may occur when invoking this method. */ @SuppressWarnings("unchecked") public static synchronized T invokeMethod(Object tested, String methodToExecute, Class[] argumentTypes, Object... arguments) throws Exception { final Class unmockedType = getType(tested); Method method = getMethod(unmockedType, methodToExecute, argumentTypes); if (method == null) { throwExceptionIfMethodWasNotFound(unmockedType, methodToExecute, null, arguments); } return (T) performMethodInvocation(tested, method, arguments); } /** * Invoke a private or inner class method in a subclass (defined by * {@code definedIn}) in cases where power mock cannot automatically * determine the type of the parameters, for example when mixing primitive * types and wrapper types in the same method. For most situations use * * @param the generic type * @param tested the tested * @param methodToExecute the method to execute * @param definedIn the defined in * @param argumentTypes the argument types * @param arguments the arguments * @return the t * @throws Exception Exception that may occur when invoking this method. * {@link #invokeMethod(Class, String, Object...)} instead. */ @SuppressWarnings("unchecked") public static synchronized T invokeMethod(Object tested, String methodToExecute, Class definedIn, Class[] argumentTypes, Object... arguments) throws Exception { Method method = getMethod(definedIn, methodToExecute, argumentTypes); if (method == null) { throwExceptionIfMethodWasNotFound(definedIn, methodToExecute, null, arguments); } return (T) performMethodInvocation(tested, method, arguments); } /** * Invoke a private or inner class method in that is located in a subclass * of the tested instance. This might be useful to test private methods. * * @param the generic type * @param tested the tested * @param declaringClass the declaring class * @param methodToExecute the method to execute * @param arguments the arguments * @return the t * @throws Exception Exception that may occur when invoking this method. */ @SuppressWarnings("unchecked") public static synchronized T invokeMethod(Object tested, Class declaringClass, String methodToExecute, Object... arguments) throws Exception { return (T) doInvokeMethod(tested, declaringClass, methodToExecute, arguments); } /** * Invoke a private method in that is located in a subclass of an instance. * This might be useful to test overloaded private methods. * * Use this for overloaded methods only, if possible use * * @param the generic type * @param object the object * @param declaringClass the declaring class * @param methodToExecute the method to execute * @param parameterTypes the parameter types * @param arguments the arguments * @return the t * @throws Exception Exception that may occur when invoking this method. * {@link #invokeMethod(Object, Object...)} or * {@link #invokeMethod(Object, String, Object...)} instead. */ @SuppressWarnings("unchecked") public static synchronized T invokeMethod(Object object, Class declaringClass, String methodToExecute, Class[] parameterTypes, Object... arguments) throws Exception { if (object == null) { throw new IllegalArgumentException("object cannot be null"); } final Method methodToInvoke = getMethod(declaringClass, methodToExecute, parameterTypes); // Invoke method return (T) performMethodInvocation(object, methodToInvoke, arguments); } /** * Invoke a private or inner class method. This might be useful to test * private methods. * * @param the generic type * @param clazz the clazz * @param methodToExecute the method to execute * @param arguments the arguments * @return the t * @throws Exception the exception */ @SuppressWarnings("unchecked") public static synchronized T invokeMethod(Class clazz, String methodToExecute, Object... arguments) throws Exception { return (T) doInvokeMethod(clazz, null, methodToExecute, arguments); } /** * Do invoke method. * * @param the generic type * @param tested the tested * @param declaringClass the declaring class * @param methodToExecute the method to execute * @param arguments the arguments * @return the t * @throws Exception the exception */ @SuppressWarnings("unchecked") private static T doInvokeMethod(Object tested, Class declaringClass, String methodToExecute, Object... arguments) throws Exception { Method methodToInvoke = findMethodOrThrowException(tested, declaringClass, methodToExecute, arguments); // Invoke test return (T) performMethodInvocation(tested, methodToInvoke, arguments); } /** * Finds and returns a certain method. If the method couldn't be found this * method delegates to * * @param tested The instance or class containing the method. * @param declaringClass The class where the method is supposed to be declared (may be * {@code null}). * @param methodToExecute The method name. If {@code null} then method will be * looked up based on the argument types only. * @param arguments The arguments of the methods. * @return A single method. * @throws MethodNotFoundException if no method was found. * @throws TooManyMethodsFoundException if too methods matched. * @throws IllegalArgumentException if {@code tested} is null. */ public static Method findMethodOrThrowException(Object tested, Class declaringClass, String methodToExecute, Object[] arguments){ if (tested == null) { throw new IllegalArgumentException("The object to perform the operation on cannot be null."); } /* * Get methods from the type if it's not mocked or from the super type * if the tested object is mocked. */ Class testedType = null; if (isClass(tested)) { testedType = (Class) tested; } else { testedType = tested.getClass(); } Method[] methods = null; if (declaringClass == null) { methods = getAllMethods(testedType); } else { methods = declaringClass.getDeclaredMethods(); } Method potentialMethodToInvoke = null; for (Method method : methods) { if (methodToExecute == null || method.getName().equals(methodToExecute)) { Class[] paramTypes = method.getParameterTypes(); if ((arguments != null && (paramTypes.length == arguments.length))) { if (paramTypes.length == 0) { potentialMethodToInvoke = method; break; } boolean methodFound = checkArgumentTypesMatchParameterTypes(method.isVarArgs(), paramTypes, arguments); if (methodFound) { if (potentialMethodToInvoke == null) { potentialMethodToInvoke = method; } else if (potentialMethodToInvoke.getName().equals(method.getName())) { if (areAllArgumentsOfSameType(arguments) && potentialMethodToInvoke.getDeclaringClass() != method.getDeclaringClass()) { // We've already found the method which means that "potentialMethodToInvoke" overrides "method". return potentialMethodToInvoke; } else { // We've found an overloaded method return getBestMethodCandidate(getType(tested), method.getName(), getTypes(arguments), false); } } else { // A special case to be backward compatible Method bestCandidateMethod = getMethodWithMostSpecificParameterTypes(method, potentialMethodToInvoke); if (bestCandidateMethod != null) { potentialMethodToInvoke = bestCandidateMethod; continue; } /* * We've already found a method match before, this * means that PowerMock cannot determine which * method to expect since there are two methods with * the same name and the same number of arguments * but one is using wrapper types. */ throwExceptionWhenMultipleMethodMatchesFound("argument parameter types", new Method[]{ potentialMethodToInvoke, method}); } } } else if (isPotentialVarArgsMethod(method, arguments)) { if (potentialMethodToInvoke == null) { potentialMethodToInvoke = method; } else { /* * We've already found a method match before, this means * that PowerMock cannot determine which method to * expect since there are two methods with the same name * and the same number of arguments but one is using * wrapper types. */ throwExceptionWhenMultipleMethodMatchesFound("argument parameter types", new Method[]{ potentialMethodToInvoke, method}); } break; } else if (arguments != null && (paramTypes.length != arguments.length)) { continue; } else if (arguments == null && paramTypes.length == 1 && !paramTypes[0].isPrimitive()) { potentialMethodToInvoke = method; } } } WhiteboxImpl.throwExceptionIfMethodWasNotFound(getType(tested), methodToExecute, potentialMethodToInvoke, arguments); return potentialMethodToInvoke; } /** * Find the method whose parameter types most closely matches the {@code types}. * * @param firstMethodCandidate The first method candidate * @param secondMethodCandidate The second method candidate * @return The method that most closely matches the provided types or {@code null} if no method match. */ private static Method getMethodWithMostSpecificParameterTypes(Method firstMethodCandidate, Method secondMethodCandidate) { Class[] firstMethodCandidateParameterTypes = firstMethodCandidate.getParameterTypes(); Class[] secondMethodCandidateParameterTypes = secondMethodCandidate.getParameterTypes(); Method bestMatch = null; for (int i = 0; i < firstMethodCandidateParameterTypes.length; i++) { Class candidateType1 = toBoxedIfPrimitive(firstMethodCandidateParameterTypes[i]); Class candidateType2 = toBoxedIfPrimitive(secondMethodCandidateParameterTypes[i]); if (!candidateType1.equals(candidateType2)) { Method potentialMatch = null; if (candidateType1.isAssignableFrom(candidateType2)) { potentialMatch = secondMethodCandidate; } else if (candidateType2.isAssignableFrom(candidateType1)) { potentialMatch = firstMethodCandidate; } if (potentialMatch != null) { if (bestMatch != null && !potentialMatch.equals(bestMatch)) { /* * We cannot determine which method is the most specific because one parameter of the first candidate * was more specific and another parameter of the second candidate was more specific. */ return null; } else { bestMatch = potentialMatch; } } } } return bestMatch; } private static Class toBoxedIfPrimitive(Class type) { return type.isPrimitive() ? BoxedWrapper.getBoxedFromPrimitiveType(type) : type; } /** * Gets the types. * * @param arguments the arguments * @return the types */ private static Class[] getTypes(Object[] arguments) { Class[] classes = new Class[arguments.length]; for (int i = 0; i < arguments.length; i++) { classes[i] = getType(arguments[i]); } return classes; } /** * Gets the best method candidate. * * @param cls the cls * @param methodName the method name * @param signature the signature * @param exactParameterTypeMatch {@code true} if the {@code expectedTypes} must match * the parameter types must match exactly, {@code false} if * the {@code expectedTypes} are allowed to be converted * into primitive types if they are of a wrapped type and still * match. * @return the best method candidate */ public static Method getBestMethodCandidate(Class cls, String methodName, Class[] signature, boolean exactParameterTypeMatch) { final Method foundMethod; final Method[] methods = getMethods(cls, methodName, signature, exactParameterTypeMatch); if (methods.length == 1) { foundMethod = methods[0]; } else { // We've found overloaded methods, we need to find the best one to invoke. Arrays.sort(methods, ComparatorFactory.createMethodComparator()); foundMethod = methods[0]; } return foundMethod; } /** * Finds and returns the default constructor. If the constructor couldn't be * found this method delegates to {@link #throwExceptionWhenMultipleConstructorMatchesFound(java.lang.reflect.Constructor[])}. * * @param type The type where the constructor should be located. * @return The found constructor. * @throws ConstructorNotFoundException if too many constructors was found. */ public static Constructor findDefaultConstructorOrThrowException(Class type) throws ConstructorNotFoundException { if (type == null) { throw new IllegalArgumentException("type cannot be null"); } final Constructor declaredConstructor; try { declaredConstructor = type.getDeclaredConstructor(); } catch (NoSuchMethodException e) { throw new ConstructorNotFoundException(String.format("Couldn't find a default constructor in %s.", type.getName())); } return declaredConstructor; } /** * Finds and returns any constructor. If the constructor couldn't be * found this method delegates to {@link #throwExceptionWhenMultipleConstructorMatchesFound(java.lang.reflect.Constructor[])}. * * @param type The type where the constructor should be located. * @return The found constructor. * @throws TooManyConstructorsFoundException if too many constructors was found. */ public static Constructor findConstructorOrThrowException(Class type) { final Constructor[] declaredConstructors = filterPowerMockConstructor(type.getDeclaredConstructors()); if (declaredConstructors.length > 1) { throwExceptionWhenMultipleConstructorMatchesFound(declaredConstructors); } return declaredConstructors[0]; } /** * Filter power mock constructor. * * @param declaredConstructors the declared constructors * @return the constructor[] */ static Constructor[] filterPowerMockConstructor(Constructor[] declaredConstructors) { Set> constructors = new HashSet>(); for (Constructor constructor : declaredConstructors) { final Class[] parameterTypes = constructor.getParameterTypes(); if (parameterTypes.length >= 1 && parameterTypes[parameterTypes.length - 1].getName().equals( "org.powermock.core.IndicateReloadClass")) { continue; } else { constructors.add(constructor); } } return constructors.toArray(new Constructor[constructors.size()]); } /** * Finds and returns a certain constructor. If the constructor couldn't be * found this method delegates to * * @param type The type where the constructor should be located. * @param arguments The arguments passed to the constructor. * @return The found constructor. * @throws ConstructorNotFoundException if no constructor was found. * @throws TooManyConstructorsFoundException if too constructors matched. * @throws IllegalArgumentException if {@code type} is null. */ public static Constructor findUniqueConstructorOrThrowException(Class type, Object... arguments) { return new ConstructorFinder(type, arguments).findConstructor(); } /** * Convert argument types to primitive. * * @param paramTypes the param types * @param arguments the arguments * @return the class[] */ private static Class[] convertArgumentTypesToPrimitive(Class[] paramTypes, Object[] arguments) { Class[] types = new Class[arguments.length]; for (int i = 0; i < arguments.length; i++) { Class argumentType = null; if (arguments[i] == null) { argumentType = paramTypes[i]; } else { argumentType = getType(arguments[i]); } Class primitiveWrapperType = PrimitiveWrapper.getPrimitiveFromWrapperType(argumentType); if (primitiveWrapperType == null) { types[i] = argumentType; } else { types[i] = primitiveWrapperType; } } return types; } /** * Throw exception if method was not found. * * @param type the type * @param methodName the method name * @param methodToMock the method to mock * @param arguments the arguments */ public static void throwExceptionIfMethodWasNotFound(Class type, String methodName, Method methodToMock, Object... arguments) { if (methodToMock == null) { String methodNameData = ""; if (methodName != null) { methodNameData = "with name '" + methodName + "' "; } throw new MethodNotFoundException("No method found " + methodNameData + "with parameter types: [ " + getArgumentTypesAsString(arguments) + " ] in class " + getOriginalUnmockedType(type) .getName() + "."); } } /** * Throw exception if field was not found. * * @param type the type * @param fieldName the field name * @param field the field */ public static void throwExceptionIfFieldWasNotFound(Class type, String fieldName, Field field) { if (field == null) { throw new FieldNotFoundException("No field was found with name '" + fieldName + "' in class " + getOriginalUnmockedType(type).getName() + "."); } } /** * Throw exception if constructor was not found. * * @param type the type * @param potentialConstructor the potential constructor * @param arguments the arguments */ static void throwExceptionIfConstructorWasNotFound(Class type, Constructor potentialConstructor, Object... arguments) { if (potentialConstructor == null) { String message = "No constructor found in class '" + getOriginalUnmockedType(type).getName() + "' with " + "parameter types: [ " + getArgumentTypesAsString(arguments) + " ]."; throw new ConstructorNotFoundException(message); } } /** * Gets the argument types as string. * * @param arguments the arguments * @return the argument types as string */ static String getArgumentTypesAsString(Object... arguments) { StringBuilder argumentsAsString = new StringBuilder(); final String noParameters = ""; if (arguments != null && arguments.length != 0) { for (int i = 0; i < arguments.length; i++) { String argumentName = null; Object argument = arguments[i]; if (argument instanceof Class) { argumentName = ((Class) argument).getName(); } else if (argument instanceof Class[] && arguments.length == 1) { Class[] argumentArray = (Class[]) argument; if (argumentArray.length > 0) { for (int j = 0; j < argumentArray.length; j++) { appendArgument(argumentsAsString, j, argumentArray[j] == null ? "null" : getUnproxyType(argumentArray[j]).getName(), argumentArray); } return argumentsAsString.toString(); } else { argumentName = noParameters; } } else if (argument == null) { argumentName = "null"; } else { argumentName = getUnproxyType(argument).getName(); } appendArgument(argumentsAsString, i, argumentName, arguments); } } else { argumentsAsString.append(""); } return argumentsAsString.toString(); } /** * Append argument. * * @param argumentsAsString the arguments as string * @param index the index * @param argumentName the argument name * @param arguments the arguments */ private static void appendArgument(StringBuilder argumentsAsString, int index, String argumentName, Object[] arguments) { argumentsAsString.append(argumentName); if (index != arguments.length - 1) { argumentsAsString.append(", "); } } /** * Invoke a constructor. Useful for testing classes with a private * constructor when PowerMock cannot determine which constructor to invoke. * This only happens if you have two constructors with the same number of * arguments where one is using primitive data types and the other is using * the wrapped counter part. For example: * *

     * public class MyClass {
     * private MyClass(Integer i) {
     * ...
     * }
     *
     * private MyClass(int i) {
     * ...
     * }
     * 
* * This ought to be a really rare case. So for most situation, use * * @param the generic type * @param classThatContainsTheConstructorToTest the class that contains the constructor to test * @param parameterTypes the parameter types * @param arguments the arguments * @return The object created after the constructor has been invoked. * @throws Exception If an exception occur when invoking the constructor. * {@link #invokeConstructor(Class, Object...)} instead. */ public static T invokeConstructor(Class classThatContainsTheConstructorToTest, Class[] parameterTypes, Object[] arguments) throws Exception { if (parameterTypes != null && arguments != null) { if (parameterTypes.length != arguments.length) { throw new IllegalArgumentException("parameterTypes and arguments must have the same length"); } } Constructor constructor = null; try { constructor = classThatContainsTheConstructorToTest.getDeclaredConstructor(parameterTypes); } catch (Exception e) { throw new ConstructorNotFoundException("Could not lookup the constructor", e); } return createInstance(constructor, arguments); } /** * Invoke a constructor. Useful for testing classes with a private * constructor. * * @param the generic type * @param classThatContainsTheConstructorToTest the class that contains the constructor to test * @param arguments the arguments * @return The object created after the constructor has been invoked. * @throws Exception If an exception occur when invoking the constructor. */ public static T invokeConstructor(Class classThatContainsTheConstructorToTest, Object... arguments) throws Exception { if (classThatContainsTheConstructorToTest == null) { throw new IllegalArgumentException("The class should contain the constructor cannot be null."); } Class[] argumentTypes = null; if (arguments == null) { argumentTypes = new Class[0]; } else { argumentTypes = new Class[arguments.length]; for (int i = 0; i < arguments.length; i++) { argumentTypes[i] = getType(arguments[i]); } } Constructor constructor = null; constructor = getBestCandidateConstructor(classThatContainsTheConstructorToTest, argumentTypes, arguments); return createInstance(constructor, arguments); } private static Constructor getBestCandidateConstructor(Class classThatContainsTheConstructorToTest, Class[] argumentTypes, Object[] arguments) { Constructor constructor; Constructor potentialConstructorWrapped = getPotentialConstructorWrapped(classThatContainsTheConstructorToTest, argumentTypes); Constructor potentialConstructorPrimitive = getPotentialConstructorPrimitive(classThatContainsTheConstructorToTest, argumentTypes); if (potentialConstructorPrimitive == null && potentialConstructorWrapped == null) { // Check if we can find a matching var args constructor. constructor = getPotentialVarArgsConstructor(classThatContainsTheConstructorToTest, arguments); if (constructor == null) { throw new ConstructorNotFoundException("Failed to find a constructor with parameter types: [" + getArgumentTypesAsString(arguments) + "]"); } } else if (potentialConstructorPrimitive == null) { constructor = potentialConstructorWrapped; } else if (potentialConstructorWrapped == null) { constructor = potentialConstructorPrimitive; } else if (arguments == null || arguments.length == 0 && potentialConstructorPrimitive != null) { constructor = potentialConstructorPrimitive; } else { throw new TooManyConstructorsFoundException( "Could not determine which constructor to execute. Please specify the parameter types by hand."); } return constructor; } private static Constructor getPotentialConstructorWrapped(Class classThatContainsTheConstructorToTest, Class[] argumentTypes) { return new CandidateConstructorSearcher(classThatContainsTheConstructorToTest, argumentTypes) .findConstructor(); } private static Constructor getPotentialConstructorPrimitive(Class classThatContainsTheConstructorToTest, Class[] argumentTypes) { Constructor potentialConstructorPrimitive = null; try { Class[] primitiveType = PrimitiveWrapper.toPrimitiveType(argumentTypes); if (!argumentTypesEqualsPrimitiveTypes(argumentTypes, primitiveType)) { potentialConstructorPrimitive = new CandidateConstructorSearcher(classThatContainsTheConstructorToTest, primitiveType) .findConstructor(); } } catch (Exception e) { // Do nothing } return potentialConstructorPrimitive; } private static boolean argumentTypesEqualsPrimitiveTypes(Class[] argumentTypes, Class[] primitiveType) { for (int index = 0; index < argumentTypes.length; index++) { if (!argumentTypes[index].equals(primitiveType[index])) { return false; } } return true; } /** * Gets the potential var args constructor. * * @param the generic type * @param classThatContainsTheConstructorToTest the class that contains the constructor to test * @param arguments the arguments * @return the potential var args constructor */ @SuppressWarnings("unchecked") private static Constructor getPotentialVarArgsConstructor(Class classThatContainsTheConstructorToTest, Object... arguments) { Constructor[] declaredConstructors = (Constructor[]) classThatContainsTheConstructorToTest .getDeclaredConstructors(); for (Constructor possibleVarArgsConstructor : declaredConstructors) { if (possibleVarArgsConstructor.isVarArgs()) { if (arguments == null || arguments.length == 0) { return possibleVarArgsConstructor; } else { Class[] parameterTypes = possibleVarArgsConstructor.getParameterTypes(); if (parameterTypes[parameterTypes.length - 1].getComponentType().isAssignableFrom( getType(arguments[0]))) { return possibleVarArgsConstructor; } } } } return null; } /** * Creates the instance. * * @param the generic type * @param constructor the constructor * @param arguments the arguments * @return the t * @throws Exception the exception */ private static T createInstance(Constructor constructor, Object... arguments) throws Exception { if (constructor == null) { throw new IllegalArgumentException("Constructor cannot be null"); } constructor.setAccessible(true); T createdObject = null; try { if (constructor.isVarArgs()) { Class[] parameterTypes = constructor.getParameterTypes(); final int varArgsIndex = parameterTypes.length - 1; Class varArgsType = parameterTypes[varArgsIndex].getComponentType(); Object varArgsArrayInstance = createAndPopulateVarArgsArray(varArgsType, varArgsIndex, arguments); Object[] completeArgumentList = new Object[parameterTypes.length]; System.arraycopy(arguments, 0, completeArgumentList, 0, varArgsIndex); completeArgumentList[completeArgumentList.length - 1] = varArgsArrayInstance; createdObject = constructor.newInstance(completeArgumentList); } else { createdObject = constructor.newInstance(arguments); } } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof Exception) { throw (Exception) cause; } else if (cause instanceof Error) { throw (Error) cause; } } return createdObject; } /** * Creates the and populate var args array. * * @param varArgsType the var args type * @param varArgsStartPosition the var args start position * @param arguments the arguments * @return the object */ private static Object createAndPopulateVarArgsArray(Class varArgsType, int varArgsStartPosition, Object... arguments) { Object arrayInstance = Array.newInstance(varArgsType, arguments.length - varArgsStartPosition); for (int i = varArgsStartPosition; i < arguments.length; i++) { Array.set(arrayInstance, i - varArgsStartPosition, arguments[i]); } return arrayInstance; } /** * Get all declared constructors in the class and set accessible to * {@code true}. * * @param clazz The class whose constructors to get. * @return All constructors declared in this class hierarchy. */ public static Constructor[] getAllConstructors(Class clazz) { Constructor[] declaredConstructors = clazz.getDeclaredConstructors(); for (Constructor constructor : declaredConstructors) { if (!constructor.isAccessible()) { constructor.setAccessible(true); } } return declaredConstructors; } /** * Get all methods in a class hierarchy! Both declared an non-declared (no * duplicates). * * @param clazz The class whose methods to get. * @return All methods declared in this class hierarchy. */ public static Method[] getAllMethods(Class clazz) { Method[] allMethods = allClassMethodsCache.get(clazz); if (allMethods == null) { // Allows a race between concurrent threads coming for clazz's methods at the same time, // but the race seems to be harmless. allMethods = doGetAllMethods(clazz); allClassMethodsCache.put(clazz, allMethods); } return allMethods; } private static Method[] doGetAllMethods(Class clazz) { if (clazz == null) { throw new IllegalArgumentException("You must specify a class in order to get the methods."); } Set methods = new LinkedHashSet(); Class thisType = clazz; while (thisType != null) { final Class type = thisType; final Method[] declaredMethods = AccessController.doPrivileged(new PrivilegedAction() { @Override public Method[] run() { return type.getDeclaredMethods(); } }); for (Method method : declaredMethods) { if(!"finalize".equals(method.getName())) { method.setAccessible(true); methods.add(method); } } Collections.addAll(methods, type.getMethods()); thisType = thisType.getSuperclass(); } return methods.toArray(new Method[methods.size()]); } /** * Get all public methods for a class (no duplicates)! Note that the * class-hierarchy will not be traversed. * * @param clazz The class whose methods to get. * @return All public methods declared in class. */ private static Method[] getAllPublicMethods(Class clazz) { if (clazz == null) { throw new IllegalArgumentException("You must specify a class in order to get the methods."); } Set methods = new LinkedHashSet(); for (Method method : clazz.getMethods()) { method.setAccessible(true); methods.add(method); } return methods.toArray(new Method[0]); } /** * Get all fields in a class hierarchy! Both declared an non-declared (no * duplicates). * * @param clazz The class whose fields to get. * @return All fields declared in this class hierarchy. */ public static Field[] getAllFields(Class clazz) { if (clazz == null) { throw new IllegalArgumentException("You must specify the class that contains the fields"); } Set fields = new LinkedHashSet(); Class thisType = clazz; while (thisType != null) { final Field[] declaredFields = thisType.getDeclaredFields(); for (Field field : declaredFields) { field.setAccessible(true); fields.add(field); } thisType = thisType.getSuperclass(); } return fields.toArray(new Field[fields.size()]); } /** * Get the first parent constructor defined in a super class of * {@code klass}. * * @param klass The class where the constructor is located. {@code null} * ). * @return A . */ public static Constructor getFirstParentConstructor(Class klass) { try { return getOriginalUnmockedType(klass).getSuperclass().getDeclaredConstructors()[0]; } catch (Exception e) { throw new ConstructorNotFoundException("Failed to lookup constructor.", e); } } /** * Finds and returns a method based on the input parameters. If no * {@code parameterTypes} are present the method will return the first * method with name {@code methodNameToMock}. If no method was found, * {@code null} will be returned. If no {@code methodName} is * specified the method will be found based on the parameter types. If * neither method name nor parameters are specified an * * @param the generic type * @param type the type * @param methodName the method name * @param parameterTypes the parameter types * @return the method {@link IllegalArgumentException} will be thrown. */ public static Method findMethod(Class type, String methodName, Class... parameterTypes) { if (methodName == null && parameterTypes == null) { throw new IllegalArgumentException("You must specify a method name or parameter types."); } List matchingMethodsList = new LinkedList(); for (Method method : getAllMethods(type)) { if (methodName == null || method.getName().equals(methodName)) { if (parameterTypes != null && parameterTypes.length > 0) { // If argument types was supplied, make sure that they // match. Class[] paramTypes = method.getParameterTypes(); if (!checkIfParameterTypesAreSame(method.isVarArgs(), parameterTypes, paramTypes)) { continue; } } // Add the method to the matching methods list. matchingMethodsList.add(method); } } Method methodToMock = null; if (matchingMethodsList.size() > 0) { if (matchingMethodsList.size() == 1) { // We've found a unique method match. methodToMock = matchingMethodsList.get(0); } else if ((parameterTypes != null ? parameterTypes.length : 0) == 0) { /* * If we've found several matches and we've supplied no * parameter types, go through the list of found methods and see * if we have a method with no parameters. In that case return * that method. */ for (Method method : matchingMethodsList) { if (method.getParameterTypes().length == 0) { methodToMock = method; break; } } if (methodToMock == null) { WhiteboxImpl.throwExceptionWhenMultipleMethodMatchesFound("argument parameter types", matchingMethodsList.toArray(new Method[matchingMethodsList.size()])); } } else { // We've found several matching methods. WhiteboxImpl.throwExceptionWhenMultipleMethodMatchesFound("argument parameter types", matchingMethodsList.toArray(new Method[matchingMethodsList.size()])); } } return methodToMock; } /** * Gets the unmocked type. * * @param the generic type * @param type the type * @return the unmocked type */ public static Class getOriginalUnmockedType(Class type) { return getUnproxiedType(type).getOriginalType(); } public static UnproxiedType getUnproxiedType(Class type) { return proxyFrameworks.getUnproxiedType(type); } /** * Throw exception when multiple method matches found. * * @param helpInfo the help info * @param methods the methods */ static void throwExceptionWhenMultipleMethodMatchesFound(String helpInfo, Method[] methods) { if (methods == null || methods.length < 2) { throw new IllegalArgumentException( "Internal error: throwExceptionWhenMultipleMethodMatchesFound needs at least two methods."); } StringBuilder sb = new StringBuilder(); sb.append("Several matching methods found, please specify the "); sb.append(helpInfo); sb.append(" so that PowerMock can determine which method you're referring to.\n"); sb.append("Matching methods in class ").append(methods[0].getDeclaringClass().getName()).append(" were:\n"); for (Method method : methods) { sb.append(method.getReturnType().getName()).append(" "); sb.append(method.getName()).append("( "); final Class[] parameterTypes = method.getParameterTypes(); for (Class paramType : parameterTypes) { sb.append(paramType.getName()).append(".class "); } sb.append(")\n"); } throw new TooManyMethodsFoundException(sb.toString()); } /** * Throw exception when multiple constructor matches found. * * @param constructors the constructors */ static void throwExceptionWhenMultipleConstructorMatchesFound(Constructor[] constructors) { if (constructors == null || constructors.length < 2) { throw new IllegalArgumentException( "Internal error: throwExceptionWhenMultipleConstructorMatchesFound needs at least two constructors."); } StringBuilder sb = new StringBuilder(); sb.append("Several matching constructors found, please specify the argument parameter types so that PowerMock can determine which method you're referring to.\n"); sb.append("Matching constructors in class ").append(constructors[0].getDeclaringClass().getName()) .append(" were:\n"); for (Constructor constructor : constructors) { sb.append(constructor.getName()).append("( "); final Class[] parameterTypes = constructor.getParameterTypes(); for (Class paramType : parameterTypes) { sb.append(paramType.getName()).append(".class "); } sb.append(")\n"); } throw new TooManyConstructorsFoundException(sb.toString()); } /** * Find method or throw exception. * * @param type the type * @param methodName the method name * @param parameterTypes the parameter types * @return the method */ @SuppressWarnings("all") public static Method findMethodOrThrowException(Class type, String methodName, Class... parameterTypes) { Method methodToMock = findMethod(type, methodName, parameterTypes); throwExceptionIfMethodWasNotFound(type, methodName, methodToMock, (Object[]) parameterTypes); return methodToMock; } /** * Get an array of {@link Method}'s that matches the supplied list of method * names. Both instance and static methods are taken into account. * * @param clazz The class that should contain the methods. * @param methodNames Names of the methods that will be returned. * @return An array of Method's. */ public static Method[] getMethods(Class clazz, String... methodNames) { if (methodNames == null || methodNames.length == 0) { throw new IllegalArgumentException("You must supply at least one method name."); } final List methodsToMock = new LinkedList(); Method[] allMethods = null; if (clazz.isInterface()) { allMethods = getAllPublicMethods(clazz); } else { allMethods = getAllMethods(clazz); } for (Method method : allMethods) { for (String methodName : methodNames) { if (method.getName().equals(methodName)) { method.setAccessible(true); methodsToMock.add(method); } } } final Method[] methodArray = methodsToMock.toArray(new Method[0]); if (methodArray.length == 0) { throw new MethodNotFoundException(String.format( "No methods matching the name(s) %s were found in the class hierarchy of %s.", concatenateStrings(methodNames), getType(clazz))); } return methodArray; } /** * Get an array of {@link Method}'s that matches the method name and whose * argument types are assignable from {@code expectedTypes}. Both * instance and static methods are taken into account. * * @param clazz The class that should contain the methods. * @param methodName Names of the methods that will be returned. * @param expectedTypes The methods must match * @param exactParameterTypeMatch {@code true} if the {@code expectedTypes} must match * the parameter types must match exactly, {@code false} if * the {@code expectedTypes} are allowed to be converted * into primitive types if they are of a wrapped type and still * match. * @return An array of Method's. */ public static Method[] getMethods(Class clazz, String methodName, Class[] expectedTypes, boolean exactParameterTypeMatch) { List matchingArgumentTypes = new LinkedList(); Method[] methods = getMethods(clazz, methodName); for (Method method : methods) { final Class[] parameterTypes = method.getParameterTypes(); if (checkIfParameterTypesAreSame(method.isVarArgs(), expectedTypes, parameterTypes) || (!exactParameterTypeMatch && checkIfParameterTypesAreSame(method.isVarArgs(), convertParameterTypesToPrimitive(expectedTypes), convertParameterTypesToPrimitive(parameterTypes)))) { matchingArgumentTypes.add(method); } } final Method[] methodArray = matchingArgumentTypes.toArray(new Method[0]); if (methodArray.length == 0) { throw new MethodNotFoundException(String.format( "No methods matching the name(s) %s were found in the class hierarchy of %s.", concatenateStrings(methodName), getType(clazz))); } return matchingArgumentTypes.toArray(new Method[matchingArgumentTypes.size()]); } /** * Get an array of {@link Field}'s that matches the supplied list of field * names. Both instance and static fields are taken into account. * * @param clazz The class that should contain the fields. * @param fieldNames Names of the fields that will be returned. * @return An array of Field's. May be of length 0 but not . */ public static Field[] getFields(Class clazz, String... fieldNames) { final List fields = new LinkedList(); for (Field field : getAllFields(clazz)) { for (String fieldName : fieldNames) { if (field.getName().equals(fieldName)) { fields.add(field); } } } final Field[] fieldArray = fields.toArray(new Field[fields.size()]); if (fieldArray.length == 0) { throw new FieldNotFoundException(String.format( "No fields matching the name(s) %s were found in the class hierarchy of %s.", concatenateStrings(fieldNames), getType(clazz))); } return fieldArray; } /** * Perform method invocation. * * @param the generic type * @param tested the tested * @param methodToInvoke the method to invoke * @param arguments the arguments * @return the t * @throws Exception the exception */ @SuppressWarnings("unchecked") public static T performMethodInvocation(Object tested, Method methodToInvoke, Object... arguments) throws Exception { final boolean accessible = methodToInvoke.isAccessible(); if (!accessible) { methodToInvoke.setAccessible(true); } try { if (isPotentialVarArgsMethod(methodToInvoke, arguments)) { Class[] parameterTypes = methodToInvoke.getParameterTypes(); final int varArgsIndex = parameterTypes.length - 1; Class varArgsType = parameterTypes[varArgsIndex].getComponentType(); Object varArgsArrayInstance = createAndPopulateVarArgsArray(varArgsType, varArgsIndex, arguments); Object[] completeArgumentList = new Object[parameterTypes.length]; System.arraycopy(arguments, 0, completeArgumentList, 0, varArgsIndex); completeArgumentList[completeArgumentList.length - 1] = varArgsArrayInstance; return (T) methodToInvoke.invoke(tested, completeArgumentList); } else { return (T) methodToInvoke.invoke(tested, arguments == null ? new Object[]{arguments} : arguments); } } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof Exception) { throw (Exception) cause; } else if (cause instanceof Error) { throw (Error) cause; } else { throw new MethodInvocationException(cause); } } finally { if (!accessible) { methodToInvoke.setAccessible(false); } } } /** * Gets the all method except. * * @param the generic type * @param type the type * @param methodNames the method names * @return the all method except */ public static Method[] getAllMethodExcept(Class type, String... methodNames) { List methodsToMock = new LinkedList(); Method[] methods = getAllMethods(type); iterateMethods: for (Method method : methods) { for (String methodName : methodNames) { if (method.getName().equals(methodName)) { continue iterateMethods; } } methodsToMock.add(method); } return methodsToMock.toArray(new Method[0]); } /** * Gets the all metods except. * * @param the generic type * @param type the type * @param methodNameToExclude the method name to exclude * @param argumentTypes the argument types * @return the all metods except */ public static Method[] getAllMethodsExcept(Class type, String methodNameToExclude, Class[] argumentTypes) { Method[] methods = getAllMethods(type); List methodList = new ArrayList(); outer: for (Method method : methods) { if (method.getName().equals(methodNameToExclude)) { if (argumentTypes != null && argumentTypes.length > 0) { final Class[] args = method.getParameterTypes(); if (args != null && args.length == argumentTypes.length) { for (int i = 0; i < args.length; i++) { if (args[i].isAssignableFrom(getOriginalUnmockedType(argumentTypes[i]))) { /* * Method was not found thus it should not be * mocked. Continue to investigate the next * method. */ continue outer; } } } } else { continue; } } methodList.add(method); } return methodList.toArray(new Method[0]); } /** * Are all methods static. * * @param methods the methods * @return true, if successful */ public static boolean areAllMethodsStatic(Method... methods) { for (Method method : methods) { if (!Modifier.isStatic(method.getModifiers())) { return false; } } return true; } /** * Check if all arguments are of the same type. * * @param arguments the arguments * @return true, if successful */ static boolean areAllArgumentsOfSameType(Object[] arguments) { if (arguments == null || arguments.length <= 1) { return true; } // Handle null values int index = 0; Object object = null; while (object == null && index < arguments.length) { object = arguments[index++]; } if (object == null) { return true; } // End of handling null values final Class firstArgumentType = getType(object); for (int i = index; i < arguments.length; i++) { final Object argument = arguments[i]; if (argument != null && !getType(argument).isAssignableFrom(firstArgumentType)) { return false; } } return true; } /** * Check argument types match parameter types. * * @param isVarArgs If the last parameter is a var args. * @param parameterTypes the parameter types * @param arguments the arguments * @return if all actual parameter types are assignable from the expected * arguments, otherwise. */ static boolean checkArgumentTypesMatchParameterTypes(boolean isVarArgs, Class[] parameterTypes, Object[] arguments) { if (parameterTypes == null) { throw new IllegalArgumentException("parameter types cannot be null"); } else if (!isVarArgs && arguments.length != parameterTypes.length) { return false; } for (int i = 0; i < arguments.length; i++) { Object argument = arguments[i]; if (argument == null) { final int index; if (i >= parameterTypes.length) { index = parameterTypes.length - 1; } else { index = i; } final Class type = parameterTypes[index]; if (type.isPrimitive()) { // Primitives cannot be null return false; } else { continue; } } else if (i >= parameterTypes.length) { if (isAssignableFrom(parameterTypes[parameterTypes.length - 1], getType(argument))) { continue; } else { return false; } } else { boolean assignableFrom = isAssignableFrom(parameterTypes[i], getType(argument)); final boolean isClass = parameterTypes[i].equals(Class.class) && isClass(argument); if (!assignableFrom && !isClass) { return false; } } } return true; } static boolean isAssignableFrom(Class type, Class from) { boolean assignableFrom; Class theType = getComponentType(type); Class theFrom = getComponentType(from); assignableFrom = theType.isAssignableFrom(theFrom); if (!assignableFrom && PrimitiveWrapper.hasPrimitiveCounterPart(theFrom)) { final Class primitiveFromWrapperType = PrimitiveWrapper.getPrimitiveFromWrapperType(theFrom); if (primitiveFromWrapperType != null) { assignableFrom = theType.isAssignableFrom(primitiveFromWrapperType); } } return assignableFrom; } private static Class getComponentType(Class type) { Class theType = type; while (theType.isArray()) { theType = theType.getComponentType(); } return theType; } /** * Gets the type. * * @param object the object * @return The type of the of an object. */ public static Class getType(Object object) { Class type = null; if (isClass(object)) { type = (Class) object; } else if (object != null) { type = object.getClass(); } return type; } /** * Gets the type. * * @param object the object * @return The type of the of an object. */ public static Class getUnproxyType(Object object) { Class type = null; if (isClass(object)) { type = (Class) object; } else if (object != null) { type = object.getClass(); } return type == null ? null : getOriginalUnmockedType(type); } /** * Get an inner class type. * * @param declaringClass The class in which the inner class is declared. * @param name The unqualified name (simple name) of the inner class. * @return The type. * @throws ClassNotFoundException the class not found exception */ @SuppressWarnings("unchecked") public static Class getInnerClassType(Class declaringClass, String name) throws ClassNotFoundException { return (Class) Class.forName(declaringClass.getName() + "$" + name); } /** * Get the type of a local inner class. * * @param declaringClass The class in which the local inner class is declared. * @param occurrence The occurrence of the local class. For example if you have two * local classes in the {@code declaringClass} you must pass * in {@code 1} if you want to get the type for the first * one or {@code 2} if you want the second one. * @param name The unqualified name (simple name) of the local class. * @return The type. * @throws ClassNotFoundException the class not found exception */ @SuppressWarnings("unchecked") public static Class getLocalClassType(Class declaringClass, int occurrence, String name) throws ClassNotFoundException { return (Class) Class.forName(declaringClass.getName() + "$" + occurrence + name); } /** * Get the type of an anonymous inner class. * * @param declaringClass The class in which the anonymous inner class is declared. * @param occurrence The occurrence of the anonymous inner class. For example if * you have two anonymous inner classes classes in the * {@code declaringClass} you must pass in {@code 1} if * you want to get the type for the first one or {@code 2} * if you want the second one. * @return The type. * @throws ClassNotFoundException the class not found exception */ @SuppressWarnings("unchecked") public static Class getAnonymousInnerClassType(Class declaringClass, int occurrence) throws ClassNotFoundException { return (Class) Class.forName(declaringClass.getName() + "$" + occurrence); } /** * Get all fields annotated with a particular annotation. This method * traverses the class hierarchy when checking for the annotation. * * @param object The object to look for annotations. Note that if're you're * passing an object only instance fields are checked, passing a * class will only check static fields. * @param annotation The annotation type to look for. * @param additionalAnnotations Optionally more annotations to look for. If any of the * annotations are associated with a particular field it will be * added to the resulting {@code Set}. * @return A set of all fields containing the particular annotation. */ @SuppressWarnings("unchecked") public static Set getFieldsAnnotatedWith(Object object, Class annotation, Class... additionalAnnotations) { Class[] annotations = null; if (additionalAnnotations == null || additionalAnnotations.length == 0) { annotations = (Class[]) new Class[]{annotation}; } else { annotations = (Class[]) new Class[additionalAnnotations.length + 1]; annotations[0] = annotation; System.arraycopy(additionalAnnotations, 0, annotations, 1, additionalAnnotations.length); } return getFieldsAnnotatedWith(object, annotations); } /** * Get all fields annotated with a particular annotation. This method * traverses the class hierarchy when checking for the annotation. * * @param object The object to look for annotations. Note that if're you're * passing an object only instance fields are checked, passing a * class will only check static fields. * @param annotationTypes The annotation types to look for * @return A set of all fields containing the particular annotation(s). * @since 1.3 */ public static Set getFieldsAnnotatedWith(Object object, Class[] annotationTypes) { return findAllFieldsUsingStrategy(new FieldAnnotationMatcherStrategy(annotationTypes), object, true, false, getType(object)); } /** * Get all fields assignable from a particular type. This method traverses * the class hierarchy when checking for the type. * * @param object The object to look for type. Note that if're you're passing an * object only instance fields are checked, passing a class will * only check static fields. * @param type The type to look for. * @return A set of all fields of the particular type. */ public static Set getFieldsOfType(Object object, Class type) { return findAllFieldsUsingStrategy(new AssignableFromFieldTypeMatcherStrategy(type), object, true, false, getType(object)); } /** * Get all instance fields for a particular object. It returns all fields * regardless of the field modifier and regardless of where in the class * hierarchy a field is located. * * @param object The object whose instance fields to get. * @return All instance fields in the hierarchy. All fields are set to * accessible */ public static Set getAllInstanceFields(Object object) { return findAllFieldsUsingStrategy(new AllFieldsMatcherStrategy(), object, true, true, getUnproxyType(object)); } /** * Get all static fields for a particular type. * * @param type The class whose static fields to get. * @return All static fields. All fields are set to accessible. */ public static Set getAllStaticFields(Class type) { return findAllFieldsUsingStrategy(new AllFieldsMatcherStrategy(), type, false, false, type); } /** * Checks if is class. * * @param argument the argument * @return true, if is class */ public static boolean isClass(Object argument) { return argument instanceof Class; } /** * Check if parameter types are same. * * @param isVarArgs Whether or not the method or constructor contains var args. * @param expectedParameterTypes the expected parameter types * @param actualParameterTypes the actual parameter types * @return if all actual parameter types are assignable from the expected * parameter types, otherwise. */ public static boolean checkIfParameterTypesAreSame(boolean isVarArgs, Class[] expectedParameterTypes, Class[] actualParameterTypes) { return new ParameterTypesMatcher(isVarArgs, expectedParameterTypes, actualParameterTypes).match(); } /** * Gets the field. * * @param fieldName the field name * @param where the where * @return the field */ private static Field getField(String fieldName, Class where) { if (where == null) { throw new IllegalArgumentException("where cannot be null"); } Field field = null; try { field = where.getDeclaredField(fieldName); field.setAccessible(true); } catch (NoSuchFieldException e) { throw new FieldNotFoundException("Field '" + fieldName + "' was not found in class " + where.getName() + "."); } return field; } /** * Find field or throw exception. * * @param fieldType the field type * @param where the where * @return the field */ private static Field findFieldOrThrowException(Class fieldType, Class where) { if (fieldType == null || where == null) { throw new IllegalArgumentException("fieldType and where cannot be null"); } Field field = null; for (Field currentField : where.getDeclaredFields()) { currentField.setAccessible(true); if (currentField.getType().equals(fieldType)) { field = currentField; break; } } if (field == null) { throw new FieldNotFoundException("Cannot find a field of type " + fieldType + "in where."); } return field; } /** * Sets the field. * * @param object the object * @param value the value * @param foundField the found field */ private static void setField(Object object, Object value, Field foundField) { boolean isStatic = (foundField.getModifiers() & Modifier.STATIC) == Modifier.STATIC; if (isStatic) { setStaticFieldUsingUnsafe(foundField, value); } else { setFieldUsingUnsafe(foundField, object, value); } } private static void setStaticFieldUsingUnsafe(final Field field, final Object newValue) { try { field.setAccessible(true); int fieldModifiersMask = field.getModifiers(); boolean isFinalModifierPresent = (fieldModifiersMask & Modifier.FINAL) == Modifier.FINAL; if (isFinalModifierPresent) { AccessController.doPrivileged(new PrivilegedAction() { @Override public Object run() { try { Unsafe unsafe = getUnsafe(); long offset = unsafe.staticFieldOffset(field); Object base = unsafe.staticFieldBase(field); setFieldUsingUnsafe(base, field.getType(), offset, newValue, unsafe); return null; } catch (Throwable t) { throw new RuntimeException(t); } }}); } else { field.set(null, newValue); } } catch (SecurityException ex) { throw new RuntimeException(ex); } catch (IllegalAccessException ex) { throw new RuntimeException(ex); } catch (IllegalArgumentException ex) { throw new RuntimeException(ex); } } private static void setFieldUsingUnsafe(final Field field, final Object object, final Object newValue) { try { field.setAccessible(true); int fieldModifiersMask = field.getModifiers(); boolean isFinalModifierPresent = (fieldModifiersMask & Modifier.FINAL) == Modifier.FINAL; if (isFinalModifierPresent) { AccessController.doPrivileged(new PrivilegedAction() { @Override public Object run() { try { Unsafe unsafe = getUnsafe(); long offset = unsafe.objectFieldOffset(field); setFieldUsingUnsafe(object, field.getType(), offset, newValue, unsafe); return null; } catch (Throwable t) { throw new RuntimeException(t); } } }); } else { try { field.set(object, newValue); } catch (IllegalAccessException ex) { throw new RuntimeException(ex); } } } catch (SecurityException ex) { throw new RuntimeException(ex); } } private static Unsafe getUnsafe() throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { Field field1 = Unsafe.class.getDeclaredField("theUnsafe"); field1.setAccessible(true); Unsafe unsafe = (Unsafe) field1.get(null); return unsafe; } private static void setFieldUsingUnsafe(Object base, Class type, long offset, Object newValue, Unsafe unsafe) { if (type == Integer.TYPE) { unsafe.putInt(base, offset, ((Integer) newValue)); } else if (type == Short.TYPE) { unsafe.putShort(base, offset, ((Short) newValue)); } else if (type == Long.TYPE) { unsafe.putLong(base, offset, ((Long) newValue)); } else if (type == Byte.TYPE) { unsafe.putByte(base, offset, ((Byte) newValue)); } else if (type == Boolean.TYPE) { unsafe.putBoolean(base, offset, ((Boolean) newValue)); } else if (type == Float.TYPE) { unsafe.putFloat(base, offset, ((Float) newValue)); } else if (type == Double.TYPE) { unsafe.putDouble(base, offset, ((Double) newValue)); } else if (type == Character.TYPE) { unsafe.putChar(base, offset, ((Character) newValue)); } else { unsafe.putObject(base, offset, newValue); } } /** * Concatenate strings. * * @param stringsToConcatenate the strings to concatenate * @return the string */ private static String concatenateStrings(String... stringsToConcatenate) { StringBuilder builder = new StringBuilder(); final int stringsLength = stringsToConcatenate.length; for (int i = 0; i < stringsLength; i++) { if (i == stringsLength - 1 && stringsLength != 1) { builder.append(" or "); } else if (i != 0) { builder.append(", "); } builder.append(stringsToConcatenate[i]); } return builder.toString(); } /** * Checks if is potential var args method. * * @param method the method * @param arguments the arguments * @return true, if is potential var args method */ private static boolean isPotentialVarArgsMethod(Method method, Object[] arguments) { return doesParameterTypesMatchForVarArgsInvocation(method.isVarArgs(), method.getParameterTypes(), arguments); } /** * Does parameter types match for var args invocation. * * @param isVarArgs the is var args * @param parameterTypes the parameter types * @param arguments the arguments * @return true, if successful */ static boolean doesParameterTypesMatchForVarArgsInvocation(boolean isVarArgs, Class[] parameterTypes, Object[] arguments) { if (isVarArgs && arguments != null && arguments.length >= 1 && parameterTypes != null && parameterTypes.length >= 1) { final Class componentType = parameterTypes[parameterTypes.length - 1].getComponentType(); final Object lastArgument = arguments[arguments.length - 1]; if (lastArgument != null) { final Class lastArgumentTypeAsPrimitive = getTypeAsPrimitiveIfWrapped(lastArgument); final Class varArgsParameterTypeAsPrimitive = getTypeAsPrimitiveIfWrapped(componentType); isVarArgs = varArgsParameterTypeAsPrimitive.isAssignableFrom(lastArgumentTypeAsPrimitive); } } return isVarArgs && checkArgumentTypesMatchParameterTypes(isVarArgs, parameterTypes, arguments); } /** * Get the type of an object and convert it to primitive if the type has a * primitive counter-part. E.g. if object is an instance of * {@code java.lang.Integer} this method will return * {@code int.class}. * * @param object The object whose type to get. * @return the type as primitive if wrapped */ static Class getTypeAsPrimitiveIfWrapped(Object object) { if (object != null) { final Class firstArgumentType = getType(object); final Class firstArgumentTypeAsPrimitive = PrimitiveWrapper.hasPrimitiveCounterPart(firstArgumentType) ? PrimitiveWrapper .getPrimitiveFromWrapperType(firstArgumentType) : firstArgumentType; return firstArgumentTypeAsPrimitive; } return null; } /** * Set the values of multiple instance fields defined in a context using * reflection. The values in the context will be assigned to values on the * {@code instance}. This method will traverse the class hierarchy when * searching for the fields. Example usage: * * Given: * *
     * public class MyContext {
     * 	private String myString = "myString";
     * 	protected int myInt = 9;
     * }
     *
     * public class MyInstance {
     * 	private String myInstanceString;
     * 	private int myInstanceInt;
     *
     * }
     * 
* * then * *
     * Whitebox.setInternalStateFromContext(new MyInstance(), new MyContext());
     * 
* * will set the instance variables of {@code myInstance} to the values * specified in {@code MyContext}. * * @param object the object * @param context The context where the fields are defined. * @param additionalContexts Optionally more additional contexts. */ public static void setInternalStateFromContext(Object object, Object context, Object[] additionalContexts) { setInternalStateFromContext(object, context, FieldMatchingStrategy.MATCHING); if (additionalContexts != null && additionalContexts.length > 0) { for (Object additionContext : additionalContexts) { setInternalStateFromContext(object, additionContext, FieldMatchingStrategy.MATCHING); } } } public static void setInternalStateFromContext(Object object, Object context, FieldMatchingStrategy strategy) { if (isClass(context)) { copyState(object, getType(context), strategy); } else { copyState(object, context, strategy); } } /** * Set the values of multiple static fields defined in a context using * reflection. The values in the context will be assigned to values on the * {@code classOrInstance}. This method will traverse the class * hierarchy when searching for the fields. Example usage: * * Given: * *
     * public class MyContext {
     * 	private static String myString = "myString";
     * 	protected static int myInt = 9;
     * }
     *
     * public class MyInstance {
     * 	private static String myInstanceString;
     * 	private static int myInstanceInt;
     *
     * }
     * 
* * then * *
     * Whitebox.setInternalStateFromContext(MyInstance.class, MyContext.class);
     * 
* * will set the static variables of {@code MyInstance} to the values * specified in {@code MyContext}. * * @param object the object * @param context The context where the fields are defined. * @param additionalContexts Optionally more additional contexts. */ public static void setInternalStateFromContext(Object object, Class context, Class[] additionalContexts) { setInternalStateFromContext(object, context, FieldMatchingStrategy.MATCHING); if (additionalContexts != null && additionalContexts.length > 0) { for (Class additionContext : additionalContexts) { setInternalStateFromContext(object, additionContext, FieldMatchingStrategy.MATCHING); } } } /** * Copy state. * * @param object the object * @param context the context * @param strategy The field matching strategy. */ static void copyState(Object object, Object context, FieldMatchingStrategy strategy) { if (object == null) { throw new IllegalArgumentException("object to set state cannot be null"); } else if (context == null) { throw new IllegalArgumentException("context cannot be null"); } else if (strategy == null) { throw new IllegalArgumentException("strategy cannot be null"); } Set allFields = isClass(context) ? getAllStaticFields(getType(context)) : getAllInstanceFields(context); for (Field field : allFields) { try { final boolean isStaticField = Modifier.isStatic(field.getModifiers()); setInternalState(isStaticField ? getType(object) : object, field.getType(), field.get(context)); } catch (FieldNotFoundException e) { if (strategy == FieldMatchingStrategy.STRICT) { throw e; } } catch (IllegalAccessException e) { // Should never happen throw new RuntimeException( "Internal Error: Failed to get the field value in method setInternalStateFromContext.", e); } } } /** * Assert object in get internal state is not null. * * @param object the object */ private static void assertObjectInGetInternalStateIsNotNull(Object object) { if (object == null) { throw new IllegalArgumentException("The object containing the field cannot be null"); } } /** * Convert parameter types to primitive. * * @param parameterTypes the parameter types * @return the class[] */ private static Class[] convertParameterTypesToPrimitive(Class[] parameterTypes) { Class[] converted = new Class[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { Class primitiveWrapperType = PrimitiveWrapper.getPrimitiveFromWrapperType(parameterTypes[i]); if (primitiveWrapperType == null) { converted[i] = parameterTypes[i]; } else { converted[i] = primitiveWrapperType; } } return converted; } public static void copyToMock(T from, T mock) { copy(from, mock, from.getClass()); } public static void copyToRealObject(T from, T to) { copy(from, to, from.getClass()); } private static void copy(T from, T to, Class fromClazz) { while (fromClazz != Object.class) { copyValues(from, to, fromClazz); fromClazz = fromClazz.getSuperclass(); } } private static void copyValues(T from, T mock, Class classFrom) { Field[] fields = classFrom.getDeclaredFields(); for (Field field : fields) { // ignore static fields if (Modifier.isStatic(field.getModifiers())) { continue; } boolean accessible = field.isAccessible(); try { field.setAccessible(true); copyValue(from, mock, field); } catch (Exception ignored) { //Ignore - be lenient - if some field cannot be copied then let's be it } finally { field.setAccessible(accessible); } } } private static void copyValue(T from, T to, Field field) throws IllegalAccessException { Object value = field.get(from); field.set(to, value); } } ================================================ FILE: powermock-reflect/src/main/java/org/powermock/reflect/internal/comparator/ComparatorFactory.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.reflect.internal.comparator; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.Comparator; /** * This comparator factory is used to create Comparators for * {@link org.powermock.reflect.Whitebox} which are used to find best candidates * for constructor and method invocation. * @see org.powermock.reflect.internal.WhiteboxImpl#getBestMethodCandidate(Class, String, Class[], boolean) * @see org.powermock.reflect.internal.WhiteboxImpl#getBestCandidateConstructor(Class, Class[], Object[]) */ public class ComparatorFactory { private ComparatorFactory() { } public static Comparator createConstructorComparator(){ return new ConstructorComparator(new ParametersComparator()); } public static Comparator createMethodComparator(){ return new MethodComparator(new ParametersComparator()); } public static class ConstructorComparator implements Comparator { private final ParametersComparator parametersComparator; private ConstructorComparator(ParametersComparator parametersComparator) { this.parametersComparator = parametersComparator; } @Override public int compare(Constructor constructor1, Constructor constructor2) { final Class[] parameters1 = constructor1.getParameterTypes(); final Class[] parameters2 = constructor2.getParameterTypes(); return parametersComparator.compare(parameters1,parameters2); } } /** * */ public static class MethodComparator implements Comparator { private final ParametersComparator parametersComparator; private MethodComparator(ParametersComparator parametersComparator) { this.parametersComparator = parametersComparator; } @Override public int compare(Method m1, Method m2) { final Class[] typesMethod1 = m1.getParameterTypes(); final Class[] typesMethod2 = m2.getParameterTypes(); return parametersComparator.compare(typesMethod1, typesMethod2); } } private static class ParametersComparator implements Comparator{ @Override public int compare(Class[] params1, Class[] params2) { final int size = params1.length; for (int i = 0; i < size; i++) { Class type1 = params1[i]; Class type2 = params2[i]; if (!type1.equals(type2)) { if (type1.isAssignableFrom(type2)) { if (!type1.isArray() && type2.isArray()) { return -1; } return 1; } else { if (type1.isArray() && !type2.isArray()) { return 1; } return -1; } } } return 0; } } } ================================================ FILE: powermock-reflect/src/main/java/org/powermock/reflect/internal/matcherstrategies/AllFieldsMatcherStrategy.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.reflect.internal.matcherstrategies; import org.powermock.reflect.exceptions.FieldNotFoundException; import java.lang.reflect.Field; public class AllFieldsMatcherStrategy extends FieldMatcherStrategy { @Override public boolean matches(Field field) { return true; } @Override public void notFound(Class type, boolean isInstanceField) throws FieldNotFoundException { throw new FieldNotFoundException(String.format("No %s fields were declared in %s.", isInstanceField ? "instance" : "static", type.getName())); } } ================================================ FILE: powermock-reflect/src/main/java/org/powermock/reflect/internal/matcherstrategies/AssignableFromFieldTypeMatcherStrategy.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.reflect.internal.matcherstrategies; import org.powermock.reflect.exceptions.FieldNotFoundException; import org.powermock.reflect.internal.primitivesupport.PrimitiveWrapper; import java.lang.reflect.Field; public class AssignableFromFieldTypeMatcherStrategy extends FieldTypeMatcherStrategy { private final Class primitiveCounterpart; public AssignableFromFieldTypeMatcherStrategy(Class fieldType) { super(fieldType); primitiveCounterpart = PrimitiveWrapper.getPrimitiveFromWrapperType(expectedFieldType); } @Override public boolean matches(Field field) { Class actualFieldType = field.getType(); return actualFieldType.isAssignableFrom(expectedFieldType) || (primitiveCounterpart != null && actualFieldType.isAssignableFrom(primitiveCounterpart)); } @Override public void notFound(Class type, boolean isInstanceField) throws FieldNotFoundException { throw new FieldNotFoundException(String.format("No %s field assignable from \"%s\" could be found in the class hierarchy of %s.", isInstanceField ? "instance" : "static", expectedFieldType.getName(), type.getName())); } @Override public String toString() { return "type " + (primitiveCounterpart == null ? expectedFieldType.getName() : primitiveCounterpart.getName()); } } ================================================ FILE: powermock-reflect/src/main/java/org/powermock/reflect/internal/matcherstrategies/AssignableToFieldTypeMatcherStrategy.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.reflect.internal.matcherstrategies; import java.lang.reflect.Field; public class AssignableToFieldTypeMatcherStrategy extends FieldTypeMatcherStrategy { public AssignableToFieldTypeMatcherStrategy(Class fieldType) { super(fieldType); } @Override public boolean matches(Field field) { return expectedFieldType.isAssignableFrom(field.getType()); } } ================================================ FILE: powermock-reflect/src/main/java/org/powermock/reflect/internal/matcherstrategies/FieldAnnotationMatcherStrategy.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.reflect.internal.matcherstrategies; import org.powermock.reflect.exceptions.FieldNotFoundException; import java.lang.annotation.Annotation; import java.lang.reflect.Field; public class FieldAnnotationMatcherStrategy extends FieldMatcherStrategy { final Class[] annotations; public FieldAnnotationMatcherStrategy(Class[] annotations) { if (annotations == null || annotations.length == 0) { throw new IllegalArgumentException("You must specify atleast one annotation."); } this.annotations = annotations; } @Override public boolean matches(Field field) { for (Class annotation : annotations) { if (field.isAnnotationPresent(annotation)) { return true; } } return false; } @Override public void notFound(Class type, boolean isInstanceField) throws FieldNotFoundException { throw new FieldNotFoundException("No field that has any of the annotation types \"" + getAnnotationNames() + "\" could be found in the class hierarchy of " + type.getName() + "."); } @Override public String toString() { return "annotations " + getAnnotationNames(); } private String getAnnotationNames() { final StringBuilder builder = new StringBuilder(); for (int i = 0; i < annotations.length; i++) { builder.append(annotations[i].getName()); if (i != annotations.length - 1) { builder.append(", "); } } return builder.toString(); } } ================================================ FILE: powermock-reflect/src/main/java/org/powermock/reflect/internal/matcherstrategies/FieldMatcherStrategy.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.reflect.internal.matcherstrategies; import org.powermock.reflect.exceptions.FieldNotFoundException; import java.lang.reflect.Field; /** * Class that should be implemented by field matching strategies. */ public abstract class FieldMatcherStrategy { /** * A field matcher that checks if a field matches a given criteria. * * @param field * The field to check whether it matches the strategy or not. * @return {@code true} if this field matches the strategy, * {@code false} otherwise. * */ public abstract boolean matches(Field field); /** * Throws an {@link FieldNotFoundException} if the strategy criteria could * not be found. * * @param type * The type of the object that was not found. * @param isInstanceField * {@code true} if the field that was looked after was an * instance field or {@code false} if it was a static field. */ public abstract void notFound(Class type, boolean isInstanceField) throws FieldNotFoundException; } ================================================ FILE: powermock-reflect/src/main/java/org/powermock/reflect/internal/matcherstrategies/FieldNameMatcherStrategy.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.reflect.internal.matcherstrategies; import org.powermock.reflect.exceptions.FieldNotFoundException; import java.lang.reflect.Field; public class FieldNameMatcherStrategy extends FieldMatcherStrategy { private final String fieldName; public FieldNameMatcherStrategy(String fieldName) { if (fieldName == null || fieldName.equals("") || fieldName.startsWith(" ")) { throw new IllegalArgumentException("field name cannot be null."); } this.fieldName = fieldName; } @Override public boolean matches(Field field) { return fieldName.equals(field.getName()); } @Override public void notFound(Class type, boolean isInstanceField) throws FieldNotFoundException { throw new FieldNotFoundException(String.format("No %s field named \"%s\" could be found in the class hierarchy of %s.", isInstanceField ? "instance" : "static", fieldName, type.getName())); } @Override public String toString() { return "fieldName " + fieldName; } } ================================================ FILE: powermock-reflect/src/main/java/org/powermock/reflect/internal/matcherstrategies/FieldTypeMatcherStrategy.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.reflect.internal.matcherstrategies; import org.powermock.reflect.exceptions.FieldNotFoundException; import java.lang.reflect.Field; public class FieldTypeMatcherStrategy extends FieldMatcherStrategy { final Class expectedFieldType; public FieldTypeMatcherStrategy(Class fieldType) { if (fieldType == null) { throw new IllegalArgumentException("field type cannot be null."); } this.expectedFieldType = fieldType; } @Override public boolean matches(Field field) { return expectedFieldType.equals(field.getType()); } @Override public void notFound(Class type, boolean isInstanceField) throws FieldNotFoundException { throw new FieldNotFoundException(String.format("No %s field of type \"%s\" could be found in the class hierarchy of %s.", isInstanceField ? "instance" : "static", expectedFieldType.getName(), type.getName())); } @Override public String toString() { return "type " + expectedFieldType.getName(); } } ================================================ FILE: powermock-reflect/src/main/java/org/powermock/reflect/internal/primitivesupport/BoxedWrapper.java ================================================ /* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.reflect.internal.primitivesupport; import java.util.HashMap; import java.util.Map; /** * The purpose of the Primitive Wrapper is to provide methods that deals with * translating wrapper types to its related primitive type. */ public class BoxedWrapper { private static final Map, Class> boxedWrapper = new HashMap, Class>(); static { boxedWrapper.put(int.class, Integer.class); boxedWrapper.put(long.class, Long.class); boxedWrapper.put(float.class, Float.class); boxedWrapper.put(double.class, Double.class); boxedWrapper.put(boolean.class, Boolean.class); boxedWrapper.put(byte.class, Byte.class); boxedWrapper.put(short.class, Short.class); boxedWrapper.put(char.class, Character.class); } /** * Get the wrapped counter part from a primitive type. For example: *

* * {@code getBoxedFromPrimitiveType(int.class)} will return * {@code Integer.class}. * * * @param primitiveType * The primitive type to convert to its wrapper counter part. * @return The boxed counter part or {@code null} if the class did * not have a boxed counter part. * */ public static Class getBoxedFromPrimitiveType(Class primitiveType) { return boxedWrapper.get(primitiveType); } /** * Returns {@code true} if {@code type} has a primitive * counter-part. E.g. if {@code type} if {@code Integer} then this * method will return {@code true}. * * @param type * The type to check whether or not it has a primitive * counter-part. * @return {@code true} if this type has a primitive counter-part. */ public static boolean hasBoxedCounterPart(Class type) { return boxedWrapper.containsKey(type); } } ================================================ FILE: powermock-reflect/src/main/java/org/powermock/reflect/internal/primitivesupport/PrimitiveWrapper.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.reflect.internal.primitivesupport; import java.util.HashMap; import java.util.Map; /** * The purpose of the Primitive Wrapper is to provide methods that deals with * translating wrapper types to its related primitive type. */ public class PrimitiveWrapper { private static final Map, Class> primitiveWrapper = new HashMap, Class>(); static { primitiveWrapper.put(Integer.class, int.class); primitiveWrapper.put(Long.class, long.class); primitiveWrapper.put(Float.class, float.class); primitiveWrapper.put(Double.class, double.class); primitiveWrapper.put(Boolean.class, boolean.class); primitiveWrapper.put(Byte.class, byte.class); primitiveWrapper.put(Short.class, short.class); primitiveWrapper.put(Character.class, char.class); } /** * Convert all wrapper types in {@code types} to their primitive * counter parts. * * @param types * The array of types that should be converted. * @return A new array where all wrapped types have been converted to their * primitive counter part. */ public static Class[] toPrimitiveType(Class[] types) { if (types == null) { throw new IllegalArgumentException("types cannot be null"); } Class[] convertedTypes = new Class[types.length]; for (int i = 0; i < types.length; i++) { final Class originalType = types[i]; Class primitiveType = primitiveWrapper.get(originalType); if (primitiveType == null) { convertedTypes[i] = originalType; } else { convertedTypes[i] = primitiveType; } } return convertedTypes; } /** * Get the primitive counter part from a wrapped type. For example: *

* * {@code getPrimitiveFromWrapperType(Integer.class)} will return * {@code int.class}. * * * @param wrapperType * The wrapper type to convert to its primitive counter part. * @return The primitive counter part or {@code null} if the class did * not have a primitive counter part. * */ public static Class getPrimitiveFromWrapperType(Class wrapperType) { return primitiveWrapper.get(wrapperType); } /** * Returns {@code true} if {@code type} has a primitive * counter-part. E.g. if {@code type} if {@code Integer} then this * method will return {@code true}. * * @param type * The type to check whether or not it has a primitive * counter-part. * @return {@code true} if this type has a primitive counter-part. */ public static boolean hasPrimitiveCounterPart(Class type) { return primitiveWrapper.containsKey(type); } } ================================================ FILE: powermock-reflect/src/main/java/org/powermock/reflect/internal/proxy/ProxyFrameworks.java ================================================ package org.powermock.reflect.internal.proxy; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class ProxyFrameworks { private static final UnproxiedTypeFactory UNPROXIED_TYPE_FACTORY = new UnproxiedTypeFactory(); public UnproxiedType getUnproxiedType(Class type) { if (type == null){ return null; } if (isJavaProxy(type)){ return UNPROXIED_TYPE_FACTORY.createFromInterfaces(type.getInterfaces()); } if (isCglibProxyClass(type)) { return UNPROXIED_TYPE_FACTORY.createFromSuperclassAndInterfaces(type.getSuperclass(), type.getInterfaces()); } return UNPROXIED_TYPE_FACTORY.createFromType(type); } public UnproxiedType getUnproxiedType(Object o) { if (o == null) { return null; } return getUnproxiedType(o.getClass()); } private boolean isJavaProxy(Class clazz) { return (clazz != null && Proxy.isProxyClass(clazz)); } private boolean isCglibProxyClass(Class clazz) { if (clazz == null){ return false; } Method[] methods = clazz.getDeclaredMethods(); for(Method m: methods){ if(isCglibCallbackMethod(m)) { return true; } } return false; } private boolean isCglibCallbackMethod(Method m) { return "CGLIB$SET_THREAD_CALLBACKS".equals(m.getName()) && m.getParameterTypes().length == 1; } } ================================================ FILE: powermock-reflect/src/main/java/org/powermock/reflect/internal/proxy/UnproxiedType.java ================================================ package org.powermock.reflect.internal.proxy; public interface UnproxiedType { Class getOriginalType(); Class[] getInterfaces(); } ================================================ FILE: powermock-reflect/src/main/java/org/powermock/reflect/internal/proxy/UnproxiedTypeFactory.java ================================================ package org.powermock.reflect.internal.proxy; import java.util.ArrayList; import java.util.List; class UnproxiedTypeFactory { private static final String[] RESTRICTED_INTERFACES = { "cglib.proxy.Factory" }; UnproxiedType createFromInterfaces(Class[] interfaces) { Class[] filteredInterfaces = filterInterfaces(interfaces); if (filteredInterfaces.length == 0){ return new UnproxiedTypeImpl(Object.class); } if (filteredInterfaces.length == 1){ return new UnproxiedTypeImpl(filteredInterfaces[0]); } return new UnproxiedTypeImpl(filteredInterfaces); } UnproxiedType createFromSuperclassAndInterfaces(Class superclass, Class[] interfaces) { if (Object.class.equals(superclass)){ return createFromInterfaces(interfaces); } Class[] filteredInterfaces = filterInterfaces(interfaces); return new UnproxiedTypeImpl(superclass, filteredInterfaces); } UnproxiedType createFromType(Class type) { return new UnproxiedTypeImpl(type); } private Class[] filterInterfaces(Class[] interfaces) { List> filtered = new ArrayList>(); for (Class anInterface : interfaces) { if(!isMockFrameworkInterface(anInterface)){ filtered.add(anInterface); } } return filtered.toArray(new Class[filtered.size()]); } private boolean isMockFrameworkInterface(Class anInterface) { String name = anInterface.getName(); for (String restrictedInterface : RESTRICTED_INTERFACES) { if (name.contains(restrictedInterface)){ return true; } } return false; } private static class UnproxiedTypeImpl implements UnproxiedType { private final Class type; private final Class[] interfaces; private UnproxiedTypeImpl(Class type) { this.type = type; this.interfaces = new Class[0]; } private UnproxiedTypeImpl(Class[] interfaces) { this.type = null; this.interfaces = interfaces; } private UnproxiedTypeImpl(Class type, Class[] interfaces) { this.type = type; this.interfaces = interfaces; } @Override public Class getOriginalType() { return type; } @Override public Class[] getInterfaces() { return interfaces; } } } ================================================ FILE: powermock-reflect/src/main/java/org/powermock/reflect/matching/FieldMatchingStrategy.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.reflect.matching; /** * Defines strategies for field matching. */ public enum FieldMatchingStrategy { /** * All fields in the context must match exactly the fields in the * target instance or class. This means that an exception will be thrown * unless all fields in the context are found in the target. */ STRICT, /** * All fields in the context are copied to the target instance or class. The * context may contain additional fields not present in the target. Only * fields that may be copied from the context to the target are taken into * consideration. An exception will not be thrown if a field exists in the * context but is non-existent in the target. */ MATCHING } ================================================ FILE: powermock-reflect/src/test/java/org/powermock/reflect/WhiteBoxGetFieldTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.reflect; import org.junit.Test; import org.powermock.reflect.internal.WhiteboxImpl; import java.lang.reflect.Field; import static org.assertj.core.api.Java6Assertions.assertThat; /** * A test case to demonstrate an issue * {@link org.powermock.reflect.internal.WhiteboxImpl#getField(Class, String)}. * As the class hierarchy for the given Class is ascended, if the field is not * found in the parent class, the interfaces are checked before the grandparent * class. The problem is that the getSuperclass() method will always return null * for the Class representing the interface. The current implementation of * WhiteboxImpl blindly adds this null to the {@code examine} LinkedList. * * @author Ben Chatelain */ public class WhiteBoxGetFieldTest { interface SomeInterface { } class GrandParentClass { @SuppressWarnings("unused") private String fieldA; } class ParentClass extends GrandParentClass { } class ClassUnderTest extends ParentClass implements SomeInterface { @SuppressWarnings("unused") private String fieldB; } /** * Verifies that issue * 149 has been resolved. */ @Test public void testGetField() { Field fieldA = WhiteboxImpl.getField(ClassUnderTest.class, "fieldA"); assertThat(fieldA).isNotNull(); } } ================================================ FILE: powermock-reflect/src/test/java/org/powermock/reflect/WhiteBoxTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.reflect; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.powermock.reflect.context.ClassFieldsNotInTargetContext; import org.powermock.reflect.context.InstanceFieldsNotInTargetContext; import org.powermock.reflect.context.MyContext; import org.powermock.reflect.context.MyIntContext; import org.powermock.reflect.context.MyStringContext; import org.powermock.reflect.context.OneInstanceAndOneStaticFieldOfSameTypeContext; import org.powermock.reflect.exceptions.FieldNotFoundException; import org.powermock.reflect.exceptions.MethodNotFoundException; import org.powermock.reflect.exceptions.TooManyFieldsFoundException; import org.powermock.reflect.exceptions.TooManyMethodsFoundException; import org.powermock.reflect.internal.WhiteboxImpl; import org.powermock.reflect.matching.FieldMatchingStrategy; import org.powermock.reflect.testclasses.AbstractClass; import org.powermock.reflect.testclasses.AnInterface; import org.powermock.reflect.testclasses.Child; import org.powermock.reflect.testclasses.ClassWithAMethod; import org.powermock.reflect.testclasses.ClassWithChildThatHasInternalState; import org.powermock.reflect.testclasses.ClassWithInterfaceConstructors; import org.powermock.reflect.testclasses.ClassWithInterfaceConstructors.ConstructorInterface; import org.powermock.reflect.testclasses.ClassWithInterfaceConstructors.ConstructorInterfaceImpl; import org.powermock.reflect.testclasses.ClassWithInternalState; import org.powermock.reflect.testclasses.ClassWithList; import org.powermock.reflect.testclasses.ClassWithObjectConstructors; import org.powermock.reflect.testclasses.ClassWithOverloadedConstructors; import org.powermock.reflect.testclasses.ClassWithOverloadedMethods; import org.powermock.reflect.testclasses.ClassWithOverriddenMethod; import org.powermock.reflect.testclasses.ClassWithPrimitiveConstructors; import org.powermock.reflect.testclasses.ClassWithPrivateMethods; import org.powermock.reflect.testclasses.ClassWithSerializableState; import org.powermock.reflect.testclasses.ClassWithSeveralMethodsWithSameName; import org.powermock.reflect.testclasses.ClassWithSeveralMethodsWithSameNameOneWithoutParameters; import org.powermock.reflect.testclasses.ClassWithSimpleInternalState; import org.powermock.reflect.testclasses.ClassWithStaticAndInstanceInternalStateOfSameType; import org.powermock.reflect.testclasses.ClassWithStaticMethod; import org.powermock.reflect.testclasses.ClassWithUniquePrivateMethods; import org.powermock.reflect.testclasses.ClassWithVarArgsConstructor; import org.powermock.reflect.testclasses.ClassWithVarArgsConstructor2; import java.io.InputStream; import java.io.Serializable; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.sql.Connection; import java.util.Set; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * Tests the WhiteBox's functionality. */ public class WhiteBoxTest { @Rule public ExpectedException expectedException = ExpectedException.none(); @Test public void testFindMethod_classContainingMethodWithNoParameters() throws Exception { Method expected = ClassWithSeveralMethodsWithSameNameOneWithoutParameters.class.getMethod("getDouble"); Method actual = WhiteboxImpl.findMethodOrThrowException( ClassWithSeveralMethodsWithSameNameOneWithoutParameters.class, "getDouble"); assertEquals(expected, actual); } @Test public void testFindMethod_classContainingOnlyMethodsWithParameters() throws Exception { try { WhiteboxImpl.findMethodOrThrowException(ClassWithSeveralMethodsWithSameName.class, "getDouble"); fail("Should throw runtime exception!"); } catch (RuntimeException e) { assertTrue("Error message did not match", e.getMessage().contains( "Several matching methods found, please specify the argument parameter types")); } } @Test public void testFindMethod_noMethodFound() throws Exception { try { WhiteboxImpl.findMethodOrThrowException(ClassWithSeveralMethodsWithSameName.class, "getDouble2"); fail("Should throw runtime exception!"); } catch (RuntimeException e) { assertEquals("Error message did not match", "No method found with name 'getDouble2' with parameter types: [ ] in class " + ClassWithSeveralMethodsWithSameName.class.getName() + ".", e.getMessage()); } } @Test public void testGetInternalState_object() throws Exception { ClassWithInternalState tested = new ClassWithInternalState(); tested.increaseInteralState(); Object internalState = Whitebox.getInternalState(tested, "internalState"); assertTrue("InternalState should be instanceof Integer", internalState instanceof Integer); assertEquals(1, internalState); } @SuppressWarnings("deprecation") @Test public void testGetInternalState_parmaterizedType() throws Exception { ClassWithInternalState tested = new ClassWithInternalState(); tested.increaseInteralState(); int internalState = Whitebox.getInternalState(tested, "internalState", tested.getClass(), int.class); assertEquals(1, internalState); } @Test public void testSetInternalState() throws Exception { ClassWithInternalState tested = new ClassWithInternalState(); tested.increaseInteralState(); Whitebox.setInternalState(tested, "anotherInternalState", 2); assertEquals(2, tested.getAnotherInternalState()); } @Test public void testSetInternalStateWithMultipleValues() throws Exception { ClassWithInternalState tested = new ClassWithInternalState(); final ClassWithPrivateMethods classWithPrivateMethods = new ClassWithPrivateMethods(); final String stringState = "someStringState"; Whitebox.setInternalState(tested, classWithPrivateMethods, stringState); assertEquals(stringState, Whitebox.getInternalState(tested, String.class)); assertSame(classWithPrivateMethods, Whitebox.getInternalState(tested, ClassWithPrivateMethods.class)); } @Test public void testSetInternalState_superClass() throws Exception { ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState(); tested.increaseInteralState(); Whitebox.setInternalState(tested, "anotherInternalState", 2, ClassWithInternalState.class); assertEquals(2, tested.getAnotherInternalState()); } @Test public void testGetInternalState_superClass_object() throws Exception { ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState(); Object internalState = Whitebox.getInternalState(tested, "internalState", ClassWithInternalState.class); assertEquals(0, internalState); } @SuppressWarnings("deprecation") @Test public void testGetInternalState_superClass_parameterized() throws Exception { ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState(); int internalState = Whitebox.getInternalState(tested, "internalState", ClassWithInternalState.class, int.class); assertEquals(0, internalState); } @Test public void testInvokePrivateMethod_primtiveType() throws Exception { assertTrue(Whitebox.invokeMethod(new ClassWithPrivateMethods(), "primitiveMethod", 8.2)); } @Test public void testInvokePrivateMethod_primtiveType_withoutSpecifyingMethodName() throws Exception { assertTrue((Boolean) Whitebox.invokeMethod(new ClassWithUniquePrivateMethods(), 8.2d, 8.4d)); } /** * This test actually invokes the finalize method of * java.lang.Object because we supply no method name and no * arguments. finalize is thus the first method found and it'll * be executed. * * @throws Exception */ @Test @Ignore("Invokes different methods on PC and MAC (hashCode on mac)") public void testInvokePrivateMethod_withoutSpecifyingMethodName_noArguments() throws Exception { assertNull(Whitebox.invokeMethod(new ClassWithUniquePrivateMethods())); } @Test public void testInvokePrivateMethod_withoutSpecifyingMethodName_assertThatNullWorks() throws Exception { assertTrue(Whitebox.invokeMethod(new ClassWithUniquePrivateMethods(), 8.2d, 8.3d, null) instanceof Object); } /** * This test should actually fail since equals takes an Object and we pass * in a primitive wrapped as a Double. Thus PowerMock cannot determine * whether to invoke the single argument method defined in * {@link ClassWithUniquePrivateMethods} or the * {@link Object#equals(Object)} method because we could potentially invoke * equals with a Double. */ @Test(expected = TooManyMethodsFoundException.class) public void testInvokePrivateMethod_withoutSpecifyingMethodName_onlyOneArgument() throws Exception { Whitebox.invokeMethod(new ClassWithUniquePrivateMethods(), 8.2d); } @Test(expected = TooManyMethodsFoundException.class) public void testInvokeStaticPrivateMethod_withoutSpecifyingMethodName_onlyOneArgument() throws Exception { assertTrue((Boolean) Whitebox.invokeMethod(ClassWithUniquePrivateMethods.class, 8.2d)); } @Test public void testInvokePrivateMethod_primtiveType_Wrapped() throws Exception { assertTrue((Boolean) Whitebox.invokeMethod(new ClassWithPrivateMethods(), "primitiveMethod", new Double(8.2))); } @Test public void testInvokePrivateMethod_wrappedType() throws Exception { assertTrue((Boolean) Whitebox.invokeMethod(new ClassWithPrivateMethods(), "wrappedMethod", new Double(8.2))); } @Test public void testInvokePrivateMethod_wrappedType_primitive() throws Exception { assertTrue((Boolean) Whitebox.invokeMethod(new ClassWithPrivateMethods(), "wrappedMethod", 8.2)); } @Test public void testMethodWithPrimitiveIntAndString_primitive() throws Exception { assertEquals("My int value is: " + 8, Whitebox.invokeMethod(new ClassWithPrivateMethods(), "methodWithPrimitiveIntAndString", 8, "My int value is: ")); } @Test public void testMethodWithPrimitiveIntAndString_Wrapped() throws Exception { assertEquals("My int value is: " + 8, Whitebox.invokeMethod(new ClassWithPrivateMethods(), "methodWithPrimitiveIntAndString", Integer.valueOf(8), "My int value is: ")); } @Test public void testMethodWithPrimitiveAndWrappedInt_primtive_wrapped() throws Exception { assertEquals(17, Whitebox.invokeMethod(new ClassWithPrivateMethods(), "methodWithPrimitiveAndWrappedInt", new Class[]{int.class, Integer.class}, 9, Integer.valueOf(8))); } @Test public void testStaticState() { int expected = 123; Whitebox.setInternalState(ClassWithInternalState.class, "staticState", expected); assertEquals(expected, ClassWithInternalState.getStaticState()); assertEquals(expected, Whitebox.getInternalState(ClassWithInternalState.class, "staticState")); } @Test public void testStaticFinalPrimitiveState() { Whitebox.setInternalState(ClassWithInternalState.class, "staticFinalIntState", 123); assertEquals(123, Whitebox.getInternalState(ClassWithInternalState.class, "staticFinalIntState")); } @Test public void testStaticFinalStringState() throws NoSuchFieldException { Whitebox.setInternalState(ClassWithInternalState.class, "staticFinalStringState", "Brand new string"); assertEquals("Brand new string", Whitebox.getInternalState(ClassWithInternalState.class, "staticFinalStringState")); } @Test public void testStaticFinalObject() throws NoSuchFieldException { int modifiersBeforeSet = ClassWithInternalState.class.getDeclaredField("staticFinalIntegerState").getModifiers(); Integer newValue = ClassWithInternalState.getStaticFinalIntegerState() + 1; Whitebox.setInternalState(ClassWithInternalState.class, "staticFinalIntegerState", newValue); int modifiersAfterSet = ClassWithInternalState.class.getDeclaredField("staticFinalIntegerState").getModifiers(); assertEquals(newValue, ClassWithInternalState.getStaticFinalIntegerState()); assertEquals(modifiersBeforeSet, modifiersAfterSet); } /** * Verifies that the http://code.google.com/p/powermock/issues/detail?id=6 * is fixed. */ @Test(expected = IllegalArgumentException.class) public void testInvokeMethodWithNullParameter() throws Exception { Whitebox.invokeMethod(null, "method"); } @Test(expected = IllegalArgumentException.class) public void testInvokeConstructorWithNullParameter() throws Exception { Whitebox.invokeConstructor(null, "constructor"); } @Test(expected = IllegalArgumentException.class) public void testGetInternalWithNullParameter() throws Exception { Whitebox.getInternalState(null, "state"); } @Test(expected = IllegalArgumentException.class) public void testSetInternalWithNullParameter() throws Exception { Whitebox.setInternalState(null, "state", new Object()); } @Test public void testInstantiateVarArgsOnlyConstructor() throws Exception { final String argument1 = "argument1"; final String argument2 = "argument2"; ClassWithVarArgsConstructor instance = Whitebox.invokeConstructor(ClassWithVarArgsConstructor.class, argument1, argument2); String[] strings = instance.getStrings(); assertEquals(2, strings.length); assertEquals(argument1, strings[0]); assertEquals(argument2, strings[1]); } @Test public void testInstantiateVarArgsOnlyConstructor_noArguments() throws Exception { ClassWithVarArgsConstructor instance = Whitebox.invokeConstructor(ClassWithVarArgsConstructor.class); String[] strings = instance.getStrings(); assertEquals(0, strings.length); } @Test public void testInvokeVarArgsMethod_multipleValues() throws Exception { ClassWithPrivateMethods tested = new ClassWithPrivateMethods(); assertEquals(6, Whitebox.invokeMethod(tested, "varArgsMethod", 1, 2, 3)); } @Test public void testInvokeVarArgsMethod_noArguments() throws Exception { ClassWithPrivateMethods tested = new ClassWithPrivateMethods(); assertEquals(0, Whitebox.invokeMethod(tested, "varArgsMethod")); } @Test public void testInvokeVarArgsMethod_oneArgument() throws Exception { ClassWithPrivateMethods tested = new ClassWithPrivateMethods(); assertEquals(4, Whitebox.invokeMethod(tested, "varArgsMethod", 2)); } @Test public void testInvokeVarArgsMethod_invokeVarArgsWithOneArgument() throws Exception { ClassWithPrivateMethods tested = new ClassWithPrivateMethods(); assertEquals(1, Whitebox.invokeMethod(tested, "varArgsMethod", new Class[]{int[].class}, 1)); } @Test public void testInvokePrivateMethodWithASubTypeOfTheArgumentType() throws Exception { ClassWithPrivateMethods tested = new ClassWithPrivateMethods(); ClassWithChildThatHasInternalState argument = new ClassWithChildThatHasInternalState(); assertSame(argument, Whitebox.invokeMethod(tested, "methodWithObjectArgument", argument)); } @Test public void testInvokePrivateMethodWithAClassArgument() throws Exception { ClassWithPrivateMethods tested = new ClassWithPrivateMethods(); assertEquals(ClassWithChildThatHasInternalState.class, Whitebox.invokeMethod(tested, "methodWithClassArgument", ClassWithChildThatHasInternalState.class)); } @Test public void testSetInternalStateInChildClassWithoutSpecifyingTheChildClass() throws Exception { final int value = 22; final String fieldName = "internalState"; ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState() { }; Whitebox.setInternalState(tested, fieldName, value); assertEquals(value, Whitebox.getInternalState(tested, fieldName)); } @Test public void testSetInternalStateInClassAndMakeSureThatTheChildClassIsNotAffectedEvenThoughItHasAFieldWithTheSameName() throws Exception { final int value = 22; final String fieldName = "anotherInternalState"; ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState() { }; Whitebox.setInternalState(tested, fieldName, value); assertEquals(value, Whitebox.getInternalState(tested, fieldName)); assertEquals(-1, Whitebox.getInternalState(tested, fieldName, ClassWithInternalState.class)); } @Test(expected = IllegalArgumentException.class) public void testSetInternalStateWithInvalidArgumentType() throws Exception { final int value = 22; final String fieldName = "internalState"; ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState() { }; Whitebox.setInternalState(tested, fieldName, new Object()); assertEquals(value, Whitebox.getInternalState(tested, fieldName)); } @Test(expected = IllegalArgumentException.class) public void testSetInternalStateWithNull() throws Exception { final int value = 22; final String fieldName = "internalState"; ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState() { }; Whitebox.setInternalState(tested, fieldName, (Object) null); assertEquals(value, Whitebox.getInternalState(tested, fieldName)); } @Test public void testSetAndGetInternalStateBasedOnFieldType() throws Exception { final int value = 22; ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState(); Whitebox.setInternalState(tested, int.class, value); assertEquals(value, (int) Whitebox.getInternalState(tested, int.class)); assertEquals(value, Whitebox.getInternalState(tested, "anotherInternalState")); assertEquals(value, Whitebox.getInternalState(tested, "anotherInternalState", ClassWithChildThatHasInternalState.class)); } @Test public void testSetAndGetInternalStateAtASpecificPlaceInTheHierarchyBasedOnFieldType() throws Exception { final int value = 22; ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState(); Whitebox.setInternalState(tested, int.class, value, ClassWithInternalState.class); assertEquals(42, (int) Whitebox.getInternalState(tested, int.class)); assertEquals(value, (int) Whitebox.getInternalState(tested, int.class, ClassWithInternalState.class)); assertEquals(value, Whitebox.getInternalState(tested, "staticState", ClassWithInternalState.class)); } @Test public void testSetInternalStateBasedOnObjectType() throws Exception { final String value = "a string"; ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState(); Whitebox.setInternalState(tested, value); assertEquals(value, Whitebox.getInternalState(tested, String.class)); } @SuppressWarnings("deprecation") @Test public void testSetInternalStateBasedOnObjectTypeWhenArgumentIsAPrimitiveType() throws Exception { final int value = 22; ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState(); Whitebox.setInternalState(tested, value); assertEquals((Integer) value, Whitebox.getInternalState(tested, "anotherInternalState", ClassWithChildThatHasInternalState.class, Integer.class)); } @Test public void testSetInternalStateBasedOnObjectTypeWhenArgumentIsAPrimitiveTypeUsingGenerics() throws Exception { final int value = 22; ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState(); Whitebox.setInternalState(tested, value); assertEquals((Integer) value, Whitebox.getInternalState(tested, "anotherInternalState", ClassWithChildThatHasInternalState.class)); } @Test public void testSetInternalStateBasedOnObjectTypeAtASpecificPlaceInTheClassHierarchy() throws Exception { final String value = "a string"; ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState(); Whitebox.setInternalState(tested, (Object) value, ClassWithInternalState.class); assertEquals(value, Whitebox.getInternalState(tested, "finalString")); } @Test public void testSetInternalStateBasedOnObjectTypeAtASpecificPlaceInTheClassHierarchyForPrimitiveType() throws Exception { final long value = 31; ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState(); Whitebox.setInternalState(tested, value, ClassWithInternalState.class); assertEquals(value, tested.getInternalLongState()); } @Test public void testSetInternalStateBasedOnObjectTypeAtANonSpecificPlaceInTheClassHierarchyForPrimitiveType() throws Exception { final long value = 31; ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState(); Whitebox.setInternalState(tested, value); assertEquals(value, tested.getInternalLongState()); } @Test public void testSetInternalMultipleOfSameTypeOnSpecificPlaceInHierarchy() throws Exception { final int value = 31; ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState(); try { Whitebox.setInternalState(tested, value, ClassWithInternalState.class); fail("should throw TooManyFieldsFoundException!"); } catch (TooManyFieldsFoundException e) { assertEquals("Two or more fields matching type int.", e.getMessage()); } } @Test public void testSetInternalMultipleOfSameType() throws Exception { final int value = 31; ClassWithInternalState tested = new ClassWithInternalState(); try { Whitebox.setInternalState(tested, value); fail("should throw TooManyFieldsFoundException!"); } catch (TooManyFieldsFoundException e) { assertEquals("Two or more fields matching type int.", e.getMessage()); } } @Test public void testSetInternalStateBasedOnObjectSubClassTypeAtASpecificPlaceInTheClassHierarchy() throws Exception { final ClassWithPrivateMethods value = new ClassWithPrivateMethods() { }; ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState(); Whitebox.setInternalState(tested, value, ClassWithInternalState.class); assertSame(value, tested.getClassWithPrivateMethods()); } @Test public void testSetInternalStateBasedOnObjectSubClassType() throws Exception { final ClassWithPrivateMethods value = new ClassWithPrivateMethods() { }; ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState() { }; Whitebox.setInternalState(tested, value); assertSame(value, tested.getClassWithPrivateMethods()); } @Test public void testGetAllInstanceFields() throws Exception { Set allFields = Whitebox.getAllInstanceFields(new ClassWithChildThatHasInternalState()); assertEquals(8, allFields.size()); } @Test public void testGetAllInstanceFieldsOnClass() { Set allFields = Whitebox.getAllInstanceFields(ClassWithChildThatHasInternalState.class); assertEquals(8, allFields.size()); } @Test public void testGetAllStaticFields_assertNoFieldsFromParent() throws Exception { Set allFields = Whitebox.getAllStaticFields(ClassWithChildThatHasInternalState.class); assertEquals(0, allFields.size()); } @Test public void testGetAllStaticFields() throws Exception { Set allFields = Whitebox.getAllStaticFields(ClassWithInternalState.class); assertEquals(4, allFields.size()); } @Test public void testMethodWithNoMethodName_noMethodFound() throws Exception { try { Whitebox.getMethod(ClassWithInternalState.class, int.class); fail("Should throw MethodNotFoundException"); } catch (MethodNotFoundException e) { assertEquals( "No method was found with parameter types: [ int ] in class org.powermock.reflect.testclasses.ClassWithInternalState.", e.getMessage()); } } @Test public void testMethodWithNoMethodName_tooManyMethodsFound() throws Exception { try { Whitebox.getMethod(ClassWithSeveralMethodsWithSameName.class); fail("Should throw TooManyMethodsFoundException"); } catch (TooManyMethodsFoundException e) { assertTrue(e .getMessage() .contains( "Several matching methods found, please specify the method name so that PowerMock can determine which method you're referring to")); } } @Test public void testMethodWithNoMethodName_ok() throws Exception { final Method method = Whitebox.getMethod(ClassWithSeveralMethodsWithSameName.class, double.class); assertEquals(method, ClassWithSeveralMethodsWithSameName.class.getDeclaredMethod("getDouble", double.class)); } @Test public void testGetTwoMethodsWhenNoneOfThemAreFound() throws Exception { try { Whitebox.getMethods(ClassWithSeveralMethodsWithSameName.class, "notFound1", "notFound2"); } catch (MethodNotFoundException e) { assertEquals( "No methods matching the name(s) notFound1 or notFound2 were found in the class hierarchy of class org.powermock.reflect.testclasses.ClassWithSeveralMethodsWithSameName.", e.getMessage()); } } @Test public void testGetThreeMethodsWhenNoneOfThemAreFound() throws Exception { try { Whitebox.getMethods(ClassWithSeveralMethodsWithSameName.class, "notFound1", "notFound2", "notFound3"); } catch (MethodNotFoundException e) { assertEquals( "No methods matching the name(s) notFound1, notFound2 or notFound3 were found in the class hierarchy of class org.powermock.reflect.testclasses.ClassWithSeveralMethodsWithSameName.", e.getMessage()); } } /** * Asserts that issue * 118 is fixed. Thanks to cemcatik for finding this. */ @Test public void testInvokeConstructorWithBothNormalAndVarArgsParameter() throws Exception { ClassWithVarArgsConstructor2 instance = Whitebox.invokeConstructor(ClassWithVarArgsConstructor2.class, "first", "second", "third"); assertArrayEquals(new String[]{"first", "second", "third"}, instance.getStrings()); } /** * Asserts that issue * 118 is fixed. Thanks to cemcatik for finding this. */ @Test public void testInvokeMethodWithBothNormalAndVarArgsParameter() throws Exception { ClassWithPrivateMethods tested = new ClassWithPrivateMethods(); assertEquals(4, Whitebox.invokeMethod(tested, "varArgsMethod2", 1, 2, 3)); } @Test public void testInvokePrivateMethodWithArrayArgument() throws Exception { ClassWithPrivateMethods tested = new ClassWithPrivateMethods(); assertEquals("Hello World", Whitebox.invokeMethod(tested, "evilConcatOfStrings", new Object[]{new String[]{ "Hello ", "World"}})); } @Test public void testSetInternalStateFromContext_allStatesInSameOneContext() throws Exception { ClassWithSimpleInternalState tested = new ClassWithSimpleInternalState(); MyContext context = new MyContext(); Whitebox.setInternalStateFromContext(tested, context); assertEquals(context.getMyStringState(), tested.getSomeStringState()); assertEquals(context.getMyIntState(), tested.getSomeIntState()); } @Test public void testSetInternalStateFromContext_statesInDifferentContext() throws Exception { ClassWithSimpleInternalState tested = new ClassWithSimpleInternalState(); MyIntContext myIntContext = new MyIntContext(); MyStringContext myStringContext = new MyStringContext(); Whitebox.setInternalStateFromContext(tested, myIntContext, myStringContext); assertEquals(myStringContext.getMyStringState(), tested.getSomeStringState()); assertEquals(myIntContext.getSimpleIntState(), tested.getSomeIntState()); } @Test public void testSetInternalStateFromContext_contextIsAClass() throws Exception { ClassWithSimpleInternalState tested = new ClassWithSimpleInternalState(); Whitebox.setInternalStateFromContext(tested, MyContext.class); assertEquals(Whitebox.getInternalState(MyContext.class, long.class), (Long) tested.getSomeStaticLongState()); } @Test public void testSetInternalStateFromContext_contextIsAClassAndAnInstance() throws Exception { ClassWithSimpleInternalState tested = new ClassWithSimpleInternalState(); MyContext myContext = new MyContext(); Whitebox.setInternalStateFromContext(tested, MyContext.class, myContext); assertEquals(myContext.getMyStringState(), tested.getSomeStringState()); assertEquals(myContext.getMyIntState(), tested.getSomeIntState()); assertEquals((Long) myContext.getMyLongState(), (Long) tested.getSomeStaticLongState()); } @Test public void testSetInternalStateFromContext_contextHasOneInstanceAndOneStaticFieldOfSameType_onlyInstanceContext() throws Exception { ClassWithStaticAndInstanceInternalStateOfSameType.reset(); ClassWithStaticAndInstanceInternalStateOfSameType tested = new ClassWithStaticAndInstanceInternalStateOfSameType(); OneInstanceAndOneStaticFieldOfSameTypeContext context = new OneInstanceAndOneStaticFieldOfSameTypeContext(); Whitebox.setInternalStateFromContext(tested, context); assertEquals(context.getMyStringState(), tested.getStringState()); assertEquals("Static String state", tested.getStaticStringState()); } @Test public void testSetInternalStateFromContext_contextHasOneInstanceAndOneStaticFieldOfSameType_onlyStaticContext() throws Exception { ClassWithStaticAndInstanceInternalStateOfSameType.reset(); ClassWithStaticAndInstanceInternalStateOfSameType tested = new ClassWithStaticAndInstanceInternalStateOfSameType(); Whitebox.setInternalStateFromContext(tested, OneInstanceAndOneStaticFieldOfSameTypeContext.class); assertEquals(OneInstanceAndOneStaticFieldOfSameTypeContext.getMyStaticStringState(), tested .getStaticStringState()); assertEquals("String state", tested.getStringState()); } @Test public void setInternalStateFromInstanceContextCopiesMatchingContextFieldsToTargetObjectByDefault() throws Exception { ClassWithSimpleInternalState tested = new ClassWithSimpleInternalState(); InstanceFieldsNotInTargetContext fieldsNotInTargetContext = new InstanceFieldsNotInTargetContext(); assertThat(tested.getSomeStringState()).isNotEqualTo(fieldsNotInTargetContext.getString()); Whitebox.setInternalStateFromContext(tested, fieldsNotInTargetContext); assertEquals(tested.getSomeStringState(), fieldsNotInTargetContext.getString()); } @Test public void setInternalStateFromInstanceContextCopiesMatchingContextFieldsToTargetObjectWhenSpecifyingMatchingStrategy() throws Exception { ClassWithSimpleInternalState tested = new ClassWithSimpleInternalState(); InstanceFieldsNotInTargetContext fieldsNotInTargetContext = new InstanceFieldsNotInTargetContext(); assertThat(tested.getSomeStringState()).isNotEqualTo(fieldsNotInTargetContext.getString()); Whitebox.setInternalStateFromContext(tested, fieldsNotInTargetContext, FieldMatchingStrategy.MATCHING); assertEquals(tested.getSomeStringState(), fieldsNotInTargetContext.getString()); } @Test(expected = FieldNotFoundException.class) public void setInternalStateFromInstanceContextThrowsExceptionWhenContextContainsFieldsNotDefinedInTargetObjectWhenSpecifyingStrictStrategy() throws Exception { ClassWithSimpleInternalState tested = new ClassWithSimpleInternalState(); InstanceFieldsNotInTargetContext fieldsNotInTargetContext = new InstanceFieldsNotInTargetContext(); assertThat(tested.getSomeStringState()).isNotEqualTo(fieldsNotInTargetContext.getString()); Whitebox.setInternalStateFromContext(tested, fieldsNotInTargetContext, FieldMatchingStrategy.STRICT); assertEquals(tested.getSomeStringState(), fieldsNotInTargetContext.getString()); } @Test public void setInternalStateFromClassContextCopiesMatchingContextFieldsToTargetObjectByDefault() throws Exception { long state = ClassWithSimpleInternalState.getLong(); try { assertThat(state).isNotEqualTo(ClassFieldsNotInTargetContext.getLong()); Whitebox.setInternalStateFromContext(ClassWithSimpleInternalState.class, ClassFieldsNotInTargetContext.class); assertEquals(ClassFieldsNotInTargetContext.getLong(), ClassWithSimpleInternalState.getLong()); } finally { // Restore the state ClassWithSimpleInternalState.setLong(state); } } @Test public void setInternalStateFromClassContextCopiesMatchingContextFieldsToTargetObjectWhenSpecifyingMatchingStrategy() throws Exception { long state = ClassWithSimpleInternalState.getLong(); try { assertThat(state).isNotEqualTo(ClassFieldsNotInTargetContext.getLong()); Whitebox.setInternalStateFromContext(ClassWithSimpleInternalState.class, ClassFieldsNotInTargetContext.class, FieldMatchingStrategy.MATCHING); assertEquals(ClassFieldsNotInTargetContext.getLong(), ClassWithSimpleInternalState.getLong()); } finally { // Restore the state ClassWithSimpleInternalState.setLong(state); } } @Test(expected = FieldNotFoundException.class) public void setInternalStateFromClassContextThrowsExceptionWhenContextContainsFieldsNotDefinedInTargetObjectWhenSpecifyingStrictStrategy() throws Exception { long state = ClassWithSimpleInternalState.getLong(); try { assertThat(state).isNotEqualTo(ClassFieldsNotInTargetContext.getLong()); Whitebox.setInternalStateFromContext(ClassWithSimpleInternalState.class, ClassFieldsNotInTargetContext.class, FieldMatchingStrategy.STRICT); } finally { // Restore the state ClassWithSimpleInternalState.setLong(state); } } @Test public void assertThatErrorMessageIsCorrectWhenNoInstanceFieldFound() throws Exception { ClassWithInternalState classWithInternalState = new ClassWithInternalState(); try { Whitebox.setInternalState(classWithInternalState, (byte) 23); fail("Should throw a FieldNotFoundException."); } catch (FieldNotFoundException e) { assertEquals( "No instance field assignable from \"java.lang.Byte\" could be found in the class hierarchy of " + ClassWithInternalState.class.getName() + ".", e.getMessage()); } } @Test public void assertThatErrorMessageIsCorrectWhenNoStaticFieldFound() throws Exception { try { Whitebox.setInternalState(ClassWithInternalState.class, (byte) 23); fail("Should throw a FieldNotFoundException."); } catch (FieldNotFoundException e) { assertEquals("No static field assignable from \"java.lang.Byte\" could be found in the class hierarchy of " + ClassWithInternalState.class.getName() + ".", e.getMessage()); } } @Test public void assertThatWhiteboxWorksWithGenericsWhenSpecifyingFieldName() throws Exception { ClassWithInternalState object = new ClassWithInternalState(); Set state = Whitebox.getInternalState(object, "genericState"); assertSame(object.getGenericState(), state); } @Test public void whiteboxGetMethodWithCorrectMethodNameButWrongParameterTypeReturnsErrorMessageReflectingTheWrongParameter() throws Exception { try { Whitebox.getMethod(ClassWithInternalState.class, "methodWithArgument", String.class, InputStream.class); fail("Should throw MethodNotFoundException"); } catch (MethodNotFoundException e) { assertEquals( "No method found with name 'methodWithArgument' with parameter types: [ java.lang.String, java.io.InputStream ] in class org.powermock.reflect.testclasses.ClassWithInternalState.", e.getMessage()); } } @Test public void whiteboxSetInternalStateWorksOnArraysWhenDefiningMethodName() { ClassWithInternalState tested = new ClassWithInternalState(); final String[] expected = new String[]{"string1", "string2"}; Whitebox.setInternalState(tested, "stringArray", expected); assertArrayEquals(expected, tested.getStringArray()); } @Test public void whiteboxSetInternalStateWorksOnArraysWhenNotDefiningMethodName() { ClassWithInternalState tested = new ClassWithInternalState(); final String[] expected = new String[]{"string1", "string2"}; Whitebox.setInternalState(tested, expected); assertArrayEquals(expected, tested.getStringArray()); } @Test public void getInternalStateThrowsIAEWhenInstanceIsNull() { try { Whitebox.getInternalState(null, String.class); fail("Should throw IllegalArgumentException"); } catch (IllegalArgumentException e) { assertEquals("The object containing the field cannot be null", e.getMessage()); } } @Test public void getInternalStateSupportsObjectArrayWhenSUTContainsSerializable() { ClassWithSerializableState tested = new ClassWithSerializableState(); tested.setSerializable(new Serializable() { private static final long serialVersionUID = -1850246005852779087L; }); tested.setObjectArray(new Object[0]); assertNotNull(Whitebox.getInternalState(tested, Object[].class)); } @Test public void getInternalStateUsesAssignableToWhenLookingForObject() { ClassWithList tested = new ClassWithList(); assertNotNull(Whitebox.getInternalState(tested, Object.class)); } @Test(expected = TooManyFieldsFoundException.class) public void getInternalStateThrowsTooManyFieldsFoundWhenTooManyFieldsMatchTheSuppliedType() { ClassWithInternalState tested = new ClassWithInternalState(); assertNotNull(Whitebox.getInternalState(tested, Object.class)); } @Test public void invokeMethodInvokesOverridenMethods() throws Exception { assertTrue(Whitebox.invokeMethod(new ClassWithOverriddenMethod(), 2.0d)); } @Test(expected = IllegalArgumentException.class) public void newInstanceThrowsIAEWhenClassIsAbstract() throws Exception { Whitebox.newInstance(AbstractClass.class); } @Test public void newInstanceReturnsJavaProxyWhenInterface() throws Exception { AnInterface instance = Whitebox.newInstance(AnInterface.class); assertTrue(Proxy.isProxyClass(instance.getClass())); } @Test public void newInstanceCreatesAnEmptyArrayWhenClassIsArray() throws Exception { byte[] newInstance = Whitebox.newInstance(byte[].class); assertEquals(0, newInstance.length); } @Test(expected = IllegalArgumentException.class) public void invokeMethodSupportsNullParameters() throws Exception { ClassWithAMethod classWithAMethod = new ClassWithAMethod(); Connection connection = null; Whitebox.invokeMethod(classWithAMethod, "connect", connection); } @Test(expected = MethodNotFoundException.class) public void invokeOverriddenMethodWithNullParameterThrowsIAE() throws Exception { ClassWithOverloadedMethods tested = new ClassWithOverloadedMethods(); Child child = null; Whitebox.invokeMethod(tested, "overloaded", 2, child); } @Test public void canPassNullParamToPrivateStaticMethod() throws Exception { assertEquals("hello", Whitebox.invokeMethod(ClassWithStaticMethod.class, "aStaticMethod", (Object[])null)); } @Test public void canPassNullParamToPrivateStaticMethodWhenDefiningParameterTypes() throws Exception { assertEquals("hello", Whitebox.invokeMethod(ClassWithStaticMethod.class, "aStaticMethod", new Class[]{byte[].class}, (Object[])null)); } @Test public void canPassNullPrimitiveArraysToAPrivateStaticMethod() throws Exception { assertEquals("hello", Whitebox.invokeMethod(ClassWithStaticMethod.class, "aStaticMethod", (byte[]) null)); } @Test public void canPassMultipleNullValuesToStaticMethod() throws Exception { assertEquals("null null", Whitebox.invokeMethod(ClassWithStaticMethod.class, "anotherStaticMethod", (Object) null, (byte[]) null)); } @Test public void testObjectConstructors() throws Exception { String name = "objectConstructor"; ClassWithObjectConstructors instance = Whitebox.invokeConstructor(ClassWithObjectConstructors.class, name); assertEquals(instance.getName(), name); } @Test public void testInterfaceConstructors() throws Exception { ConstructorInterface param = new ConstructorInterfaceImpl("constructorInterfaceSomeValue"); ClassWithInterfaceConstructors instance = Whitebox.invokeConstructor(ClassWithInterfaceConstructors.class, param); assertEquals(instance.getValue(), param.getValue()); } @Test public void testPrimitiveConstructorsArgumentBoxed() throws Exception { Long arg = 1L; ClassWithPrimitiveConstructors instance = Whitebox.invokeConstructor(ClassWithPrimitiveConstructors.class, arg); assertEquals(instance.getValue(), arg.longValue()); } @Test public void testOverloadedConstructors() throws Exception { String name = "overloadedConstructor"; ClassWithOverloadedConstructors instance = Whitebox.invokeConstructor(ClassWithOverloadedConstructors.class, true, name); assertEquals(instance.getName(), name); assertTrue(instance.isBool()); assertThat(instance.isBool1()).isFalse(); } @Test @Ignore("Reflection and direct call returns different values.") public void testFinalState() { ClassWithInternalState state = new ClassWithInternalState(); String expected = "changed"; Whitebox.setInternalState(state, "finalString", expected); assertEquals(expected, state.getFinalString()); assertEquals(expected, Whitebox.getInternalState(state, "finalString")); } } ================================================ FILE: powermock-reflect/src/test/java/org/powermock/reflect/context/ClassFieldsNotInTargetContext.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.reflect.context; import java.util.HashMap; import java.util.Map; /** * The purpose of this context is that it should define fields not available in * the target object to where the state is supposed to be copied. */ public class ClassFieldsNotInTargetContext { private static long something = 42L; private static Map map = new HashMap(); public static long getLong() { return something; } public static Map getMap() { return map; } } ================================================ FILE: powermock-reflect/src/test/java/org/powermock/reflect/context/InstanceFieldsNotInTargetContext.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.reflect.context; import java.util.HashMap; import java.util.Map; /** * The purpose of this context is that it should define fields not available in * the target object to where the state is supposed to be copied. */ public class InstanceFieldsNotInTargetContext { private String something = "something"; private Map map = new HashMap(); public String getString() { return something; } public Map getMap() { return map; } } ================================================ FILE: powermock-reflect/src/test/java/org/powermock/reflect/context/MyContext.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.reflect.context; public class MyContext { private int myIntState = 42; private String myStringState = "myString"; private static long myLongState = 21L; public long getMyLongState() { return myLongState; } public int getMyIntState() { return myIntState; } public String getMyStringState() { return myStringState; } } ================================================ FILE: powermock-reflect/src/test/java/org/powermock/reflect/context/MyIntContext.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.reflect.context; public class MyIntContext { private int simpleIntState = 42; public int getSimpleIntState() { return simpleIntState; } } ================================================ FILE: powermock-reflect/src/test/java/org/powermock/reflect/context/MyStringContext.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.reflect.context; public class MyStringContext { private String myStringState = "string"; public String getMyStringState() { return myStringState; } } ================================================ FILE: powermock-reflect/src/test/java/org/powermock/reflect/context/OneInstanceAndOneStaticFieldOfSameTypeContext.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.reflect.context; public class OneInstanceAndOneStaticFieldOfSameTypeContext { private String myStringState = "myString"; private static String myStaticStringState = "21L"; public String getMyStringState() { return myStringState; } public static String getMyStaticStringState() { return myStaticStringState; } } ================================================ FILE: powermock-reflect/src/test/java/org/powermock/reflect/internal/WhiteboxImplTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.reflect.internal; import org.junit.Test; import org.powermock.reflect.testclasses.*; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assume.assumeTrue; /** * Unit tests specific to the WhiteboxImpl. */ public class WhiteboxImplTest { /** * Asserts that a previous bug was fixed. */ @Test public void assertThatClassAndNotStringIsNotSameWhenInvokingCheckIfTypesAreSame() throws Exception { Method method = WhiteboxImpl.getMethod(WhiteboxImpl.class, "checkIfParameterTypesAreSame", boolean.class, Class[].class, Class[].class); boolean invokeMethod = (Boolean) method.invoke(WhiteboxImpl.class, false, new Class[] { Class.class }, new Class[] { String.class }); assertThat(invokeMethod).isFalse(); } @Test public void assertThatClassAndClassIsSameWhenInvokingCheckIfTypesAreSame() throws Exception { Method method = WhiteboxImpl.getMethod(WhiteboxImpl.class, "checkIfParameterTypesAreSame", boolean.class, Class[].class, Class[].class); boolean invokeMethod = (Boolean) method.invoke(WhiteboxImpl.class, false, new Class[] { Class.class }, new Class[] { Class.class }); assertThat(invokeMethod).isTrue(); } @Test public void getBestCandidateMethodReturnsMatchingMethodWhenNoOverloading() throws Exception { final Method expectedMethod = ClassWithStandardMethod.class.getDeclaredMethod("myMethod", double.class); final Method actualMethod = WhiteboxImpl.getBestMethodCandidate(ClassWithStandardMethod.class, "myMethod", new Class[] { double.class }, false); assertThat(actualMethod).isEqualTo(expectedMethod); } @Test public void getBestCandidateMethodReturnsMatchingMethodWhenOverloading() throws Exception { final Method expectedMethod = ClassWithOverloadedMethods.class.getDeclaredMethod("overloaded", double.class, Child.class); final Method actualMethod = WhiteboxImpl.getBestMethodCandidate(ClassWithOverloadedMethods.class, "overloaded", new Class[] { double.class, Child.class }, false); assertThat(actualMethod).isEqualTo(expectedMethod); } @Test public void defaultMethodsAreFound() throws Exception { assumeTrue(Float.valueOf(System.getProperty("java.specification.version")) >= 1.8f); Method[] methods = WhiteboxImpl.getAllMethods(Collection.class); List methodNames = new ArrayList(); for (Method method : methods) { methodNames.add(method.getName()); } assertThat(methodNames).contains("stream"); } @Test public void testGetMethodNotExactParameterTypeMatch() throws NoSuchMethodException { Method[] methods = WhiteboxImpl.getMethods( ClassWithMethodUsingBothPrimitiveTypeAndWrappedTypeArguments.class, "methodHavingBothPrimitiveTypeAndWrappedTypeArguments", new Class[]{Integer.class, Integer.class}, false ); Method method = ClassWithMethodUsingBothPrimitiveTypeAndWrappedTypeArguments.class.getMethod( "methodHavingBothPrimitiveTypeAndWrappedTypeArguments", Integer.class, int.class ); assertEquals(methods[0], method); } } ================================================ FILE: powermock-reflect/src/test/java/org/powermock/reflect/internal/proxy/AnotherInterface.java ================================================ package org.powermock.reflect.internal.proxy; public interface AnotherInterface { } ================================================ FILE: powermock-reflect/src/test/java/org/powermock/reflect/internal/proxy/ClassFactory.java ================================================ package org.powermock.reflect.internal.proxy; import net.bytebuddy.jar.asm.ClassWriter; import net.bytebuddy.jar.asm.MethodVisitor; import net.bytebuddy.jar.asm.Opcodes; class ClassFactory implements Opcodes { static byte[] create(String className) throws Exception { ClassWriter cw = new ClassWriter(0); MethodVisitor mv; cw.visit(49, ACC_PUBLIC + ACC_SUPER, className, null, "java/lang/Object", null); cw.visitSource("Hello.java", null); { mv = cw.visitMethod(ACC_PUBLIC, "", "()V", null, null); mv.visitVarInsn(ALOAD, 0); mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "", "()V", false); mv.visitInsn(RETURN); mv.visitMaxs(1, 1); mv.visitEnd(); } { mv = cw.visitMethod(ACC_PUBLIC + ACC_STATIC, "main", "([Ljava/lang/String;)V", null, null); mv.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); mv.visitLdcInsn("hello"); mv.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false); mv.visitInsn(RETURN); mv.visitMaxs(2, 1); mv.visitEnd(); } cw.visitEnd(); return cw.toByteArray(); } } ================================================ FILE: powermock-reflect/src/test/java/org/powermock/reflect/internal/proxy/ProxyFrameworksTest.java ================================================ package org.powermock.reflect.internal.proxy; import net.sf.cglib.proxy.Enhancer; import net.sf.cglib.proxy.Factory; import net.sf.cglib.proxy.InvocationHandler; import org.junit.Before; import org.junit.Test; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import static org.assertj.core.api.Java6Assertions.assertThat; public class ProxyFrameworksTest { private ProxyFrameworks proxyFrameworks; @Before public void setUp() throws Exception { proxyFrameworks = new ProxyFrameworks(); } @Test public void should_throw_illegal_argument_exception_if_class_is_null() throws Exception { assertThat(proxyFrameworks.getUnproxiedType(null)).isNull(); } @Test public void should_return_null_if_object_is_null() throws Exception { assertThat(proxyFrameworks.getUnproxiedType((Object) null)).isNull(); } @Test public void should_return_original_class_if_object_not_proxy() throws Exception { SomeClass someClass = new SomeClass(); UnproxiedType unproxiedType = proxyFrameworks.getUnproxiedType(someClass); assertThatOriginalTypeInstanceOf(unproxiedType, SomeClass.class); } @Test public void should_return_original_class_if_proxy_created_with_java() { SomeInterface someInterface = createJavaProxy(new Class[]{ SomeInterface.class }); UnproxiedType unproxiedType = proxyFrameworks.getUnproxiedType(someInterface); assertThatOriginalTypeInstanceOf(unproxiedType, SomeInterface.class); } @Test public void should_return_original_class_if_proxy_created_with_cglib() { SomeClass someClass = (SomeClass) createCglibProxy(SomeClass.class); UnproxiedType unproxiedType = proxyFrameworks.getUnproxiedType(someClass); assertThatOriginalTypeInstanceOf(unproxiedType, SomeClass.class); } @Test public void should_not_detect_synthetic_classes_as_cglib_proxy() throws Exception { final ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); final Enumeration resources = classLoader.getResources("org/powermock/reflect/internal/proxy"); final List urls = new ArrayList(); while (resources.hasMoreElements()) { urls.add(resources.nextElement()); } String className = "Some$$SyntheticClass$$Lambda"; byte[] bytes = ClassFactory.create(className); CustomClassLoader customClassLoader = new CustomClassLoader(urls.toArray(new URL[urls.size()]), classLoader); Class defineClass = customClassLoader.defineClass(className, bytes); UnproxiedType unproxiedType = proxyFrameworks.getUnproxiedType(defineClass.newInstance()); assertThatOriginalTypeInstanceOf(unproxiedType, defineClass); } @Test public void should_return_object_as_original_class_if_no_non_no_mocking_interfaces() { Factory someClass = (Factory) createCglibProxy(Factory.class); UnproxiedType unproxiedType = proxyFrameworks.getUnproxiedType(someClass); assertThatOriginalTypeInstanceOf(unproxiedType, Object.class); } @Test public void should_return_interface_as_original_type_if_only_one_non_mocking_interface() { Factory someClass = (Factory) createCglibProxy(Factory.class, SomeInterface.class); UnproxiedType unproxiedType = proxyFrameworks.getUnproxiedType(someClass); assertThatOriginalTypeInstanceOf(unproxiedType, SomeInterface.class); } @Test public void should_return_interface_and_original_type_if_proxy_has_interface_and_superclass() { SomeClass someClass = (SomeClass) createCglibProxy(SomeClass.class, SomeInterface.class, AnotherInterface.class); UnproxiedType unproxiedType = proxyFrameworks.getUnproxiedType(someClass); assertThatOriginalTypeInstanceOfAndInterfaces(unproxiedType, SomeClass.class, new Class[]{ SomeInterface.class, AnotherInterface.class }); } @Test public void should_return_interfaces_if_proxy_create_from_several_interfaces() { Class[] interfaces = {SomeInterface.class, AnotherInterface.class}; SomeInterface someInterface = createJavaProxy(interfaces); UnproxiedType unproxiedType = proxyFrameworks.getUnproxiedType(someInterface); assertThatOriginalIsNullAndInterfaces( unproxiedType, interfaces ); } private Object createCglibProxy(Class superclass, Class... interfaces) { if (interfaces.length == 0){ return Enhancer.create( superclass, new InvocationHandler() { @Override public Object invoke(Object o, Method method, Object[] objects) throws Throwable { return method.invoke(o, objects); } }); }else { return Enhancer.create( superclass, interfaces, new InvocationHandler() { @Override public Object invoke(Object o, Method method, Object[] objects) throws Throwable { return method.invoke(o, objects); } }); } } private SomeInterface createJavaProxy(Class[] interfaces) { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); return (SomeInterface) Proxy.newProxyInstance( classLoader, interfaces, new java.lang.reflect.InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return method.invoke(proxy, args); } }); } private void assertThatOriginalIsNullAndInterfaces(UnproxiedType unproxiedType, Class[] expectedInterfaces) { assertThat(unproxiedType.getOriginalType()).isNull(); assertThat(unproxiedType.getInterfaces()) .containsExactlyInAnyOrder(expectedInterfaces); } private void assertThatOriginalTypeInstanceOf(UnproxiedType unproxiedType, Class expectedClass) { assertThat(unproxiedType.getOriginalType()).isEqualTo(expectedClass); assertThat(unproxiedType.getInterfaces()).isEmpty(); } private void assertThatOriginalTypeInstanceOfAndInterfaces(UnproxiedType unproxiedType, Class expectedClass,Class[] expectedInterfaces ) { assertThat(unproxiedType.getOriginalType()).isEqualTo(expectedClass); assertThat(unproxiedType.getInterfaces()) .containsExactlyInAnyOrder(expectedInterfaces); } private static class CustomClassLoader extends URLClassLoader { private CustomClassLoader(URL[] urls, ClassLoader parent) { super(urls, parent); } Class defineClass(String name, byte[] b) { return defineClass(name, b, 0, b.length); } } } ================================================ FILE: powermock-reflect/src/test/java/org/powermock/reflect/internal/proxy/SomeClass.java ================================================ package org.powermock.reflect.internal.proxy; /** * */ public class SomeClass { } ================================================ FILE: powermock-reflect/src/test/java/org/powermock/reflect/internal/proxy/SomeInterface.java ================================================ package org.powermock.reflect.internal.proxy; public interface SomeInterface { } ================================================ FILE: powermock-reflect/src/test/java/org/powermock/reflect/testclasses/AbstractClass.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.reflect.testclasses; public abstract class AbstractClass { } ================================================ FILE: powermock-reflect/src/test/java/org/powermock/reflect/testclasses/AnInterface.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.reflect.testclasses; public interface AnInterface { } ================================================ FILE: powermock-reflect/src/test/java/org/powermock/reflect/testclasses/Child.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.reflect.testclasses; public class Child extends Parent { } ================================================ FILE: powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithAMethod.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.reflect.testclasses; import java.sql.Connection; public class ClassWithAMethod { public void connect(Connection connection) { if(connection == null) { throw new IllegalArgumentException("param was null"); } } } ================================================ FILE: powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithChildThatHasInternalState.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.reflect.testclasses; @SuppressWarnings("unused") public class ClassWithChildThatHasInternalState extends ClassWithInternalState { private int anotherInternalState = 42; } ================================================ FILE: powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithInterfaceConstructors.java ================================================ package org.powermock.reflect.testclasses; /** * */ public class ClassWithInterfaceConstructors { private final ConstructorInterface constructorInterface; public ClassWithInterfaceConstructors(ConstructorInterface constructorInterface) {this.constructorInterface = constructorInterface;} public String getValue() { return constructorInterface.getValue(); } public interface ConstructorInterface { String getValue(); } public static class ConstructorInterfaceImpl implements ConstructorInterface { private final String value; public ConstructorInterfaceImpl(String value) {this.value = value;} @Override public String getValue() { return value; } } } ================================================ FILE: powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithInternalState.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.reflect.testclasses; import java.io.InputStream; import java.util.HashSet; import java.util.Set; public class ClassWithInternalState { private static int staticState = 5; private static final int staticFinalIntState = 15; private static final Integer staticFinalIntegerState = 15; private static final String staticFinalStringState = "Some String"; private int internalState = 0; private int anotherInternalState = -1; private final String finalString = "hello"; private long internalLongState = 17; private String[] stringArray = new String[0]; private Set genericState = new HashSet(); private ClassWithPrivateMethods classWithPrivateMethods; public String getFinalString() { return finalString; } public void increaseInteralState() { internalState++; } public void decreaseInteralState() { internalState--; } public int getAnotherInternalState() { return anotherInternalState; } public static int getStaticState() { return staticState; } public static Integer getStaticFinalIntegerState() { return staticFinalIntegerState; } public ClassWithPrivateMethods getClassWithPrivateMethods() { return classWithPrivateMethods; } public long getInternalLongState() { return internalLongState; } public Set getGenericState() { return genericState; } public static String methodWithArgument(InputStream inputStream) { return ""; } public String[] getStringArray() { return stringArray; } } ================================================ FILE: powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithList.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.reflect.testclasses; import java.util.LinkedList; import java.util.List; public class ClassWithList { @SuppressWarnings("unused") private List list = new LinkedList(); } ================================================ FILE: powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithMethodUsingBothPrimitiveTypeAndWrappedTypeArguments.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.reflect.testclasses; public class ClassWithMethodUsingBothPrimitiveTypeAndWrappedTypeArguments { public void methodHavingBothPrimitiveTypeAndWrappedTypeArguments(Integer arg0, int arg1) { } } ================================================ FILE: powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithMethodUsingSuperTypeArgument.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.reflect.testclasses; public class ClassWithMethodUsingSuperTypeArgument { public void methodHavingASuperTypeArgument(ClassWithStandardMethod arg) { } } ================================================ FILE: powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithObjectConstructors.java ================================================ package org.powermock.reflect.testclasses; /** * */ public class ClassWithObjectConstructors { private final Object name; protected ClassWithObjectConstructors(Object name) { this.name = name; } public Object getName() { return name; } } ================================================ FILE: powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithOverloadedConstructors.java ================================================ package org.powermock.reflect.testclasses; /** * */ public class ClassWithOverloadedConstructors { private final String name; private final boolean bool; private final boolean bool1; protected ClassWithOverloadedConstructors(String name) { this(name, false, false); } protected ClassWithOverloadedConstructors(boolean bool, String name) { this(name, bool, false); } protected ClassWithOverloadedConstructors(String name, boolean bool, boolean bool1) { this.name = name; this.bool = bool; this.bool1 = bool1; } public String getName() { return name; } public boolean isBool() { return bool; } public boolean isBool1() { return bool1; } } ================================================ FILE: powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithOverloadedMethods.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.reflect.testclasses; public class ClassWithOverloadedMethods { public String overloaded(double value, Parent parent) { return "parent"; } public String overloaded(double value, Child child) { return "child"; } } ================================================ FILE: powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithOverriddenMethod.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.reflect.testclasses; public class ClassWithOverriddenMethod extends ClassWithStandardMethod { @Override public boolean myMethod(double value) { return true; } } ================================================ FILE: powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithPrimitiveConstructors.java ================================================ package org.powermock.reflect.testclasses; /** * */ public class ClassWithPrimitiveConstructors { private final long value; public ClassWithPrimitiveConstructors(long value){ this.value = value; } public long getValue() { return value; } } ================================================ FILE: powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithPrivateMethods.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.reflect.testclasses; @SuppressWarnings("unused") public class ClassWithPrivateMethods { private boolean primitiveMethod(double value) { return true; } private boolean wrappedMethod(Double value) { return true; } private String methodWithPrimitiveIntAndString(int myInt, String aString) { return aString + Integer.toString(myInt); } private int methodWithPrimitiveAndWrappedInt(int myInt, Integer myInt2) { return myInt + myInt2; } private String evilConcatOfStrings(String[] strings) { String returnValue = ""; for (String string : strings) { returnValue += string; } return returnValue; } private int varArgsMethod(int... ints) { int sum = 0; for (int i : ints) { sum += i; } return sum; } private ClassWithInternalState methodWithObjectArgument(ClassWithInternalState c) { return c; } private Class methodWithClassArgument(Class c) { return c; } private int varArgsMethod(int value) { return value * 2; } private int varArgsMethod2(int value, int... moreValues) { return value * 2 + moreValues.length; } } ================================================ FILE: powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithSerializableState.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.reflect.testclasses; import java.io.Serializable; @SuppressWarnings("unused") public class ClassWithSerializableState { private Serializable serializable; private Object[] objectArray; public void setSerializable(Serializable serializable) { this.serializable = serializable; } public void setObjectArray(Object[] objectArray) { this.objectArray = objectArray; } } ================================================ FILE: powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithSeveralMethodsWithSameName.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.reflect.testclasses; public class ClassWithSeveralMethodsWithSameName { public double getDouble(double value) { return value; } public double getDouble(double value1, double value2) { return value1 + value2; } } ================================================ FILE: powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithSeveralMethodsWithSameNameOneWithoutParameters.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.reflect.testclasses; public class ClassWithSeveralMethodsWithSameNameOneWithoutParameters { public double getDouble() { return Double.MAX_VALUE; } public double getDouble(double value) { return value; } public double getDouble(double value1, double value2) { return value1 + value2; } } ================================================ FILE: powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithSimpleInternalState.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.reflect.testclasses; public class ClassWithSimpleInternalState { private int someIntState = -1; private String someStringState = "-1"; private static long someStaticLongState = -1L; public static long getLong() { return someStaticLongState; } public long getSomeStaticLongState() { return someStaticLongState; } public int getSomeIntState() { return someIntState; } public String getSomeStringState() { return someStringState; } public static void setLong(long state) { someStaticLongState = state; } } ================================================ FILE: powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithSimpleStateOfSameType.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.reflect.testclasses; public class ClassWithSimpleStateOfSameType { private String someStringState = "-1"; private String someOtherStringState = "-1"; public String getSomeStringState() { return someStringState; } public String getSomeOtherStringState() { return someOtherStringState; } } ================================================ FILE: powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithStandardMethod.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.reflect.testclasses; public class ClassWithStandardMethod { public boolean myMethod(double value) { return true; } } ================================================ FILE: powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithStaticAndInstanceInternalStateOfSameType.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.reflect.testclasses; public class ClassWithStaticAndInstanceInternalStateOfSameType { private String stringState = "String state"; private static String staticStringState = "Static String state"; public String getStaticStringState() { return staticStringState; } public String getStringState() { return stringState; } public static void reset() { staticStringState = "Static String state"; } } ================================================ FILE: powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithStaticMethod.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.reflect.testclasses; public class ClassWithStaticMethod { @SuppressWarnings({"UnusedDeclaration"}) private static String aStaticMethod(byte[] something) { return "hello"; } @SuppressWarnings({"UnusedDeclaration"}) private static String anotherStaticMethod(Object object, byte[] something) { return object+" "+something; } } ================================================ FILE: powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithUniquePrivateMethods.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.reflect.testclasses; @SuppressWarnings("unused") public class ClassWithUniquePrivateMethods { private boolean primitiveMethodWithOnlyOneArgument(double value) { return true; } private static boolean primitiveStaticMethodWithOnlyOneArgument(double value) { return true; } private boolean primitiveMethod(double value, double value2) { return true; } private Object twoArgs(double value, double value2, Object obj) { return new Object(); } } ================================================ FILE: powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithVarArgsConstructor.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.reflect.testclasses; public class ClassWithVarArgsConstructor { private final String[] strings; private ClassWithVarArgsConstructor(String...strings) { this.strings = strings; } public String[] getStrings() { return strings; } } ================================================ FILE: powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithVarArgsConstructor2.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.reflect.testclasses; public class ClassWithVarArgsConstructor2 { private final String[] strings; private ClassWithVarArgsConstructor2(String required, String... strings) { this.strings = new String[strings.length + 1]; this.strings[0] = required; System.arraycopy(strings, 0, this.strings, 1, strings.length); } public String[] getStrings() { return strings; } } ================================================ FILE: powermock-reflect/src/test/java/org/powermock/reflect/testclasses/Parent.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powermock.reflect.testclasses; public class Parent { } ================================================ FILE: powermock-release/build.gradle ================================================ apply from: "${gradleScriptDir}/release/fullJars.gradle" apply from: "${gradleScriptDir}/release/distZip.gradle" jar { enabled = false } project(":powermock-release:powermock-easymock") { description = "Single jar containing binaries for PowerMock core, EasyMock and all test framework modules." def shadowDependencies = [ project(":powermock-reflect"), project(":powermock-core"), project(":powermock-classloading:powermock-classloading-base"), project(":powermock-api:powermock-api-support"), project(":powermock-api:powermock-api-easymock"), project(":powermock-modules:powermock-module-junit4-common"), project(":powermock-modules:powermock-module-junit4"), project(":powermock-modules:powermock-module-junit4-legacy"), project(":powermock-modules:powermock-module-testng"), project(":powermock-modules:powermock-module-testng-common") ] dependencies { runtime shadowDependencies } shadowJar { shadowDependencies.each { from(it.sourceSets.main.allSource) { include "**/*.java" } } } } project(":powermock-release:powermock-mockito2") { description = "Single jar containing binaries for PowerMock core, Mockito 2.x and all test framework modules." def shadowDependencies = [ project(":powermock-reflect"), project(":powermock-core"), project(":powermock-classloading:powermock-classloading-base"), project(":powermock-api:powermock-api-support"), project(":powermock-api:powermock-api-mockito2"), project(":powermock-modules:powermock-module-junit4-common"), project(":powermock-modules:powermock-module-junit4"), project(":powermock-modules:powermock-module-junit4-legacy"), project(":powermock-modules:powermock-module-testng"), project(":powermock-modules:powermock-module-testng-common") ] dependencies { runtime shadowDependencies } shadowJar { shadowDependencies.each { from(it.sourceSets.main.allSource) { include "**/*.java" } } } } project(":powermock-release:powermock-easymock-junit") { description = "Single jar containing binaries for PowerMock core, JUnit and EasyMock modules." dependencies { compile(project(path:":powermock-release:powermock-easymock", configuration: "shadow")) compile("junit:junit:${junitVersion}") { exclude group: 'org.hamcrest', module: 'hamcrest-core' } compile("org.hamcrest:hamcrest-core:${hamcrestVersion}") compile("org.easymock:easymock:${easymockVersion}") compile("org.objenesis:objenesis:${objenesisVersion}") compile("org.javassist:javassist:${javassistVersion}") compile("cglib:cglib-nodep:${cglibVersion}") } } project(":powermock-release:powermock-easymock-testng") { description = "Single jar containing binaries for PowerMock core, TestNG and EasyMock modules." dependencies { compile(project(path:":powermock-release:powermock-easymock", configuration: "shadow")) compile("org.testng:testng:${testngVersion}") compile("org.hamcrest:hamcrest-core:${hamcrestVersion}") compile("org.easymock:easymock:${easymockVersion}") compile("org.objenesis:objenesis:${objenesisVersion}") compile("org.javassist:javassist:${javassistVersion}") compile("cglib:cglib-nodep:${cglibVersion}") } } project(":powermock-release:powermock-mockito2-junit") { description = "Single jar containing binaries for PowerMock core, JUnit and Mockito modules." dependencies { compile(project(path:":powermock-release:powermock-mockito2", configuration: "shadow")) compile("junit:junit:${junitVersion}") { exclude group: 'org.hamcrest', module: 'hamcrest-core' } compile("org.hamcrest:hamcrest-core:${hamcrestVersion}") compile("org.mockito:mockito-core:${mockitoVersion}"){ exclude group: 'net.bytebuddy', module: 'byte-buddy' exclude group: 'net.bytebuddy', module: 'byte-buddy-agent' } compile("org.objenesis:objenesis:${objenesisVersion}") compile("org.javassist:javassist:${javassistVersion}") compile("cglib:cglib-nodep:${cglibVersion}") } } project(":powermock-release:powermock-mockito2-testng") { description = "Single jar containing binaries for PowerMock core, TestNG and Mockito modules." dependencies { compile(project(path:":powermock-release:powermock-mockito2", configuration: "shadow")) compile("org.testng:testng:${testngVersion}") compile("org.hamcrest:hamcrest-core:${hamcrestVersion}") compile("org.mockito:mockito-core:${mockitoVersion}"){ exclude group: 'net.bytebuddy', module: 'byte-buddy' exclude group: 'net.bytebuddy', module: 'byte-buddy-agent' } compile("org.objenesis:objenesis:${objenesisVersion}") compile("org.javassist:javassist:${javassistVersion}") compile("cglib:cglib-nodep:${cglibVersion}") } } ================================================ FILE: settings.gradle ================================================ include("powermock-reflect") include("powermock-core") include("powermock-api:powermock-api-support") include("powermock-api:powermock-api-easymock") include("powermock-api:powermock-api-mockito2") include("powermock-classloading:powermock-classloading-base") include("powermock-classloading:powermock-classloading-objenesis") include("powermock-classloading:powermock-classloading-xstream") include("powermock-modules:powermock-module-javaagent") include("powermock-modules:powermock-module-junit4-common") include("powermock-modules:powermock-module-junit4") include("powermock-modules:powermock-module-junit4-legacy") include("powermock-modules:powermock-module-junit4-rule") include("powermock-modules:powermock-module-junit4-rule-agent") include("powermock-modules:powermock-module-testng-common") include("powermock-modules:powermock-module-testng") include("powermock-modules:powermock-module-testng-agent") include("tests:utils") include("tests:junit4") include("tests:testng") include("tests:easymock:junit4-agent") include("tests:easymock:junit4-legacy") include("tests:easymock:junit4") include("tests:easymock:junit45") include("tests:easymock:junit47") include("tests:easymock:junit48") include("tests:easymock:junit410") include("tests:easymock:junit412") include("tests:easymock:testng") include("tests:easymock:testng-agent") include("tests:mockito:junit4") include("tests:mockito:inline") include("tests:mockito:junit49") include("tests:mockito:junit4-agent") include("tests:mockito:junit4-delegate") include("tests:mockito:junit4-rule-objenesis") include("tests:mockito:junit4-rule-xstream") include("tests:mockito:testng") include("tests:java8:mockito-junit4") include("tests:java8:mockito-junit4-agent") include("tests:java8:mockito-junit4-rule-xstream") include("tests:java8:easymock-junit4") include("tests:java11:mockito-junit4") include("powermock-release:powermock-easymock") include("powermock-release:powermock-mockito2") include("powermock-release:powermock-easymock-junit") include("powermock-release:powermock-easymock-testng") include("powermock-release:powermock-mockito2-junit") include("powermock-release:powermock-mockito2-testng") ================================================ FILE: tests/build.gradle ================================================ def subprojects = project(":tests").subprojects - project(":tests:easymock") ext { bintrayAutoPublish = false mavenCentralSync = false } jar{ enabled = false } configure(subprojects) { project -> ext { bintrayAutoPublish = false mavenCentralSync = false } apply from: "${gradleScriptDir}/java-module.gradle" test { jvmArgs "-XX:MaxPermSize=256m" } } project(":tests:utils"){ description = "Common set of classes to test PowerMock features in mocking framework modules." dependencies { compile(project(":powermock-core")) compile("javax.servlet:servlet-api:${servletVersion}") } } project(":tests:junit4"){ description = "Tests for junit4." dependencies { compile(project(":powermock-core")) testCompile(project(":powermock-modules:powermock-module-junit4")) testCompile("junit:junit:${junitVersion}"){ exclude group:'org.hamcrest', module:'hamcrest-core' } testCompile("org.hamcrest:hamcrest-core:${hamcrestVersion}") testCompile("org.easymock:easymock:${easymockVersion}") testCompile("org.assertj:assertj-core:${assertjVersion}") testCompile("com.github.stefanbirkner:system-rules:${systemRulesVersion}") } } project(":tests:testng") { description = "Tests for testng module." dependencies { compile(project(":powermock-core")) testCompile(project(":powermock-modules:powermock-module-testng")) testCompile("org.testng:testng:${testngVersion}") testCompile("org.hamcrest:hamcrest-core:${hamcrestVersion}") testCompile("org.assertj:assertj-core:${assertjVersion}") } test { useTestNG() { suites 'suite.xml' } } } ================================================ FILE: tests/easymock/build.gradle ================================================ List easymock = [ "org.easymock:easymock:${easymockVersion}", "org.assertj:assertj-core:${assertjVersion}", "org.hamcrest:hamcrest-core:${hamcrestVersion}", project(":powermock-api:powermock-api-easymock"), project(":tests:utils") ] project(":tests:easymock:junit4-agent") { description = "Tests for PowerMock Java agent with JUnit4 and Easymock" dependencies { compile(project(":powermock-core")) testCompile("junit:junit:${junitVersion}") testCompile easymock testCompile(project(":powermock-modules:powermock-module-javaagent")) testCompile(project(":powermock-modules:powermock-module-junit4-rule-agent")) } def pathToAgent = project(":powermock-modules:powermock-module-javaagent").jar.outputs.files.getFiles().getAt(0) test { jvmArgs "-javaagent:${pathToAgent}" } } project(":tests:easymock:junit4-legacy"){ description = "Tests for EasyMock module with JUnit 4.0-4.3." dependencies { compile(project(":powermock-core")) testCompile("junit:junit:4.3") testCompile easymock testCompile(project(":powermock-modules:powermock-module-junit4-legacy")) } } project(":tests:easymock:junit4"){ description = " Tests for EasyMock module with JUnit 4.x" dependencies { compile(project(":powermock-core")) testCompile("junit:junit:4.4") testCompile easymock testCompile(project(":powermock-modules:powermock-module-junit4")){ exclude group: 'junit', module: 'junit' } } test{ exclude "**/*Defect*" } } project(":tests:easymock:junit45"){ description = " Tests for EasyMock module with JUnit 4.5." dependencies { compile(project(":powermock-core")) testCompile("junit:junit:4.5") testCompile easymock testCompile(project(":powermock-modules:powermock-module-junit4")){ exclude group: 'junit', module: 'junit' } testCompile files(project(":tests:easymock:junit4").sourceSets.test.output) } test{ exclude "**/*Defect*" } } project(":tests:easymock:junit47"){ description = " Tests for EasyMock module with JUnit 4.7." dependencies { compile(project(":powermock-core")) testCompile("junit:junit:4.7") testCompile easymock testCompile(project(":powermock-modules:powermock-module-junit4")){ exclude group: 'junit', module: 'junit' } testCompile files(project(":tests:easymock:junit4").sourceSets.test.output) } } project(":tests:easymock:junit48"){ description = " Tests for EasyMock module with JUnit 4.8." dependencies { compile(project(":powermock-core")) testCompile("junit:junit:4.8.2") testCompile easymock testCompile(project(":powermock-modules:powermock-module-junit4")){ exclude group: 'junit', module: 'junit' } testCompile files(project(":tests:easymock:junit4").sourceSets.test.output) } } project(":tests:easymock:junit410"){ description = " Tests for EasyMock module with JUnit 4.10." dependencies { compile(project(":powermock-core")) testCompile("junit:junit:4.10") testCompile easymock testCompile(project(":powermock-modules:powermock-module-junit4")){ exclude group: 'junit', module: 'junit' } testCompile files(project(":tests:easymock:junit4").sourceSets.test.output) } } project(":tests:easymock:junit412"){ description = " Tests for EasyMock module with JUnit 4.12." dependencies { compile(project(":powermock-core")) testCompile("junit:junit:4.12") testCompile easymock testCompile(project(":powermock-modules:powermock-module-junit4")){ exclude group: 'junit', module: 'junit' } testCompile files(project(":tests:easymock:junit4").sourceSets.test.output) } } project(":tests:easymock:testng"){ description = "Tests for EasyMock module with TestNG." dependencies { compile(project(":powermock-core")) compile(project(":powermock-modules:powermock-module-testng")) testCompile easymock testCompile("org.testng:testng:${testngVersion}") testCompile("org.hamcrest:hamcrest-core:${hamcrestVersion}") testCompile("org.assertj:assertj-core:${assertjVersion}") } test{ useTestNG(){ suites 'suite.xml' } } } project(":tests:easymock:testng-agent"){ description = "Tests for EasyMock module with TestNG." dependencies { compile(project(":powermock-core")) compile(project(":powermock-modules:powermock-module-testng")) testCompile easymock testCompile("org.testng:testng:${testngVersion}") testCompile("org.hamcrest:hamcrest-core:${hamcrestVersion}") testCompile("org.assertj:assertj-core:${assertjVersion}") testCompile(project(":powermock-modules:powermock-module-testng-agent")) } def pathToAgent = project(":powermock-modules:powermock-module-javaagent").jar.outputs.files.getFiles().getAt(0) test { useTestNG(){ suites 'suite.xml' } jvmArgs "-javaagent:${pathToAgent}" } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/interfacemethodfinding/InterfaceMethodHierarchyUsageTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.interfacemethodfinding; import org.easymock.EasyMock; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.easymock.PowerMock; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.reflect.internal.WhiteboxImpl; import java.sql.Connection; import java.sql.PreparedStatement; /** * There was a bug in PowerMock 1.2 and its predecessors that made PowerMock * {@link WhiteboxImpl#getMethod(Class, Class...)} fail when invoking proxified * interface methods declared in extended interfaces. E.g. if interface A * extends B & C and a method was declared in B it wouldn't be found by * {@link WhiteboxImpl#getMethod(Class, Class...)} since it only used to * traverse the class hierarchy and not the structure of the extended * interfaces. This was fixed in version 1.3 and this test demonstrates that * it's solved. *

* Thanks to Lokesh Vaddi for finding this bug and to provide an example. */ @RunWith(PowerMockRunner.class) @PrepareForTest( { InterfaceMethodHierarchyUsage.class, WsUtil.class }) public class InterfaceMethodHierarchyUsageTest { private InterfaceMethodHierarchyUsage myClass; @Test public void assertMethodsAreFoundInInterfaceHierarchy() throws Exception { Connection mockConnection = PowerMock.createMock(Connection.class); PowerMock.mockStaticPartial(WsUtil.class, "getConnection"); PreparedStatement mockPrepared = PowerMock.createMock(PreparedStatement.class); EasyMock.expect(WsUtil.getConnection()).andReturn(mockConnection); EasyMock.expect(mockConnection.prepareStatement("select * from emp")).andReturn(mockPrepared); mockConnection.close(); EasyMock.expectLastCall(); mockPrepared.close(); EasyMock.expectLastCall(); PowerMock.replayAll(); myClass = new InterfaceMethodHierarchyUsage(); myClass.usePreparedStatement(); PowerMock.verifyAll(); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/abstractmocking/AbstractMethodMockingTest.java ================================================ package samples.junit4.abstractmocking; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.abstractmocking.AbstractMethodMocking; import static org.junit.Assert.assertEquals; import static org.powermock.api.easymock.PowerMock.*; @RunWith(PowerMockRunner.class) @PrepareForTest(AbstractMethodMocking.class) public class AbstractMethodMockingTest { @Test public void testMockingOfAbstractMethod() throws Exception { final String value = "a string"; AbstractMethodMocking tested = createPartialMock( AbstractMethodMocking.class, "getIt"); expectPrivate(tested, "getIt").andReturn(value); replay(tested); assertEquals(value, tested.getValue()); verify(tested); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/annotationbased/AnnotationDemoWithSetupMethodTest.java ================================================ package samples.junit4.annotationbased; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.modules.junit4.PowerMockRunner; import samples.Service; import samples.annotationbased.AnnotationDemo; import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertEquals; import static org.powermock.api.easymock.PowerMock.replayAll; import static org.powermock.api.easymock.PowerMock.verifyAll; /** * Verifies that PowerMock test listeners works correctly with setup methods. */ @RunWith(PowerMockRunner.class) public class AnnotationDemoWithSetupMethodTest { @org.powermock.api.easymock.annotation.Mock private Service serviceMock; private AnnotationDemo tested; @Before public void setup() { tested = new AnnotationDemo(serviceMock); } @Test public void assertInjectionWorked() throws Exception { final String expected = "mock"; expect(serviceMock.getServiceMessage()).andReturn(expected); replayAll(); assertEquals(expected, tested.getServiceMessage()); verifyAll(); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/annotationbased/FinalDemoWithAnnotationInjectionAndFieldDefaulterTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.annotationbased; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.easymock.annotation.Mock; import org.powermock.core.classloader.annotations.PowerMockListener; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.core.testlisteners.FieldDefaulter; import org.powermock.modules.junit4.PowerMockRunner; import samples.finalmocking.FinalDemo; import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.powermock.api.easymock.PowerMock.replay; import static org.powermock.api.easymock.PowerMock.verify; /** * Test class to demonstrate non-static final mocking with multiple test * listeners. * */ @RunWith(PowerMockRunner.class) @PrepareForTest(FinalDemo.class) @PowerMockListener( { FieldDefaulter.class }) public class FinalDemoWithAnnotationInjectionAndFieldDefaulterTest { @SuppressWarnings("unused") // Asserts that the FieldDefaulter handles primitive types. private int intType = 6; @Mock private FinalDemo tested; @Test public void testSay() throws Exception { String expected = "Hello altered World"; expect(tested.say("hello")).andReturn("Hello altered World"); replay(tested); String actual = tested.say("hello"); verify(tested); assertEquals("Expected and actual did not match", expected, actual); // Should still be mocked by now. try { tested.say("world"); fail("Should throw AssertionError!"); } catch (AssertionError e) { assertEquals("\n Unexpected method call FinalDemo.say(\"world\"):", e.getMessage()); } } @Test public void testSayFinalNative() throws Exception { String expected = "Hello altered World"; expect(tested.sayFinalNative("hello")).andReturn("Hello altered World"); replay(tested); String actual = tested.sayFinalNative("hello"); verify(tested); assertEquals("Expected and actual did not match", expected, actual); // Should still be mocked by now. try { tested.sayFinalNative("world"); fail("Should throw AssertionError!"); } catch (AssertionError e) { assertEquals("\n Unexpected method call FinalDemo.sayFinalNative(\"world\"):", e.getMessage()); } } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/annotationbased/FinalDemoWithAnnotationInjectionTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.annotationbased; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.easymock.annotation.Mock; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.finalmocking.FinalDemo; import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.powermock.api.easymock.PowerMock.replay; import static org.powermock.api.easymock.PowerMock.verify; /** * Test class to demonstrate non-static final mocking with one listeners. * */ @RunWith(PowerMockRunner.class) @PrepareForTest(FinalDemo.class) public class FinalDemoWithAnnotationInjectionTest { @Mock private FinalDemo tested; @Test public void testSay() throws Exception { String expected = "Hello altered World"; expect(tested.say("hello")).andReturn("Hello altered World"); replay(tested); String actual = tested.say("hello"); verify(tested); assertEquals("Expected and actual did not match", expected, actual); // Should still be mocked by now. try { tested.say("world"); fail("Should throw AssertionError!"); } catch (AssertionError e) { assertEquals("\n Unexpected method call FinalDemo.say(\"world\"):", e.getMessage()); } } @Test public void testSayFinalNative() throws Exception { String expected = "Hello altered World"; expect(tested.sayFinalNative("hello")).andReturn("Hello altered World"); replay(tested); String actual = tested.sayFinalNative("hello"); verify(tested); assertEquals("Expected and actual did not match", expected, actual); // Should no longer be mocked by now. try { tested.sayFinalNative("world"); fail("Should throw AssertionError!"); } catch (AssertionError e) { assertEquals("\n Unexpected method call FinalDemo.sayFinalNative(\"world\"):", e.getMessage()); } } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/annotationbased/FinalDemoWithNiceAnnotationInjectionTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.annotationbased; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.easymock.annotation.MockNice; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.finalmocking.FinalDemo; import static org.junit.Assert.assertEquals; import static org.powermock.api.easymock.PowerMock.replay; import static org.powermock.api.easymock.PowerMock.verify; /** * Test class to demonstrate non-static final mocking with one listeners * injecting mocks to fields annotated with {@link MockNice}. */ @RunWith(PowerMockRunner.class) @PrepareForTest(FinalDemo.class) public class FinalDemoWithNiceAnnotationInjectionTest { @MockNice private FinalDemo tested; @Test public void testSay() throws Exception { String expected = null; replay(tested); String actual = tested.say("hello"); verify(tested); assertEquals("Expected and actual did not match", expected, actual); // Should still be mocked by now. String actual2 = tested.say("world"); assertEquals(expected, actual2); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/annotationbased/FinalDemoWithStrictAnnotationInjectionTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.annotationbased; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.easymock.annotation.MockNice; import org.powermock.api.easymock.annotation.MockStrict; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.finalmocking.FinalDemo; import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertEquals; import static org.powermock.api.easymock.PowerMock.replay; import static org.powermock.api.easymock.PowerMock.verify; /** * Test class to demonstrate non-static final mocking with one listeners * injecting mocks to fields annotated with {@link MockNice}. */ @RunWith(PowerMockRunner.class) @PrepareForTest(FinalDemo.class) public class FinalDemoWithStrictAnnotationInjectionTest { @MockStrict private FinalDemo tested; @Test public void testMockStrictOk() throws Exception { String expected = "Hello altered World"; expect(tested.say("hello")).andReturn(expected); expect(tested.say("hello2")).andReturn(expected); replay(tested); String actual = tested.say("hello"); String actual2 = tested.say("hello2"); verify(tested); assertEquals("Expected and actual did not match", expected, actual); assertEquals("Expected and actual did not match", expected, actual2); } @Test(expected = AssertionError.class) public void testMockStrictNotOk() throws Exception { String expected = "Hello altered World"; expect(tested.say("hello")).andReturn(expected); replay(tested); tested.say("hello2"); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/annotationbased/TestSubjectEasymockAnnotationTest.java ================================================ package samples.junit4.annotationbased; import org.easymock.Mock; import org.easymock.TestSubject; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.modules.junit4.PowerMockRunner; import samples.injectmocks.InjectDemo; import samples.injectmocks.InjectDependencyHolder; import samples.injectmocks.InjectDependencyHolderQualifier; import static org.junit.Assert.assertNotNull; /** * Asserts that {@link @TestSubject} with PowerMock and mock witch created via @org.easymock.Mock. */ @RunWith(PowerMockRunner.class) public class TestSubjectEasymockAnnotationTest { @SuppressWarnings("unused") @Mock private InjectDemo injectDemoEasymock; @TestSubject private final InjectDependencyHolder dependencyHolder = new InjectDependencyHolder(); @SuppressWarnings("unused") @Mock(fieldName = "injectDemoQualifier") private InjectDemo injectDemoQualifierEasymock; @TestSubject private final InjectDependencyHolderQualifier dependencyHolderQualifier = new InjectDependencyHolderQualifier(); @Test public void injectMocksWorksWithEasymock() { assertNotNull("dependencyHolder is null", dependencyHolder.getInjectDemo()); } @Test public void injectMocksWorksWithEasymockQualifier() { assertNotNull("dependencyHolder is null", dependencyHolderQualifier.getInjectDemoQualifier()); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/annotationbased/TestSubjectPowermockAnnotationTest.java ================================================ package samples.junit4.annotationbased; import org.easymock.TestSubject; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.easymock.annotation.Mock; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.reflect.Whitebox; import samples.injectmocks.InjectDemo; import samples.injectmocks.InjectDependencyHolder; import samples.injectmocks.InjectDependencyHolderQualifier; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.powermock.api.easymock.PowerMock.expectPrivate; import static org.powermock.api.easymock.PowerMock.replay; /** * Asserts that {@link @TestSubject} with PowerMock and mock witch created via @org.powermock.api.easymock.annotation.Mock. */ @RunWith(PowerMockRunner.class) @PrepareForTest(InjectDemo.class) public class TestSubjectPowermockAnnotationTest { @SuppressWarnings("unused") @Mock private InjectDemo injectDemoEasymock; @TestSubject private final InjectDependencyHolder dependencyHolder = new InjectDependencyHolder(); @SuppressWarnings("unused") @Mock(fieldName = "injectDemoQualifier") private InjectDemo injectDemoQualifierEasymock; @TestSubject private final InjectDependencyHolderQualifier dependencyHolderQualifier = new InjectDependencyHolderQualifier(); @Test public void should_inject_mock_without_quantifier() throws Exception { final InjectDemo tested = dependencyHolder.getInjectDemo(); assertNotNull("dependencyHolder is null", tested); String expected = "Hello altered World"; expectPrivate(tested,"say","hello").andReturn("Hello altered World"); replay(tested); String actual = Whitebox.invokeMethod(tested,"say", "hello"); assertEquals("Expected and actual did not match", expected, actual); } @Test public void should_inject_mock_with_quantifier() throws Exception { InjectDemo tested = dependencyHolderQualifier.getInjectDemoQualifier(); assertNotNull("dependencyHolderQualifier is null", tested); String expected = "Hello altered World"; expectPrivate(tested,"say","hello").andReturn("Hello altered World"); replay(tested); String actual = Whitebox.invokeMethod(tested,"say", "hello"); assertEquals("Expected and actual did not match", expected, actual); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/assume/AssumeTest.java ================================================ package samples.junit4.assume; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.modules.junit4.PowerMockRunner; import static org.junit.Assume.assumeTrue; @RunWith(PowerMockRunner.class) public class AssumeTest { @Test public void assumesWorkWithPowerMockForJUnit44() throws Exception { // When assumeTrue(false); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/classhierarchy/CommonParentTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.classhierarchy; import org.easymock.EasyMock; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.easymock.PowerMock; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.classhierarchy.ChildA; import samples.classhierarchy.ChildB; import samples.classhierarchy.Parent; import static org.junit.Assert.assertEquals; @RunWith(PowerMockRunner.class) @PrepareForTest({ChildA.class, ChildB.class, Parent.class}) public class CommonParentTest { @Test public void testPossibleToMockTwoClassesWithSameParent() throws Exception { ChildA a = PowerMock.createMock(ChildA.class); EasyMock.expect(a.getValue()).andReturn(5); PowerMock.replay(a); assertEquals(5, a.getValue()); PowerMock.verify(a); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/classwithinnermembers/ClassWithInnerMembersTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.classwithinnermembers; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.reflect.Whitebox; import samples.classwithinnermembers.ClassWithInnerMembers; import static org.junit.Assert.assertEquals; import static org.powermock.api.easymock.PowerMock.*; /** * Test PowerMock's basic support for inner (member) and local classes. */ @RunWith(PowerMockRunner.class) @PrepareForTest(ClassWithInnerMembers.class) public class ClassWithInnerMembersTest { @Test public void assertStaticMemberClassMockingWorksWithNoConstructorArguments() throws Exception { Class innerClassType = Whitebox.getInnerClassType(ClassWithInnerMembers.class, "MyInnerClass"); Object innerClassMock = createMock(innerClassType); expectNew(innerClassType).andReturn(innerClassMock); expectPrivate(innerClassMock, "doStuff").andReturn("something else"); replayAll(); assertEquals("something else", new ClassWithInnerMembers().getValue()); verifyAll(); } @Test public void assertStaticMemberClassMockingWorksWithConstructorArguments() throws Exception { Class innerClassType = Whitebox.getInnerClassType(ClassWithInnerMembers.class, "StaticInnerClassWithConstructorArgument"); Object innerClassMock = createMock(innerClassType); expectNew(innerClassType, "value").andReturn(innerClassMock); expectPrivate(innerClassMock, "doStuff").andReturn("something else"); replayAll(); assertEquals("something else", new ClassWithInnerMembers().getValueForStaticInnerClassWithConstructorArgument()); verifyAll(); } @Test public void assertLocalClassMockingWorks() throws Exception { final Class type = Whitebox.getLocalClassType(ClassWithInnerMembers.class, 1, "MyLocalClass"); Object innerClassMock = createMock(type); expectNew(type).andReturn(innerClassMock); expectPrivate(innerClassMock, "doStuff").andReturn("something else"); replayAll(); assertEquals("something else", new ClassWithInnerMembers().getLocalClassValue()); verifyAll(); } @Test public void assertLocalClassMockingWorksWithArguments() throws Exception { final Class type = Whitebox.getLocalClassType(ClassWithInnerMembers.class, 2, "MyLocalClass"); Object innerClassMock = createMock(type); expectNew(type, "my value").andReturn(innerClassMock); expectPrivate(innerClassMock, "doStuff").andReturn("something else"); replayAll(); assertEquals("something else", new ClassWithInnerMembers().getLocalClassValueWithArgument()); verifyAll(); } @Test public void assertNonStaticMemberClassMockingWorksWithArguments() throws Exception { Class innerClassType = Whitebox.getInnerClassType(ClassWithInnerMembers.class, "MyInnerClassWithConstructorArgument"); Object innerClassMock = createMock(innerClassType); expectNew(innerClassType, "value").andReturn(innerClassMock); expectPrivate(innerClassMock, "doStuff").andReturn("something else"); replayAll(); assertEquals("something else", new ClassWithInnerMembers().getValueForInnerClassWithConstructorArgument()); verifyAll(); } @Test public void assertThatAnonymousInnerClassesWorks() throws Exception { final Class type = Whitebox.getAnonymousInnerClassType(ClassWithInnerMembers.class, 1); Object innerClassMock = createMock(type); expectNew(type).andReturn(innerClassMock); expectPrivate(innerClassMock, "doStuff").andReturn("something else"); replayAll(); assertEquals("something else", new ClassWithInnerMembers().getValueForAnonymousInnerClass()); verifyAll(); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/console/ConsoleTest.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.console; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.modules.junit4.PowerMockRunner; import java.io.Console; import static org.powermock.api.easymock.PowerMock.createMock; /** * Asserts that PowerMock can mock the Console class. This failed in version 1.4 * when the DefaultFieldValueGenerator was introduced. This tests makes sure * that the DefaultFieldValueGenerator can generate default values for field * that are interfaces and abstract with no inheritable constructor. */ @RunWith(PowerMockRunner.class) public class ConsoleTest { @Test public void canMockConsole() throws Exception { createMock(Console.class); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/constructor/PrivateConstructorInstantiationDemoTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.constructor; import org.junit.Test; import samples.constructor.PrivateConstructorInstantiationDemo; import static org.junit.Assert.assertEquals; import static org.powermock.reflect.Whitebox.invokeConstructor; public class PrivateConstructorInstantiationDemoTest { @Test public void testGetState_noArgConstructor() throws Exception { final int expected = 42; PrivateConstructorInstantiationDemo tested = invokeConstructor(PrivateConstructorInstantiationDemo.class); int actual = tested.getState(); assertEquals("Expected and actual did not match.", expected, actual); } @Test public void testGetState_intConstructor() throws Exception { final int expected = 12; PrivateConstructorInstantiationDemo tested = invokeConstructor( PrivateConstructorInstantiationDemo.class, expected); int actual = tested.getState(); assertEquals("Expected and actual did not match.", expected, actual); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/constructor/PublicConstructorWithDependencyDemoTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.constructor; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.powermock.reflect.exceptions.ConstructorNotFoundException; import samples.Service; import samples.constructor.PublicConstructorWithDependencyDemo; import static org.easymock.EasyMock.createMock; import static org.junit.Assert.*; import static org.powermock.api.easymock.PowerMock.createPartialMock; /** * Verifies that error messages are correct when the constructor cannot be found * with partial mocking. This test asserts that the * http://code.google.com/p/powertest/issues/detail?id=59 has been fixed. * */ public class PublicConstructorWithDependencyDemoTest { private Service serviceMock; @Before public void setUp() { serviceMock = createMock(Service.class); } @After public void tearDown() { serviceMock = null; } /** * * @throws Exception */ @Test public void testConstructorFound() throws Exception { PublicConstructorWithDependencyDemo tested = createPartialMock(PublicConstructorWithDependencyDemo.class, new String[] { "aMethod" }, serviceMock); assertSame(serviceMock, tested.getService()); } /** * * @throws Exception */ @Test public void testConstructorNotFound() throws Exception { try { createPartialMock(PublicConstructorWithDependencyDemo.class, new String[] { "aMethod" }, serviceMock, "bad argument"); fail("Should throw ConstructorNotFoundException."); } catch (ConstructorNotFoundException e) { assertEquals("No constructor found in class '" + PublicConstructorWithDependencyDemo.class.getName() + "' with parameter types: [ " + Service.class.getName() + ", " + String.class.getName() + " ].", e.getMessage()); } } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/constructorargs/ConstructorArgsDemoTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.constructorargs; import org.easymock.ConstructorArgs; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.reflect.Whitebox; import samples.constructorargs.ConstructorArgsDemo; import java.lang.reflect.Constructor; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.powermock.api.easymock.PowerMock.*; /** * This test demonstrates the ability to invoke a specific constructor after * creating the mock object. * */ @RunWith(PowerMockRunner.class) @PrepareForTest(ConstructorArgsDemo.class) public class ConstructorArgsDemoTest { @Test public void testGetTheSecret_noConstructor() throws Exception { ConstructorArgsDemo tested = createMock(ConstructorArgsDemo.class); assertNull(Whitebox.getInternalState(tested, "secret", ConstructorArgsDemo.class)); } @Test public void testGetTheSecret_defaultConstructor() throws Exception { final Constructor constructor = ConstructorArgsDemo.class.getConstructor((Class[]) null); ConstructorArgsDemo tested = createMock(ConstructorArgsDemo.class, new ConstructorArgs(constructor)); assertEquals("default", Whitebox.getInternalState(tested, "secret", ConstructorArgsDemo.class)); } @Test public void testGetTheSecret_stringConstructor() throws Exception { final String expected = "my own secret"; ConstructorArgsDemo tested = createMock(ConstructorArgsDemo.class, expected); assertEquals(expected, Whitebox.getInternalState(tested, "secret", ConstructorArgsDemo.class)); } @Test public void testGetTheSecret_stringConstructorAndMockedPrivateSecret() throws Exception { final String originalSecret = "my own secret"; ConstructorArgsDemo tested = createPartialMock(ConstructorArgsDemo.class, new String[] { "theSecretIsPrivate" }, originalSecret); assertEquals(originalSecret, Whitebox.getInternalState(tested, "secret", ConstructorArgsDemo.class)); final String myNewSecret = "my new secret"; expectPrivate(tested, "theSecretIsPrivate").andReturn(myNewSecret); replay(tested); final String actual = tested.getTheSecret(); verify(tested); assertEquals(myNewSecret, actual); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/easymock/EasyMockAndPowerMockMixTest.java ================================================ package samples.junit4.easymock; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor; import org.powermock.modules.junit4.PowerMockRunner; import samples.Service; import samples.privatefield.SimplePrivateFieldServiceClass; import static org.easymock.EasyMock.*; import static org.junit.Assert.assertEquals; import static org.powermock.reflect.Whitebox.setInternalState; /** * This test verifies that you can mix EasyMock and PowerMock. */ @RunWith(PowerMockRunner.class) @SuppressStaticInitializationFor("samples.privatefield.SimplePrivateFieldServiceClass") public class EasyMockAndPowerMockMixTest { @Test public void testSimplePrivateFieldServiceClass() throws Exception { SimplePrivateFieldServiceClass tested = new SimplePrivateFieldServiceClass(); Service serviceMock = createMock(Service.class); setInternalState(tested, "service", serviceMock, SimplePrivateFieldServiceClass.class); final String expected = "Hello world!"; expect(serviceMock.getServiceMessage()).andReturn(expected); replay(serviceMock); final String actual = tested.useService(); verify(serviceMock); assertEquals(expected, actual); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/enummocking/EnumMockingTest.java ================================================ package samples.junit4.enummocking; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.enummocking.MyEnum; import static org.easymock.EasyMock.expect; import static org.powermock.api.easymock.PowerMock.*; @RunWith(PowerMockRunner.class) @PrepareForTest(MyEnum.class) public class EnumMockingTest { @Test public void assertMockingOfStaticMethodInEnumWorks() throws Exception { final String expected = "something else"; mockStatic(MyEnum.class); expect(MyEnum.getString()).andReturn(expected); replayAll(); final String actual = MyEnum.getString(); verifyAll(); Assert.assertEquals(expected, actual); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/equalswithgetclass/EqualsWithGetClassTest.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.equalswithgetclass; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.MockGateway; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.equalswithgetclass.EqualsWithGetClass; import static org.junit.Assert.assertTrue; import static org.powermock.api.easymock.PowerMock.createMock; import static org.powermock.api.easymock.PowerMock.replayAll; /** * Demonstrates that PowerMock ignores the call to getClass by default. * Demonstrates that issue 190 * is resolved. */ @RunWith(PowerMockRunner.class) @PrepareForTest(EqualsWithGetClass.class) public class EqualsWithGetClassTest { @Test public void callingGetClassOnAMockWorksWhenTheCallWasUnexpected() throws Exception { EqualsWithGetClass mock1 = createMock(EqualsWithGetClass.class); replayAll(); assertTrue(mock1.getClass().getName().startsWith(EqualsWithGetClass.class.getName())); } @Test(expected = AssertionError.class) public void callingGetClassOnAMockFailsWhenTheCallWasUnexpectedAndMockStandardMethodsIsSet() throws Exception { try { EqualsWithGetClass mock1 = createMock(EqualsWithGetClass.class); MockGateway.MOCK_GET_CLASS_METHOD = true; replayAll(); mock1.getClass(); } finally { MockGateway.MOCK_GET_CLASS_METHOD = false; } } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/expectnew/ExpectNewCases.java ================================================ package samples.junit4.expectnew; import org.junit.Test; import org.powermock.reflect.Whitebox; import org.powermock.reflect.exceptions.ConstructorNotFoundException; import samples.Service; import samples.expectnew.CreationException; import samples.expectnew.ExpectNewDemo; import samples.expectnew.ExpectNewServiceUser; import samples.expectnew.ITarget; import samples.expectnew.Target; import samples.expectnew.VarArgsConstructorDemo; import samples.newmocking.MyClass; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.easymock.EasyMock.aryEq; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.expectLastCall; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.powermock.api.easymock.PowerMock.createMock; import static org.powermock.api.easymock.PowerMock.expectNew; import static org.powermock.api.easymock.PowerMock.replay; import static org.powermock.api.easymock.PowerMock.verify; public abstract class ExpectNewCases { public static final String TARGET_NAME = "MyTarget"; public static final int TARGET_ID = 1; public static final String UNKNOWN_TARGET_NAME = "Unknown2"; public static final int UNKNOWN_TARGET_ID = -11; @Test public void testNewWithCheckedException() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); final String expectedFailMessage = "testing checked exception"; expectNew(MyClass.class).andThrow(new IOException(expectedFailMessage)); replay(MyClass.class); try { tested.throwExceptionAndWrapInRunTimeWhenInvoction(); fail("Should throw a checked Exception!"); } catch (RuntimeException e) { assertTrue(e.getCause() instanceof IOException); assertEquals(expectedFailMessage, e.getMessage()); } verify(MyClass.class); } @Test public void testGetMessage() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock = createMock(MyClass.class); expectNew(MyClass.class).andReturn(myClassMock); String expected = "Hello altered World"; expect(myClassMock.getMessage()).andReturn("Hello altered World"); replay(myClassMock, MyClass.class); String actual = tested.getMessage(); verify(myClassMock, MyClass.class); assertEquals("Expected and actual did not match", expected, actual); } @Test public void testGetMessageWithArgument() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock = createMock(MyClass.class); expectNew(MyClass.class).andReturn(myClassMock); String expected = "Hello altered World"; expect(myClassMock.getMessage("test")).andReturn("Hello altered World"); replay(myClassMock, MyClass.class); String actual = tested.getMessageWithArgument(); verify(myClassMock, MyClass.class); assertEquals("Expected and actual did not match", expected, actual); } @Test public void testInvokeVoidMethod() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock = createMock(MyClass.class); expectNew(MyClass.class).andReturn(myClassMock); myClassMock.voidMethod(); expectLastCall().times(1); replay(myClassMock, MyClass.class); tested.invokeVoidMethod(); verify(myClassMock, MyClass.class); } @Test public void testNewWithRuntimeException() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); final String expectedFailMessage = "testing"; expectNew(MyClass.class).andThrow(new RuntimeException(expectedFailMessage)); replay(MyClass.class); try { tested.throwExceptionWhenInvoction(); fail("Should throw RuntimeException!"); } catch (RuntimeException e) { assertEquals(expectedFailMessage, e.getMessage()); } verify(MyClass.class); } @Test public void testPreviousProblemsWithByteCodeManipulation() throws Exception { MyClass myClassMock1 = createMock(MyClass.class); expect(myClassMock1.getMessage()).andReturn("Hello"); expect(myClassMock1.getMessage()).andReturn("World"); replay(myClassMock1); assertEquals("Hello", myClassMock1.getMessage()); assertEquals("World", myClassMock1.getMessage()); verify(myClassMock1); } @Test public void testMultipleNew() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock1 = createMock(MyClass.class); MyClass myClassMock2 = createMock(MyClass.class); expectNew(MyClass.class).andReturn(myClassMock1); expectNew(MyClass.class).andReturn(myClassMock2); expect(myClassMock1.getMessage()).andReturn("Hello "); expect(myClassMock2.getMessage()).andReturn("World"); replay(myClassMock1, myClassMock2, MyClass.class); final String actual = tested.multipleNew(); verify(myClassMock1, myClassMock2, MyClass.class); assertEquals("Hello World", actual); } @Test public void testSimpleMultipleNew() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock1 = createMock(MyClass.class); expectNew(MyClass.class).andReturn(myClassMock1).times(3); replay(myClassMock1, MyClass.class); tested.simpleMultipleNew(); verify(myClassMock1, MyClass.class); } @Test public void testSimpleMultipleNew_tooManyTimesExpected() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock1 = createMock(MyClass.class); expectNew(MyClass.class).andReturn(myClassMock1).times(4); replay(myClassMock1, MyClass.class); tested.simpleMultipleNew(); try { verify(myClassMock1, MyClass.class); fail("Should throw AssertionError."); } catch (AssertionError e) { assertEquals("\n Expectation failure on verify:" + "\n samples.newmocking.MyClass(): expected: 4, actual: 3", e .getMessage()); } } @Test public void testSimpleMultipleNew_tooFewTimesExpected() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock1 = createMock(MyClass.class); expectNew(MyClass.class).andReturn(myClassMock1).times(2); replay(myClassMock1, MyClass.class); try { tested.simpleMultipleNew(); fail("Should throw AssertionError."); } catch (AssertionError e) { assertEquals("\n Unexpected constructor call samples.newmocking.MyClass():" + "\n samples.newmocking.MyClass(): expected: 2, actual: 3", e.getMessage()); } } /** * Verifies that the issue * http://code.google.com/p/powermock/issues/detail?id=10 is solved. */ @Test public void testSimpleMultipleNewPrivate_tooFewTimesExpected() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock1 = createMock(MyClass.class); expectNew(MyClass.class).andReturn(myClassMock1).times(2); replay(myClassMock1, MyClass.class); try { Whitebox.invokeMethod(tested, "simpleMultipleNewPrivate"); fail("Should throw AssertionError."); } catch (AssertionError e) { assertEquals("\n Unexpected constructor call samples.newmocking.MyClass():" + "\n samples.newmocking.MyClass(): expected: 2, actual: 3", e.getMessage()); } } @Test public void testSimpleMultipleNewPrivate_ok() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock1 = createMock(MyClass.class); expectNew(MyClass.class).andReturn(myClassMock1).times(3); replay(myClassMock1, MyClass.class); Whitebox.invokeMethod(tested, "simpleMultipleNewPrivate"); } @Test public void testSimpleSingleNew_withOnce() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock1 = createMock(MyClass.class); expectNew(MyClass.class).andReturn(myClassMock1).once(); replay(myClassMock1, MyClass.class); tested.simpleSingleNew(); verify(myClassMock1, MyClass.class); } @Test public void testSimpleSingleNew_withAtLeastOnce() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock1 = createMock(MyClass.class); expectNew(MyClass.class).andReturn(myClassMock1).atLeastOnce(); replay(myClassMock1, MyClass.class); tested.simpleSingleNew(); verify(myClassMock1, MyClass.class); } @Test public void testSimpleMultipleNew_withAtLeastOnce() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock1 = createMock(MyClass.class); expectNew(MyClass.class).andReturn(myClassMock1).atLeastOnce(); replay(myClassMock1, MyClass.class); tested.simpleMultipleNew(); verify(myClassMock1, MyClass.class); } @Test public void testSimpleMultipleNew_withRange_lowerBoundLessThan0() throws Exception { MyClass myClassMock1 = createMock(MyClass.class); try { expectNew(MyClass.class).andReturn(myClassMock1).times(-20, 2); fail("Should throw IllegalArgumentException."); } catch (IllegalArgumentException e) { assertEquals("minimum must be >= 0", e.getMessage()); } } @Test public void testSimpleMultipleNew_withRange_upperBoundLessThan0() throws Exception { MyClass myClassMock1 = createMock(MyClass.class); try { expectNew(MyClass.class).andReturn(myClassMock1).times(-1, -2); fail("Should throw IllegalArgumentException."); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().contains("<=")); } } @Test public void testSimpleMultipleNew_withRange_upperBoundLessThanLowerBound() throws Exception { MyClass myClassMock1 = createMock(MyClass.class); try { expectNew(MyClass.class).andReturn(myClassMock1).times(10, 2); fail("Should throw IllegalArgumentException."); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().contains("<=")); } } @Test public void testSimpleMultipleNew_withRange_OK() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock1 = createMock(MyClass.class); expectNew(MyClass.class).andReturn(myClassMock1).times(1, 5); replay(myClassMock1, MyClass.class); tested.simpleMultipleNew(); verify(myClassMock1, MyClass.class); } @Test public void testSimpleMultipleNew_anyTimes() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock1 = createMock(MyClass.class); expectNew(MyClass.class).andReturn(myClassMock1).anyTimes(); replay(myClassMock1, MyClass.class); tested.simpleMultipleNew(); verify(myClassMock1, MyClass.class); } @Test public void testSimpleMultipleNew_withRange_notWithinRange() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock1 = createMock(MyClass.class); expectNew(MyClass.class).andReturn(myClassMock1).times(5, 7); replay(myClassMock1, MyClass.class); tested.simpleMultipleNew(); try { verify(myClassMock1, MyClass.class); fail("Should throw AssertionError."); } catch (AssertionError e) { assertEquals("\n Expectation failure on verify:" + "\n samples.newmocking.MyClass(): expected: between 5 and 7, actual: 3", e.getMessage()); } } @Test public void testAlternativeFlow() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); expectNew(DataInputStream.class, new Object[] { null }).andThrow(new RuntimeException("error")); replay(ExpectNewDemo.class, DataInputStream.class); InputStream stream = tested.alternativePath(); verify(ExpectNewDemo.class, DataInputStream.class); assertNotNull("The returned inputstream should not be null.", stream); assertTrue("The returned inputstream should be an instance of ByteArrayInputStream.", stream instanceof ByteArrayInputStream); } @Test public void testSimpleMultipleNewPrivate_tooManyTimesExpected() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock1 = createMock(MyClass.class); expectNew(MyClass.class).andReturn(myClassMock1).times(4); replay(myClassMock1, MyClass.class); try { Whitebox.invokeMethod(tested, "simpleMultipleNewPrivate"); verify(myClassMock1, MyClass.class); fail("Should throw an exception!."); } catch (AssertionError e) { assertEquals("\n Expectation failure on verify:" + "\n samples.newmocking.MyClass(): expected: 4, actual: 3", e .getMessage()); } } @Test public void testNewWithArguments() throws Exception { final int numberOfTimes = 2; final String expected = "used"; ExpectNewDemo tested = new ExpectNewDemo(); ExpectNewServiceUser expectNewServiceImplMock = createMock(ExpectNewServiceUser.class); Service serviceMock = createMock(Service.class); expectNew(ExpectNewServiceUser.class, serviceMock, numberOfTimes).andReturn(expectNewServiceImplMock); expect(expectNewServiceImplMock.useService()).andReturn(expected); replay(expectNewServiceImplMock, serviceMock, ExpectNewServiceUser.class); assertEquals(expected, tested.newWithArguments(serviceMock, numberOfTimes)); verify(expectNewServiceImplMock, serviceMock, ExpectNewServiceUser.class); } @Test public void testNewWithVarArgs() throws Exception { final String firstString = "hello"; final String secondString = "world"; ExpectNewDemo tested = new ExpectNewDemo(); VarArgsConstructorDemo varArgsConstructorDemoMock = createMock(VarArgsConstructorDemo.class); expectNew(VarArgsConstructorDemo.class, firstString, secondString).andReturn(varArgsConstructorDemoMock); expect(varArgsConstructorDemoMock.getAllMessages()).andReturn(new String[] { firstString, secondString }); replay(VarArgsConstructorDemo.class, varArgsConstructorDemoMock); String[] varArgs = tested.newVarArgs(firstString, secondString); assertEquals(2, varArgs.length); assertEquals(firstString, varArgs[0]); assertEquals(secondString, varArgs[1]); verify(VarArgsConstructorDemo.class, varArgsConstructorDemoMock); } @Test public void testNewWhenTheExpectedConstructorIsNotFound() throws Exception { final Object object = new Object(); try { expectNew(VarArgsConstructorDemo.class, object); fail("Should throw ConstructorNotFoundException!"); } catch (ConstructorNotFoundException e) { assertEquals("No constructor found in class '" + VarArgsConstructorDemo.class.getName() + "' with parameter types: [ " + object.getClass().getName() + " ].", e.getMessage()); } } @Test public void testNewWithVarArgsConstructorWhenOneArgumentIsOfASubType() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); Service serviceMock = createMock(Service.class); VarArgsConstructorDemo varArgsConstructorDemoMock = createMock(VarArgsConstructorDemo.class); final Service serviceSubTypeInstance = new Service() { public String getServiceMessage() { return "message"; } }; expectNew(VarArgsConstructorDemo.class, serviceSubTypeInstance, serviceMock).andReturn(varArgsConstructorDemoMock); expect(varArgsConstructorDemoMock.getAllServices()).andReturn(new Service[] { serviceMock }); replay(serviceMock, VarArgsConstructorDemo.class, varArgsConstructorDemoMock); Service[] varArgs = tested.newVarArgs(serviceSubTypeInstance, serviceMock); assertEquals(1, varArgs.length); assertSame(serviceMock, varArgs[0]); verify(serviceMock, VarArgsConstructorDemo.class, varArgsConstructorDemoMock); } @Test public void testNewWithArrayVarArgs() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); VarArgsConstructorDemo varArgsConstructorDemoMock = createMock(VarArgsConstructorDemo.class); final byte[] byteArrayOne = new byte[] { 42 }; final byte[] byteArrayTwo = new byte[] { 17 }; expectNew(VarArgsConstructorDemo.class, byteArrayOne, byteArrayTwo).andReturn(varArgsConstructorDemoMock); expect(varArgsConstructorDemoMock.getByteArrays()).andReturn(new byte[][] { byteArrayOne }); replay(VarArgsConstructorDemo.class, varArgsConstructorDemoMock); byte[][] varArgs = tested.newVarArgs(byteArrayOne, byteArrayTwo); assertEquals(1, varArgs.length); assertSame(byteArrayOne, varArgs[0]); verify(VarArgsConstructorDemo.class, varArgsConstructorDemoMock); } @Test public void testNewWithArrayVarArgsAndMatchers() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); VarArgsConstructorDemo varArgsConstructorDemoMock = createMock(VarArgsConstructorDemo.class); final byte[] byteArrayOne = new byte[] { 42 }; final byte[] byteArrayTwo = new byte[] { 17 }; expectNew(VarArgsConstructorDemo.class, aryEq(byteArrayOne), aryEq(byteArrayTwo)).andReturn(varArgsConstructorDemoMock); expect(varArgsConstructorDemoMock.getByteArrays()).andReturn(new byte[][] { byteArrayOne }); replay(VarArgsConstructorDemo.class, varArgsConstructorDemoMock); byte[][] varArgs = tested.newVarArgsWithMatchers(); assertEquals(1, varArgs.length); assertSame(byteArrayOne, varArgs[0]); verify(VarArgsConstructorDemo.class, varArgsConstructorDemoMock); } @Test public void testNewWithArrayVarArgsWhenFirstArgumentIsNullAndSubseqentArgumentsAreNotNull() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); VarArgsConstructorDemo varArgsConstructorDemoMock = createMock(VarArgsConstructorDemo.class); final byte[] byteArrayOne = null; final byte[] byteArrayTwo = new byte[] { 17 }; expectNew(VarArgsConstructorDemo.class, byteArrayOne, byteArrayTwo).andReturn(varArgsConstructorDemoMock); expect(varArgsConstructorDemoMock.getByteArrays()).andReturn(new byte[][] { byteArrayTwo }); replay(VarArgsConstructorDemo.class, varArgsConstructorDemoMock); byte[][] varArgs = tested.newVarArgs(byteArrayOne, byteArrayTwo); assertEquals(1, varArgs.length); assertSame(byteArrayTwo, varArgs[0]); verify(VarArgsConstructorDemo.class, varArgsConstructorDemoMock); } @Test public void testNewWithArrayVarArgsWhenFirstArgumentIsNotNullButSubseqentArgumentsAreNull() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); VarArgsConstructorDemo varArgsConstructorDemoMock = createMock(VarArgsConstructorDemo.class); final byte[] byteArrayOne = new byte[] { 42 }; final byte[] byteArrayTwo = null; expectNew(VarArgsConstructorDemo.class, byteArrayOne, byteArrayTwo).andReturn(varArgsConstructorDemoMock); expect(varArgsConstructorDemoMock.getByteArrays()).andReturn(new byte[][] { byteArrayOne }); replay(VarArgsConstructorDemo.class, varArgsConstructorDemoMock); byte[][] varArgs = tested.newVarArgs(byteArrayOne, byteArrayTwo); assertEquals(1, varArgs.length); assertSame(byteArrayOne, varArgs[0]); verify(VarArgsConstructorDemo.class, varArgsConstructorDemoMock); } @Test public void testNewWithArrayVarArgsWhenFirstArgumentIsNullSecondArgumentIsNotNullAndThirdArgumentIsNull() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); VarArgsConstructorDemo varArgsConstructorDemoMock = createMock(VarArgsConstructorDemo.class); final byte[] byteArrayOne = null; final byte[] byteArrayTwo = new byte[] { 42 }; final byte[] byteArrayThree = null; expectNew(VarArgsConstructorDemo.class, byteArrayOne, byteArrayTwo, byteArrayThree).andReturn(varArgsConstructorDemoMock); expect(varArgsConstructorDemoMock.getByteArrays()).andReturn(new byte[][] { byteArrayTwo }); replay(VarArgsConstructorDemo.class, varArgsConstructorDemoMock); byte[][] varArgs = tested.newVarArgs(byteArrayOne, byteArrayTwo, byteArrayThree); assertEquals(1, varArgs.length); assertSame(byteArrayTwo, varArgs[0]); verify(VarArgsConstructorDemo.class, varArgsConstructorDemoMock); } @Test public void testNewWithArrayVarArgsWhenAllArgumentsAreNull() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); VarArgsConstructorDemo varArgsConstructorDemoMock = createMock(VarArgsConstructorDemo.class); final byte[] byteArrayOne = null; final byte[] byteArrayTwo = null; expectNew(VarArgsConstructorDemo.class, byteArrayOne, byteArrayTwo).andReturn(varArgsConstructorDemoMock); expect(varArgsConstructorDemoMock.getByteArrays()).andReturn(new byte[][] { byteArrayTwo }); replay(VarArgsConstructorDemo.class, varArgsConstructorDemoMock); byte[][] varArgs = tested.newVarArgs(byteArrayOne, byteArrayTwo); assertEquals(1, varArgs.length); assertSame(byteArrayTwo, varArgs[0]); verify(VarArgsConstructorDemo.class, varArgsConstructorDemoMock); } @Test public void testNewWithWrongArgument() throws Exception { final int numberOfTimes = 2; final String expected = "used"; ExpectNewDemo tested = new ExpectNewDemo(); ExpectNewServiceUser expectNewServiceImplMock = createMock(ExpectNewServiceUser.class); Service serviceMock = createMock(Service.class); expectNew(ExpectNewServiceUser.class, serviceMock, numberOfTimes).andReturn(expectNewServiceImplMock); expect(expectNewServiceImplMock.useService()).andReturn(expected); replay(expectNewServiceImplMock, serviceMock, ExpectNewServiceUser.class); try { assertEquals(expected, tested.newWithWrongArguments(serviceMock, numberOfTimes)); verify(expectNewServiceImplMock, serviceMock, ExpectNewServiceUser.class); fail("Should throw AssertionError!"); } catch (AssertionError e) { assertEquals( "\n Unexpected constructor call samples.expectnew.ExpectNewServiceUser(EasyMock for interface samples.Service, 4 (int)):" + "\n samples.expectnew.ExpectNewServiceUser(EasyMock for interface samples.Service, 2 (int)): expected: 1, actual: 0", e.getMessage()); } } @Test public void testExpectNewButNoNewCallWasMade() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock1 = createMock(MyClass.class); expectNew(MyClass.class).andReturn(myClassMock1).once(); replay(myClassMock1, MyClass.class); try { tested.makeDate(); verify(myClassMock1, MyClass.class); fail("Should throw AssertionError!"); } catch (AssertionError e) { assertTrue(e.getMessage().contains(MyClass.class.getName() + "(): expected: 1, actual: 0")); } } @Test public void canDefineSeveralMockResultForNew() throws Exception { final Target expectedTarget = new Target(UNKNOWN_TARGET_NAME, UNKNOWN_TARGET_ID); expectNew(Target.class, TARGET_NAME, TARGET_ID).andThrow(new CreationException()); expectNew(Target.class, "Unknown",-1).andReturn(expectedTarget); replay(Target.class); Target actualTarget = new ExpectNewDemo().createTarget(new ITarget() { @Override public int getId() { return TARGET_ID; } @Override public String getName() { return TARGET_NAME; } }); assertThat(actualTarget).isEqualToComparingFieldByField(expectedTarget); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/expectnew/ExpectNewDemoTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.expectnew; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.expectnew.ExpectNewDemo; import samples.newmocking.MyClass; import java.io.DataInputStream; /** * Test class to demonstrate new instance mocking using expectNew(..). * */ @RunWith(PowerMockRunner.class) @PrepareForTest( { MyClass.class, ExpectNewDemo.class, DataInputStream.class }) public class ExpectNewDemoTest extends ExpectNewCases { } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/expectnew/ExpectNewOfFinalSystemClassTest.java ================================================ package samples.junit4.expectnew; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.expectnew.ExpectNewOfFinalSystemClassDemo; import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertEquals; import static org.powermock.api.easymock.PowerMock.*; @RunWith(PowerMockRunner.class) @PrepareForTest(ExpectNewOfFinalSystemClassDemo.class) public class ExpectNewOfFinalSystemClassTest { @Test public void assertThatExpectNewWorksForFinalSystemClasses() throws Exception { String mock = createMock(String.class); expectNew(String.class, "My String").andReturn(mock); expect(mock.charAt(0)).andReturn('o'); replayAll(); assertEquals('o', new ExpectNewOfFinalSystemClassDemo().getFirstChar()); verifyAll(); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/expectnew/MockDateTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.expectnew; import junit.framework.Assert; import org.easymock.EasyMock; import org.easymock.internal.MocksControl; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.easymock.PowerMock; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.expectnew.ExpectNewDemo; import java.util.Date; @RunWith(PowerMockRunner.class) @PrepareForTest( { ExpectNewDemo.class }) public class MockDateTest { @Test public void testMockDate() throws Exception { Date someDate = new Date(); Date date = PowerMock.createMock(Date.class); EasyMock.expect(date.after(someDate)).andReturn(false); PowerMock.replay(date); date.after(someDate); PowerMock.verify(date); } @Test public void testMockDateWithEasyMock() throws Exception { Date someDate = new Date(); MocksControl c = (MocksControl) org.easymock.EasyMock.createControl(); Date date = c.createMock(Date.class); EasyMock.expect(date.after(someDate)).andReturn(false); PowerMock.replay(date); date.after(someDate); PowerMock.verify(date); } @Test(expected = IllegalStateException.class) public void testMockDateWithEasyMockFails() { Date someDate = new Date(); MocksControl c = (MocksControl) org.easymock.EasyMock.createControl(); Date date = c.createMock(null, Date.class, null); EasyMock.expect(date.after(someDate)).andReturn(false); Assert.fail("EasyMock with no methods mocked should not be possible to mock"); } @Test public void testExpectNewDate() throws Exception { Date someDate = new Date(); long time = someDate.getTime(); PowerMock.expectNew(Date.class).andReturn(someDate); PowerMock.replay(Date.class); Assert.assertEquals(time, new ExpectNewDemo().makeDate().getTime()); PowerMock.verify(Date.class); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/expectnew/PrimitiveAndWrapperDemoTest.java ================================================ package samples.junit4.expectnew; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.reflect.exceptions.TooManyConstructorsFoundException; import samples.expectnew.PrimitiveAndWrapperDemo; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import static org.junit.matchers.JUnitMatchers.containsString; import static org.powermock.api.easymock.PowerMock.createMockAndExpectNew; /** * Unit test for the {@link PrimitiveAndWrapperDemo} class. */ @RunWith(PowerMockRunner.class) public class PrimitiveAndWrapperDemoTest { @Test public void testWhenConstructorCannotBeDetermined() throws Exception { try { createMockAndExpectNew(PrimitiveAndWrapperDemo.class, 2); fail("Should throw TooManyConstructorsFoundException"); } catch (TooManyConstructorsFoundException e) { assertThat(e.getMessage(), containsString("Several matching constructors found, please specify the argument parameter types so that PowerMock can determine which method you're referring to." + "\nMatching constructors in class samples.expectnew.PrimitiveAndWrapperDemo were:\n")); assertThat(e.getMessage(), containsString("samples.expectnew.PrimitiveAndWrapperDemo( java.lang.Integer.class )\n")); assertThat(e.getMessage(), containsString("samples.expectnew.PrimitiveAndWrapperDemo( int.class )\n")); } } @Test public void testWrapperConstructor() throws Exception { createMockAndExpectNew(PrimitiveAndWrapperDemo.class, new Class[] { Integer.class }, 2); } @Test public void testPrimitiveConstructor() throws Exception { createMockAndExpectNew(PrimitiveAndWrapperDemo.class, new Class[] { int.class }, 2); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/expectnew/PrimitiveAndWrapperUserTest.java ================================================ package samples.junit4.expectnew; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.expectnew.PrimitiveAndWrapperDemo; import samples.expectnew.PrimitiveAndWrapperUser; import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertEquals; import static org.powermock.api.easymock.PowerMock.*; /** * Unit test for the {@link PrimitiveAndWrapperUser} class. */ @RunWith(PowerMockRunner.class) @PrepareForTest(PrimitiveAndWrapperUser.class) public class PrimitiveAndWrapperUserTest { @Test public void testNewWithStrictMocking_ok() throws Exception { PrimitiveAndWrapperDemo mock1 = createStrictMockAndExpectNew(PrimitiveAndWrapperDemo.class, new Class[] { Integer.class }, 42); PrimitiveAndWrapperDemo mock2 = createStrictMockAndExpectNew(PrimitiveAndWrapperDemo.class, new Class[] { int.class }, 21); expect(mock1.getMyInt()).andReturn(10); expect(mock2.getMyInt()).andReturn(21); replayAll(); assertEquals(31, new PrimitiveAndWrapperUser().useThem()); verifyAll(); } @Test(expected = AssertionError.class) public void testNewWithStrictMocking_notOk() throws Exception { PrimitiveAndWrapperDemo mock2 = createStrictMockAndExpectNew(PrimitiveAndWrapperDemo.class, new Class[] { int.class }, 21); PrimitiveAndWrapperDemo mock1 = createStrictMockAndExpectNew(PrimitiveAndWrapperDemo.class, new Class[] { Integer.class }, 42); expect(mock1.getMyInt()).andReturn(10); expect(mock2.getMyInt()).andReturn(21); replayAll(); assertEquals(31, new PrimitiveAndWrapperUser().useThem()); verifyAll(); } @Test public void testNewWithNiceMocking() throws Exception { PrimitiveAndWrapperDemo mock = createNiceMockAndExpectNew(PrimitiveAndWrapperDemo.class, new Class[] { Integer.class }, 42); expect(mock.getMyInt()).andReturn(2); replayAll(); assertEquals(2, new PrimitiveAndWrapperUser().useThem()); verifyAll(); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/expectvoid/ExpectVoidDemoTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.expectvoid; import org.easymock.EasyMock; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.reflect.Whitebox; import samples.expectvoid.ExpectVoidDemo; import static org.powermock.api.easymock.PowerMock.*; @RunWith(PowerMockRunner.class) @PrepareForTest(ExpectVoidDemo.class) public class ExpectVoidDemoTest { @Test public void testInvokeAPrivateVoidMethod() throws Exception { final String methodToMock = "privateInvoke"; ExpectVoidDemo tested = createPartialMock(ExpectVoidDemo.class, methodToMock); final int expected = 112; expectPrivate(tested, methodToMock, expected).times(1); replay(tested); tested.invokeAPrivateVoidMethod(expected); verify(tested); } @Test public void testInvokeAPrivateVoidMethod_usingPowerMockExpectLastCall() throws Exception { final String methodToMock = "privateInvoke"; ExpectVoidDemo tested = createPartialMock(ExpectVoidDemo.class, methodToMock); final int expected = 112; Whitebox.invokeMethod(tested, methodToMock, expected); expectLastCall().times(1); replay(tested); tested.invokeAPrivateVoidMethod(expected); verify(tested); } @Test public void testInvokeAPrivateVoidMethod_usingEasyMockExpectLastCall() throws Exception { final String methodToMock = "privateInvoke"; ExpectVoidDemo tested = createPartialMock(ExpectVoidDemo.class, methodToMock); final int expected = 112; Whitebox.invokeMethod(tested, methodToMock, expected); EasyMock.expectLastCall(); replay(tested); tested.invokeAPrivateVoidMethod(expected); verify(tested); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/finalmocking/FinalDemoTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.finalmocking; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.finalmocking.FinalDemo; import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.powermock.api.easymock.PowerMock.*; /** * Test class to demonstrate non-static final mocking. */ @RunWith(PowerMockRunner.class) @PrepareForTest(FinalDemo.class) public class FinalDemoTest { @Test public void testSay() throws Exception { FinalDemo tested = createMock(FinalDemo.class); String expected = "Hello altered World"; expect(tested.say("hello")).andReturn("Hello altered World"); replay(tested); String actual = tested.say("hello"); verify(tested); assertEquals("Expected and actual did not match", expected, actual); // Should still be mocked by now. try { tested.say("world"); fail("Should throw AssertionError!"); } catch (AssertionError e) { assertEquals("\n Unexpected method call FinalDemo.say(\"world\"):", e.getMessage()); } } @Test public void testSayFinalNative() throws Exception { FinalDemo tested = createMock(FinalDemo.class); String expected = "Hello altered World"; expect(tested.sayFinalNative("hello")).andReturn("Hello altered World"); replay(tested); String actual = tested.sayFinalNative("hello"); verify(tested); assertEquals("Expected and actual did not match", expected, actual); // Should still be mocked by now. try { tested.sayFinalNative("world"); fail("Should throw AssertionError!"); } catch (AssertionError e) { assertEquals("\n Unexpected method call FinalDemo.sayFinalNative(\"world\"):", e.getMessage()); } } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/finalmocking/MockingOfInstanceMethodsInFinalSystemClassTest.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.finalmocking; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertEquals; import static org.powermock.api.easymock.PowerMock.*; /** * Test class to demonstrate non-static final mocking of instance methods in * system classes. */ @RunWith(PowerMockRunner.class) @PrepareForTest(MockingOfInstanceMethodsInFinalSystemClassTest.class) public class MockingOfInstanceMethodsInFinalSystemClassTest { @Test public void assertThatMockingOfInstanceMethodsInFinalSystemClassesWorks() throws Exception { Long tested = createMock(Long.class); expect(tested.longValue()).andReturn(22L); replayAll(); assertEquals(22L, tested.longValue()); verifyAll(); } @Test public void assertThatMockingOfInstanceMethodsInStringWorks() throws Exception { String tested = createMock(String.class); expect(tested.charAt(2)).andReturn('A'); replayAll(); assertEquals('A', tested.charAt(2)); verifyAll(); } @Test public void assertThatPartialMockingOfInstanceMethodsInFinalSystemClassesWhenNotInvokingConstructorWorks() throws Exception { Long tested = createPartialMock(Long.class, "doubleValue"); expect(tested.doubleValue()).andReturn(54d); replayAll(); assertEquals(0, tested.longValue()); assertEquals(54d, tested.doubleValue(), 0.0d); verifyAll(); } @Test public void assertThatPartialMockingOfInstanceMethodsInFinalSystemClassesWhenNotInvokingNonDefaultConstructorWorks() throws Exception { Long tested = createPartialMock(Long.class, new String[] { "doubleValue" }, 27L); expect(tested.doubleValue()).andReturn(54d); replayAll(); assertEquals(27L, tested.longValue()); assertEquals(54d, tested.doubleValue(), 0.0d); verifyAll(); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/finalmocking/NoDuplicateTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.finalmocking; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.finalmocking.FinalDemo; import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.powermock.api.easymock.PowerMock.*; /** * This test demonstrates that the issue at * http://code.google.com/p/powertest/issues/detail?id=63 is solved. * *

* The bug was that if there were only one test case and the * {@code @PrepareForTest} annotation was placed at the test method instead * of the class the PowerMock JUnit runner would detect an extra test case. * */ @RunWith(PowerMockRunner.class) public class NoDuplicateTest { @Test @PrepareForTest(FinalDemo.class) public void assertThatPrepareForTestAnnotationAtMethodLevelButNotClassLevelWorks() throws Exception { FinalDemo tested = createMock(FinalDemo.class); String expected = "Hello altered World"; expect(tested.say("hello")).andReturn("Hello altered World"); replay(tested); String actual = tested.say("hello"); verify(tested); assertEquals("Expected and actual did not match", expected, actual); // Should still be mocked by now. try { tested.say("world"); fail("Should throw AssertionError!"); } catch (AssertionError e) { assertEquals("\n Unexpected method call FinalDemo.say(\"world\"):", e.getMessage()); } } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/hashcode/PowerMockUsesIdentityHashMapToStoreMocks.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.hashcode; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.modules.junit4.PowerMockRunner; import samples.hashcode.HashCodeInitializedInCtor; import static org.powermock.api.easymock.PowerMock.createMock; @RunWith(PowerMockRunner.class) public class PowerMockUsesIdentityHashMapToStoreMocks { @Test public void storesObjectsToAutomaticallyReplayAndVerifyToAnIdentityHashMap()throws Exception { createMock(HashCodeInitializedInCtor.class); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/interfacefieldchange/ChangeValueOfStaticFinalFieldInInterfacesDefect.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.interfacefieldchange; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.reflect.Whitebox; import samples.interfacefieldchange.InterfaceWithStaticFinalField; import static org.junit.Assert.assertEquals; /** * This test asserts that it's possible for PowerMock to modify static final * fields in Interfaces. */ @RunWith(PowerMockRunner.class) @PrepareForTest( { InterfaceWithStaticFinalField.class }) public class ChangeValueOfStaticFinalFieldInInterfacesDefect { @Test public void assertThatStaticFinalFieldValuesInInterfacesAreChangable() throws Exception { final String value = "new value"; Whitebox.setInternalState(InterfaceWithStaticFinalField.class, value); assertEquals(value, Whitebox.getInternalState(InterfaceWithStaticFinalField.class, String.class)); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/java/MockClassesInsideJavaPackage.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.java; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.java.ClassInsideJavaPackage; import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertEquals; import static org.powermock.api.easymock.PowerMock.*; @RunWith(PowerMockRunner.class) @PrepareForTest(ClassInsideJavaPackage.class) public class MockClassesInsideJavaPackage { @Test public void allowsMockingOfClassesInsidePackageContainingJava() { ClassInsideJavaPackage mock = createMock(ClassInsideJavaPackage.class); expect(mock.mockMe()).andReturn("mocked"); replayAll(); assertEquals("mocked", mock.mockMe()); verifyAll(); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/largemethod/LargeMethodTest.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package samples.junit4.largemethod; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.largemethod.MethodExceedingJvmLimit; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertNull; import static junit.framework.Assert.assertSame; import static junit.framework.Assert.assertTrue; import static junit.framework.Assert.fail; import static org.easymock.EasyMock.expect; import static org.powermock.api.easymock.PowerMock.method; import static org.powermock.api.easymock.PowerMock.mockStatic; import static org.powermock.api.easymock.PowerMock.replayAll; import static org.powermock.api.easymock.PowerMock.suppress; @RunWith(PowerMockRunner.class) @PrepareForTest(MethodExceedingJvmLimit.class) public class LargeMethodTest { @Test public void largeMethodShouldBeOverridden() { try { MethodExceedingJvmLimit.init(); fail("Method should be overridden and exception should be thrown"); } catch (Exception e) { assertSame(IllegalAccessException.class, e.getClass()); assertTrue(e.getMessage().contains("Method was too large and after instrumentation exceeded JVM limit")); } } @Test public void largeMethodShouldBeAbleToBeSuppressed() { suppress(method(MethodExceedingJvmLimit.class, "init")); assertNull("Suppressed method should return: null", MethodExceedingJvmLimit.init()); } @Test public void largeMethodShouldBeAbleToBeMocked() { mockStatic(MethodExceedingJvmLimit.class); expect(MethodExceedingJvmLimit.init()).andReturn("ok"); replayAll(); assertEquals("Mocked method should return: ok", "ok", MethodExceedingJvmLimit.init()); } @Test(expected = IllegalStateException.class) public void largeMethodShouldBeAbleToBeMockedAndThrowException() { mockStatic(MethodExceedingJvmLimit.class); expect(MethodExceedingJvmLimit.init()).andThrow(new IllegalStateException()); replayAll(); MethodExceedingJvmLimit.init(); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/misc/PrivateInnerInterfacesInTestClassTest.java ================================================ package samples.junit4.misc; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import static org.junit.Assert.assertEquals; @RunWith(PowerMockRunner.class) @PrepareForTest( { PrivateInnerInterfacesInTestClassTest.class }) public class PrivateInnerInterfacesInTestClassTest { @Test public void privateInterfacesCanBeLoadedAndBytcodeManipulatedByPowerMock() throws Exception { InnerInterface innerInterface = new InnerInterface() { public String aMethod() { return "ok"; } }; assertEquals("ok", innerInterface.aMethod()); } private interface InnerInterface { String aMethod(); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/mockpolicy/MockPolicyUsageExampleTest.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.mockpolicy; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.MockPolicy; import org.powermock.core.spi.PowerMockPolicy; import org.powermock.mockpolicies.MockPolicyClassLoadingSettings; import org.powermock.mockpolicies.MockPolicyInterceptionSettings; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.reflect.Whitebox; import samples.mockpolicy.ResultCalculator; import samples.mockpolicy.SomeClassWithAMethod; import java.lang.reflect.Method; import static org.junit.Assert.assertEquals; /** * A simple example of a mock policy that stubs out a method call. */ @RunWith(PowerMockRunner.class) @MockPolicy(MockPolicyExample.class) public class MockPolicyUsageExampleTest { @Test public void exampleOfStubbingOutCallsInParentClass() throws Exception { SomeClassWithAMethod tested = new SomeClassWithAMethod(); assertEquals(8.0d, tested.getResult(), 0.0d); } } class MockPolicyExample implements PowerMockPolicy { @Override public void applyClassLoadingPolicy(MockPolicyClassLoadingSettings settings) { settings.addFullyQualifiedNamesOfClassesToLoadByMockClassloader(ResultCalculator.class.getName()); } @Override public void applyInterceptionPolicy(MockPolicyInterceptionSettings settings) { Method calculateMethod = Whitebox.getMethod(ResultCalculator.class, "calculate"); settings.stubMethod(calculateMethod, 4d); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/mockpolicy/MockPolicyWithExpectationsTest.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.mockpolicy; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.MockPolicy; import org.powermock.core.spi.PowerMockPolicy; import org.powermock.mockpolicies.MockPolicyClassLoadingSettings; import org.powermock.mockpolicies.MockPolicyInterceptionSettings; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.reflect.Whitebox; import samples.mockpolicy.ResultCalculator; import samples.mockpolicy.SimpleClassWithADependency; import java.lang.reflect.Method; import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertEquals; import static org.powermock.api.easymock.PowerMock.*; @RunWith(PowerMockRunner.class) @MockPolicy(MockPolicyExpectationsExample.class) public class MockPolicyWithExpectationsTest { @Test public void mockPolicyWithExpectationsWorks() throws Exception { final SimpleClassWithADependency tested = new SimpleClassWithADependency(); Whitebox.setInternalState(tested, new ResultCalculator(5)); assertEquals(2.0, tested.getResult(), 0.0); verifyAll(); } } class MockPolicyExpectationsExample implements PowerMockPolicy { @Override public void applyClassLoadingPolicy(MockPolicyClassLoadingSettings settings) { settings.addFullyQualifiedNamesOfClassesToLoadByMockClassloader(ResultCalculator.class.getName()); } @Override public void applyInterceptionPolicy(MockPolicyInterceptionSettings settings) { final ResultCalculator calculatorMock = createMock(ResultCalculator.class); expect(calculatorMock.calculate()).andReturn(2.0); replay(calculatorMock); Method calculateMethod = Whitebox.getMethod(ResultCalculator.class, "calculate"); settings.stubMethod(calculateMethod, calculatorMock.calculate()); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/mockpolicy/MockPolicyWithInvocationHandlerTest.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.mockpolicy; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.MockPolicy; import org.powermock.core.spi.PowerMockPolicy; import org.powermock.mockpolicies.MockPolicyClassLoadingSettings; import org.powermock.mockpolicies.MockPolicyInterceptionSettings; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.reflect.Whitebox; import samples.mockpolicy.ResultCalculator; import samples.mockpolicy.SimpleClassWithADependency; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import static org.junit.Assert.assertEquals; import static org.powermock.api.easymock.PowerMock.verifyAll; import static org.powermock.api.support.membermodification.MemberMatcher.method; @RunWith(PowerMockRunner.class) @MockPolicy(MockPolicyInvocationHandlerExample.class) public class MockPolicyWithInvocationHandlerTest { @Test public void mockPolicyWithInvocationHandlerWorks() { final SimpleClassWithADependency tested = new SimpleClassWithADependency(); Whitebox.setInternalState(tested, new ResultCalculator(0)); assertEquals(1.0, tested.getResult(), 0.0); verifyAll(); } } class MockPolicyInvocationHandlerExample implements PowerMockPolicy { @Override public void applyClassLoadingPolicy(MockPolicyClassLoadingSettings settings) { settings.addFullyQualifiedNamesOfClassesToLoadByMockClassloader(ResultCalculator.class.getName()); } @Override public void applyInterceptionPolicy(MockPolicyInterceptionSettings settings) { settings.proxyMethod(method(ResultCalculator.class, "calculate"), new InvocationHandler() { @Override public Object invoke(Object object, Method method, Object[] args) throws Throwable { final double result = (Double) method.invoke(object, args); return result + 1.0; } }); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/mockpolicy/frameworkexample/SimpleFrameworkMockPolicy.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.mockpolicy.frameworkexample; import org.powermock.core.spi.PowerMockPolicy; import org.powermock.mockpolicies.MockPolicyClassLoadingSettings; import org.powermock.mockpolicies.MockPolicyInterceptionSettings; import org.powermock.reflect.Whitebox; import samples.mockpolicy.frameworkexample.NativeResult; import samples.mockpolicy.frameworkexample.SimpleFramework; import java.lang.reflect.Method; public class SimpleFrameworkMockPolicy implements PowerMockPolicy { public static final String NATIVE_RESULT_VALUE = "result"; @Override public void applyClassLoadingPolicy(MockPolicyClassLoadingSettings settings) { settings.addStaticInitializersToSuppress("samples.mockpolicy.frameworkexample.SimpleFramework"); } @Override public void applyInterceptionPolicy(MockPolicyInterceptionSettings settings) { final Method doNativeStuffMethod = Whitebox.getMethod(SimpleFramework.class, String.class); NativeResult nativeResult = new NativeResult(NATIVE_RESULT_VALUE); settings.stubMethod(doNativeStuffMethod, nativeResult); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/mockpolicy/frameworkexample/SimpleFrameworkUserTest.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.mockpolicy.frameworkexample; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.MockPolicy; import org.powermock.modules.junit4.PowerMockRunner; import samples.mockpolicy.frameworkexample.SimpleFrameworkUser; import static org.junit.Assert.assertEquals; @RunWith(PowerMockRunner.class) @MockPolicy(SimpleFrameworkMockPolicy.class) public class SimpleFrameworkUserTest { @Test public void testPerformComplexOperation() { SimpleFrameworkUser tested = new SimpleFrameworkUser(); assertEquals(SimpleFrameworkMockPolicy.NATIVE_RESULT_VALUE, tested.performComplexOperation("some complex stuff")); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/multireplayverify/MultiReplayVerifyTest.java ================================================ package samples.junit4.multireplayverify; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.expectnew.ExpectNewDemo; import samples.newmocking.MyClass; import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertEquals; import static org.powermock.api.easymock.PowerMock.*; /** * Asserts that it's ok the manually replay a mock and then use replayAll(). The * same regards verify and verifyAll. */ @RunWith(PowerMockRunner.class) @PrepareForTest(ExpectNewDemo.class) public class MultiReplayVerifyTest { @Test public void replyFollowedByReplayAllIsAllowed() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock = createMock(MyClass.class); expectNew(MyClass.class).andReturn(myClassMock); String expected = "Hello altered World"; expect(myClassMock.getMessage()).andReturn("Hello altered World"); replay(MyClass.class); replayAll(); String actual = tested.getMessage(); verifyAll(); assertEquals("Expected and actual did not match", expected, actual); } @Test public void verifyFollowedByVerifyAllIsAllowed() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock = createMock(MyClass.class); expectNew(MyClass.class).andReturn(myClassMock); String expected = "Hello altered World"; expect(myClassMock.getMessage()).andReturn("Hello altered World"); replayAll(); String actual = tested.getMessage(); verify(MyClass.class); verifyAll(); assertEquals("Expected and actual did not match", expected, actual); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/nativemocking/NativeMockingSampleTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.nativemocking; import org.junit.Test; import samples.nativemocking.NativeMockingSample; import samples.nativemocking.NativeService; import static org.easymock.EasyMock.*; import static org.junit.Assert.assertEquals; /** * This test demonstrates that it's possible to mock native methods using plain * EasyMock class extensions. */ public class NativeMockingSampleTest { @Test public void testMockNative() throws Exception { NativeService nativeServiceMock = createMock(NativeService.class); NativeMockingSample tested = new NativeMockingSample(nativeServiceMock); final String expectedParameter = "question"; final String expectedReturnValue = "answer"; expect(nativeServiceMock.invokeNative(expectedParameter)).andReturn(expectedReturnValue); replay(nativeServiceMock); assertEquals(expectedReturnValue, tested.invokeNativeMethod(expectedParameter)); verify(nativeServiceMock); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/newmocking/StupidNewTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.newmocking; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.newmocking.MyClass; import samples.newmocking.StupidNew; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.expectLastCall; import static org.junit.Assert.assertEquals; import static org.powermock.api.easymock.PowerMock.*; /** * Test class to demonstrate new instance mocking. * * @author Johan Haleby */ @RunWith(PowerMockRunner.class) @PrepareForTest( { MyClass.class, StupidNew.class }) public class StupidNewTest { @Test public void testGetMessage() throws Exception { StupidNew tested = new StupidNew(); MyClass myClassMock = createMockAndExpectNew(MyClass.class); String expected = "Hello altered World"; expect(myClassMock.getMessage()).andReturn("Hello altered World"); replay(myClassMock, MyClass.class); String actual = tested.getMessage(); verify(myClassMock, MyClass.class); assertEquals("Expected and actual did not match", expected, actual); } @Test public void testGetMessageWithArgument() throws Exception { StupidNew tested = new StupidNew(); MyClass myClassMock = createMockAndExpectNew(MyClass.class); String expected = "Hello altered World"; expect(myClassMock.getMessage("test")).andReturn("Hello altered World"); replay(myClassMock, MyClass.class); String actual = tested.getMessageWithArgument(); verify(myClassMock, MyClass.class); assertEquals("Expected and actual did not match", expected, actual); } @Test public void testInvokeVoidMethod() throws Exception { StupidNew tested = new StupidNew(); MyClass myClassMock = createMockAndExpectNew(MyClass.class); myClassMock.voidMethod(); expectLastCall().times(1); replay(myClassMock, MyClass.class); tested.invokeVoidMethod(); verify(myClassMock, MyClass.class); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/nice/NiceDemoTest.java ================================================ package samples.junit4.nice; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.modules.junit4.PowerMockRunner; import samples.nice.NiceDemo; import static org.powermock.api.easymock.PowerMock.*; /** * This is a simple test case for the {@link NiceDemo} class that demonstrates * that strict method mocking works. * */ @RunWith(PowerMockRunner.class) public class NiceDemoTest { @Test public void testCallAThenB_noExpectations() throws Exception { NiceDemo tested = createNicePartialMock(NiceDemo.class, "A", "B"); replay(tested); tested.callAThenB(); verify(tested); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/noannotation/NoAnnotationUsageTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.noannotation; import junit.framework.TestCase; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.staticandinstance.StaticAndInstanceDemo; import static org.easymock.EasyMock.expect; import static org.powermock.api.easymock.PowerMock.*; /** * Test case that demonstrates the ability to run test cases not annotated with * {@link Test} when extending from {@link TestCase} using JUnit 4.4. */ @RunWith(PowerMockRunner.class) @PrepareForTest(StaticAndInstanceDemo.class) public class NoAnnotationUsageTest extends TestCase { public void testGetMessage() throws Exception { mockStaticPartial(StaticAndInstanceDemo.class, "getStaticMessage"); StaticAndInstanceDemo tested = createPartialMock(StaticAndInstanceDemo.class, "getPrivateMessage"); final String staticExpected = "a static message"; expect(StaticAndInstanceDemo.getStaticMessage()).andReturn(staticExpected); final String privateExpected = "A private message "; expectPrivate(tested, "getPrivateMessage").andReturn(privateExpected); replay(tested); replay(StaticAndInstanceDemo.class); String actual = tested.getMessage(); verify(tested); verify(StaticAndInstanceDemo.class); assertEquals(privateExpected + staticExpected, actual); } public void testGetMessage2() throws Exception { mockStaticPartial(StaticAndInstanceDemo.class, "getStaticMessage"); StaticAndInstanceDemo tested = createPartialMock(StaticAndInstanceDemo.class, "getPrivateMessage"); final String staticExpected = "a static message"; expect(StaticAndInstanceDemo.getStaticMessage()).andReturn(staticExpected); final String privateExpected = "A private message "; expectPrivate(tested, "getPrivateMessage").andReturn(privateExpected); replay(tested); replay(StaticAndInstanceDemo.class); String actual = tested.getMessage(); verify(tested); verify(StaticAndInstanceDemo.class); assertEquals(privateExpected + staticExpected, actual); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/noannotation/SetUpAndTearDownWhenExtendingTestCaseTest.java ================================================ package samples.junit4.noannotation; import junit.framework.TestCase; import org.junit.runner.RunWith; import org.powermock.modules.junit4.PowerMockRunner; @RunWith(PowerMockRunner.class) public class SetUpAndTearDownWhenExtendingTestCaseTest extends TestCase { private static final String INITIAL_MESSAGE = ""; private static final String SET_UP_MESSAGE = "setUp"; private static final String TEST_MESSAGE = "test"; private static String CURRENT_MESSAGE = INITIAL_MESSAGE; @Override protected void setUp() throws Exception { assertEquals(INITIAL_MESSAGE, CURRENT_MESSAGE); CURRENT_MESSAGE = SET_UP_MESSAGE; } @Override protected void tearDown() throws Exception { assertEquals(TEST_MESSAGE, CURRENT_MESSAGE); } public void testSomething() throws Exception { assertEquals(SET_UP_MESSAGE, CURRENT_MESSAGE); CURRENT_MESSAGE = TEST_MESSAGE; } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/noannotation/SetUpAndTearDownWhenNotExtendingTestCaseTest.java ================================================ package samples.junit4.noannotation; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.modules.junit4.PowerMockRunner; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; @RunWith(PowerMockRunner.class) public class SetUpAndTearDownWhenNotExtendingTestCaseTest { private static final String INITIAL_MESSAGE = ""; private static String CURRENT_MESSAGE = INITIAL_MESSAGE; public void setUp() throws Exception { fail("Should not call setUp"); } public void tearDown() throws Exception { fail("Should not call tearDown"); } @Test public void testSomething() throws Exception { assertEquals(INITIAL_MESSAGE, CURRENT_MESSAGE); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/noannotation/SetUpIsOnlyCalledOnceWhenExtendingTestCaseTest.java ================================================ package samples.junit4.noannotation; import junit.framework.TestCase; import org.junit.Before; public class SetUpIsOnlyCalledOnceWhenExtendingTestCaseTest extends TestCase { private int state = 0; @Before @Override public void setUp() throws Exception { state++; } public void testSetupMethodIsOnlyCalledOnceWhenExtendingFromTestCase() throws Exception { assertEquals(1, state); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/noannotation/StringConstructorWorksWhenExtendingTestCase.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.noannotation; import junit.framework.TestCase; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.singleton.StaticHelper; import samples.singleton.StaticService; import static org.easymock.EasyMock.expect; import static org.powermock.api.easymock.PowerMock.*; /** * Demonstrates that the PowerMock JUnit runner works with single-arg string * constructor. Asserts that issue 174 is * fixed. * */ @RunWith(PowerMockRunner.class) @PrepareForTest( { StaticService.class, StaticHelper.class }) public class StringConstructorWorksWhenExtendingTestCase extends TestCase { public StringConstructorWorksWhenExtendingTestCase(String name) { super(name); } public void testMockingStaticMethodWorksWhenStringArgConstructor() throws Exception { mockStatic(StaticService.class); String expected = "Hello altered World"; expect(StaticService.say("hello")).andReturn("Hello altered World"); replay(StaticService.class); String actual = StaticService.say("hello"); verify(StaticService.class); assertEquals("Expected and actual did not match", expected, actual); // Singleton still be mocked by now. try { StaticService.say("world"); fail("Should throw AssertionError!"); } catch (AssertionError e) { assertEquals("\n Unexpected method call StaticService.say(\"world\"):", e.getMessage()); } } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/overloading/MethodWithSameNameButDifferentDefinitionTypeTest.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.overloading; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.classhierarchy.ChildA; import samples.classhierarchy.Parent; import samples.overloading.StaticAndInstanceMethodWithSameName; import samples.overloading.StaticAndInstanceMethodWithSameNameUser; import static org.powermock.api.easymock.PowerMock.*; /** * Demonstrates that PowerMock correctly methods that seam to be overloaded but * differ because one is static and one is instance. */ @RunWith(PowerMockRunner.class) @PrepareForTest( { StaticAndInstanceMethodWithSameNameUser.class, StaticAndInstanceMethodWithSameName.class }) public class MethodWithSameNameButDifferentDefinitionTypeTest { @Test public void mockGatewayCanInvokeInstanceMethodWhenClassContainsStaticAndInstanceMethodWithSameName() throws Exception { final ChildA object = createMock(ChildA.class); StaticAndInstanceMethodWithSameName mock = createMock(StaticAndInstanceMethodWithSameName.class); expectNew(ChildA.class).andReturn(object); mock.overloaded((Parent) object); expectLastCall().once(); replayAll(); new StaticAndInstanceMethodWithSameNameUser().performInstaceInvocation(mock); verifyAll(); } @Test public void mockGatewayCanInvokeStaticMethodWhenClassContainsStaticAndInstanceMethodWithSameName() throws Exception { final Parent object = createMock(ChildA.class); mockStatic(StaticAndInstanceMethodWithSameName.class); expectNew(ChildA.class).andReturn((ChildA) object); StaticAndInstanceMethodWithSameName.overloaded((ChildA) object); expectLastCall().once(); replayAll(); new StaticAndInstanceMethodWithSameNameUser().performStaticInvocation(); verifyAll(); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/overloading/OverloadingDemoTest.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.overloading; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.classhierarchy.ChildA; import samples.classhierarchy.Parent; import samples.overloading.OverloadedMethodsExample; import samples.overloading.OverloadingDemo; import static org.powermock.api.easymock.PowerMock.*; /** * Demonstrates that PowerMock correctly invoke overloaded methods from the * MockGateway. * href="http://code.google.com/p/powermock/issues/detail?id=229">229 is * solved. */ @RunWith(PowerMockRunner.class) @PrepareForTest({ OverloadedMethodsExample.class, OverloadingDemo.class }) public class OverloadingDemoTest { @Test public void mockGatewayFindsBestOverloadedMethodCandidateWhenOnlyOneArgument() throws Exception { final Parent object = createMock(ChildA.class); mockStatic(OverloadedMethodsExample.class); OverloadedMethodsExample.overloadedMethodWithOneArgument(object); expectLastCall().once(); expectNew(ChildA.class).andReturn((ChildA) object); replayAll(); final OverloadingDemo demo = new OverloadingDemo(); demo.performSingleOverloadedArgumentTest(); verifyAll(); } @Test public void mockGatewayFindsBestOverloadedMethodCandidateWhenBothArgumentSame() throws Exception { final Parent child = createMock(ChildA.class); mockStatic(OverloadedMethodsExample.class); OverloadedMethodsExample.overloadedMethodWithTwoArguments(child, child); expectLastCall().once(); expectNew(ChildA.class).andReturn((ChildA) child).times(2); replayAll(); final OverloadingDemo demo = new OverloadingDemo(); demo.performMethodOverloadTestWhenBothArgumentSame(); verifyAll(); } @Test public void mockGatewayFindsBestOverloadedMethodCandidateWhenOneArgumentSameAndOneDifferent() throws Exception { final Parent child = createMock(ChildA.class); final Parent parent = createMock(Parent.class); mockStatic(OverloadedMethodsExample.class); OverloadedMethodsExample.overloadedMethodWithTwoArguments(parent, child); expectLastCall().once(); expectNew(ChildA.class).andReturn((ChildA) child); expectNew(Parent.class).andReturn(parent); replayAll(); final OverloadingDemo demo = new OverloadingDemo(); demo.performMethodOverloadTestWithOneArgumentSameAndOneDiffernt(); verifyAll(); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/partialmocking/MockSelfDemoTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.partialmocking; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.reflect.Whitebox; import org.powermock.reflect.exceptions.ConstructorNotFoundException; import samples.partialmocking.MockSelfDemo; import samples.partialmocking.MockSelfWithNoDefaultConstructorDemo; import java.sql.Connection; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.expectLastCall; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.powermock.api.easymock.PowerMock.*; @RunWith(PowerMockRunner.class) @PrepareForTest(MockSelfDemo.class) public class MockSelfDemoTest { private MockSelfDemo tested; @Test public void testMockMultiple_ok() throws Exception { tested = createPartialMock(MockSelfDemo.class, "aMethod2", "getString"); tested.aMethod2(); expectLastCall().times(1); final String expected = "Hello altered world"; expect(tested.getString("world")).andReturn(expected); replay(tested); String actual = tested.aMethod(); verify(tested); assertEquals("Result ought to be \"Hello altered world\".", expected, actual); } @Test public void testMockMultiple_sameName() throws Exception { tested = createPartialMock(MockSelfDemo.class, "getString"); final String firstString = "A message: "; expectPrivate(tested, "getString").andReturn(firstString); final String secondString = "altered world"; expect(tested.getString("world2")).andReturn(secondString); final String expected = firstString + secondString; replay(tested); String actual = tested.getTwoStrings(); verify(tested); assertEquals("Result ought to be \"A message:Hello altered world\".", expected, actual); } @Test public void testMockSingleMethod() throws Exception { tested = createPartialMock(MockSelfDemo.class, "timesTwo", int.class); final int expectedInt = 2; final int expectedInteger = 8; expect(tested.timesTwo(4)).andReturn(expectedInt); replay(tested); int actualInt = tested.timesTwo(4); int actualInteger = tested.timesTwo(new Integer(4)); verify(tested); assertEquals(expectedInt, actualInt); assertEquals(expectedInteger, actualInteger); } @Test public void testMockAllExcept_parametersDefined() throws Exception { tested = createPartialMockForAllMethodsExcept(MockSelfDemo.class, "getString2", String.class); final String expected = "Hello altered world"; expect(tested.getString2()).andReturn(expected); replay(tested); assertEquals(expected, tested.getString2()); assertEquals("Hello string", tested.getString2("string")); verify(tested); } @Test public void testMockAllExcept_single() throws Exception { tested = createPartialMockForAllMethodsExcept(MockSelfDemo.class, "aMethod"); tested.aMethod2(); expectLastCall().times(1); final String expected = "Hello altered world"; expect(tested.getString("world")).andReturn(expected); replay(tested); String actual = tested.aMethod(); verify(tested); assertEquals("Result ought to be \"Hello altered world\".", expected, actual); } @Test public void testMockAllExcept_multiple() throws Exception { tested = createPartialMockForAllMethodsExcept(MockSelfDemo.class, "timesTwo", "timesThree"); final String expected = "A new value"; expect(tested.getString2()).andReturn(expected); replay(tested); assertEquals(4, tested.timesTwo(2)); assertEquals(4, tested.timesTwo(new Integer(2))); assertEquals(6, tested.timesThree(2)); assertEquals(expected, tested.getString2()); verify(tested); } @Test public void testCreatePartialMockAndInvokeObjectConstructor() throws Exception { tested = createPartialMock(MockSelfDemo.class, new String[] { "aMethod2", "getString" }, new Object()); tested.aMethod2(); expectLastCall().times(1); final String expected = "Hello altered world"; expect(tested.getString("world")).andReturn(expected); replay(tested); String actual = tested.aMethod(); verify(tested); assertEquals("Result ought to be \"Hello altered world\".", expected, actual); } @Test public void testCreatePartialMockAndInvokeDefaultConstructor() throws Exception { tested = createPartialMockAndInvokeDefaultConstructor(MockSelfDemo.class, "aMethod2", "getString"); tested.aMethod2(); expectLastCall().times(1); final String expected = "Hello altered world"; expect(tested.getString("world")).andReturn(expected); replay(tested); String actual = tested.aMethod(); verify(tested); assertEquals("Result ought to be \"Hello altered world\".", expected, actual); } @Test public void partialMockingWithNullArgumentWorks() throws Exception { final MockSelfDemo tested = createPartialMock(MockSelfDemo.class, "establishConnection"); Connection conn=null; Whitebox.invokeMethod(tested, "establishConnection", conn); } @PrepareForTest(MockSelfWithNoDefaultConstructorDemo.class) @Test public void testCreatePartialMockAndInvokeDefaultConstructor_noDefaultConstructorFound() throws Exception { try { createPartialMockAndInvokeDefaultConstructor(MockSelfWithNoDefaultConstructorDemo.class, "aMethod2"); fail("Should throw ConstructorNotFoundException!"); } catch (ConstructorNotFoundException e) { assertEquals("Failed to lookup constructor with parameter types [ ] in class samples.partialmocking.MockSelfWithNoDefaultConstructorDemo.", e.getMessage()); } } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/partialmocking/MockSelfDemoWithSubClassTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.partialmocking; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.partialmocking.MockSelfDemoWithSubClass; import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertEquals; import static org.powermock.api.easymock.PowerMock.*; @RunWith(PowerMockRunner.class) @PrepareForTest(MockSelfDemoWithSubClass.class) public class MockSelfDemoWithSubClassTest { @Test public void testMockPartialMethodInChildClass() throws Exception { MockSelfDemoWithSubClass tested = createPartialMock( MockSelfDemoWithSubClass.class, "getAMessage", "getInternalMessage"); final String getAMessageMock = "Hello "; final String getInternalMessageMock = "World!"; final String expected = getInternalMessageMock + getAMessageMock; expect(tested.getAMessage()).andReturn(getAMessageMock); expectPrivate(tested, "getInternalMessage").andReturn( getInternalMessageMock); replay(tested); String actual = tested.getMessage(); verify(tested); assertEquals(expected, actual); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/partialmocking/PartialMockingWithConstructorTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.partialmocking; import org.junit.Ignore; import org.junit.Test; import samples.partialmocking.PartialMockingWithConstructor; import static org.powermock.api.easymock.PowerMock.*; public class PartialMockingWithConstructorTest { @Ignore("The initialize method is never invoked but is caught by the proxy. This is a possibly a bug in EasyMock class extensions?") @Test public void testPartialMock() throws Exception { /* * In the original test case PartialMockingWithConstructor had * constructor arguments which I removed to slim down the test case, * originally I was using the following method to create a partial mock. * Regardless the same problem still occurs. */ PartialMockingWithConstructor nationPartialMock = createPartialMockAndInvokeDefaultConstructor(PartialMockingWithConstructor.class, "touch"); /* * The following method also causes the same problem. */ // Nation nationPartialMock = // createPartialMockAndInvokeDefaultConstructor(Nation.class,"touch"); replay(nationPartialMock); // Uncommenting the following line has no effect on the test result. // nationPartialMock.initialize(); verify(nationPartialMock); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/partialmocking/PartialMockingWithConstructorUsingEasyMockTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.partialmocking; import org.easymock.ConstructorArgs; import org.junit.Ignore; import org.junit.Test; import samples.partialmocking.PartialMockingWithConstructor; import java.lang.reflect.Method; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; import static org.powermock.api.easymock.PowerMock.createMock; public class PartialMockingWithConstructorUsingEasyMockTest { @SuppressWarnings("deprecation") @Ignore("The initialize method is never invoked but is caught by the proxy. This is a possibly a bug in EasyMock class extensions?") @Test public void testPartialMock() throws Exception { /* * In the original test case PartialMockingWithConstructor had * constructor arguments which I removed to slim down the test case, * originally I was using the following method to create a partial mock. * Regardless the same problem still occurs. */ ConstructorArgs args = new ConstructorArgs(PartialMockingWithConstructor.class.getConstructor()); Method touchMethod = PartialMockingWithConstructor.class.getMethod("touch"); PartialMockingWithConstructor nationPartialMock = createMock(PartialMockingWithConstructor.class, args, touchMethod); /* * The following method also causes the same problem. */ // Nation nationPartialMock = // createPartialMockAndInvokeDefaultConstructor(Nation.class,"touch"); replay(nationPartialMock); // Uncommenting the following line has no effect on the test result. // nationPartialMock.initialize(); verify(nationPartialMock); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/powermockignore/PowerMockIgnoreAndPrepareForTest.java ================================================ package samples.junit4.powermockignore; import net.bytebuddy.utility.RandomString; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.singleton.StaticService; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.easymock.EasyMock.expect; import static org.powermock.api.easymock.PowerMock.*; @RunWith(PowerMockRunner.class) @PowerMockIgnore("samples.*") @PrepareForTest(StaticService.class) public class PowerMockIgnoreAndPrepareForTest { @Test public void powermock_ignore_annotation_and_prepare_for_test_annotation_can_be_combined() { mockStatic(StaticService.class); final String expected = RandomString.make(5); expect(StaticService.doStatic(5)).andReturn(expected); replay(StaticService.class); assertThat(StaticService.doStatic(5)) .isEqualTo(expected); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/prepareeverything/ExpectNewDemoUsingThePrepareEverythingAnnotationTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.prepareeverything; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareEverythingForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.reflect.Whitebox; import org.powermock.reflect.exceptions.ConstructorNotFoundException; import samples.Service; import samples.expectnew.ExpectNewDemo; import samples.expectnew.ExpectNewServiceUser; import samples.expectnew.VarArgsConstructorDemo; import samples.newmocking.MyClass; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import static org.easymock.EasyMock.*; import static org.easymock.EasyMock.expectLastCall; import static org.junit.Assert.*; import static org.powermock.api.easymock.PowerMock.createMock; import static org.powermock.api.easymock.PowerMock.*; /** * Test class to demonstrate new instance mocking using expectNew(..) with the * {@link PrepareEverythingForTest} annotation and replayAll and verifyAll. * */ @RunWith(PowerMockRunner.class) @PrepareEverythingForTest public class ExpectNewDemoUsingThePrepareEverythingAnnotationTest { @Test public void testNewWithCheckedException() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); final String expectedFailMessage = "testing checked exception"; expectNew(MyClass.class).andThrow(new IOException(expectedFailMessage)); replayAll(); try { tested.throwExceptionAndWrapInRunTimeWhenInvoction(); fail("Should throw a checked Exception!"); } catch (RuntimeException e) { assertTrue(e.getCause() instanceof IOException); assertEquals(expectedFailMessage, e.getMessage()); } verifyAll(); } @PrepareEverythingForTest @Test public void testGetMessage() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock = createMock(MyClass.class); expectNew(MyClass.class).andReturn(myClassMock); String expected = "Hello altered World"; expect(myClassMock.getMessage()).andReturn("Hello altered World"); replayAll(); String actual = tested.getMessage(); verifyAll(); assertEquals("Expected and actual did not match", expected, actual); } @Test public void testGetMessageWithArgument() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock = createMock(MyClass.class); expectNew(MyClass.class).andReturn(myClassMock); String expected = "Hello altered World"; expect(myClassMock.getMessage("test")).andReturn("Hello altered World"); replayAll(); String actual = tested.getMessageWithArgument(); verifyAll(); assertEquals("Expected and actual did not match", expected, actual); } @Test public void testInvokeVoidMethod() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock = createMock(MyClass.class); expectNew(MyClass.class).andReturn(myClassMock); myClassMock.voidMethod(); expectLastCall().times(1); replayAll(); tested.invokeVoidMethod(); verifyAll(); } @Test public void testNewWithRuntimeException() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); final String expectedFailMessage = "testing"; expectNew(MyClass.class).andThrow(new RuntimeException(expectedFailMessage)); replayAll(); try { tested.throwExceptionWhenInvoction(); fail("Should throw RuntimeException!"); } catch (RuntimeException e) { assertEquals(expectedFailMessage, e.getMessage()); } verifyAll(); } @Test public void testPreviousProblemsWithByteCodeManipulation() throws Exception { MyClass myClassMock1 = createMock(MyClass.class); expect(myClassMock1.getMessage()).andReturn("Hello"); expect(myClassMock1.getMessage()).andReturn("World"); replayAll(); assertEquals("Hello", myClassMock1.getMessage()); assertEquals("World", myClassMock1.getMessage()); verifyAll(); } @Test public void testMultipleNew() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock1 = createMock(MyClass.class); MyClass myClassMock2 = createMock(MyClass.class); expectNew(MyClass.class).andReturn(myClassMock1); expectNew(MyClass.class).andReturn(myClassMock2); expect(myClassMock1.getMessage()).andReturn("Hello "); expect(myClassMock2.getMessage()).andReturn("World"); replayAll(); final String actual = tested.multipleNew(); verifyAll(); assertEquals("Hello World", actual); } @Test public void testSimpleMultipleNew() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock1 = createMock(MyClass.class); expectNew(MyClass.class).andReturn(myClassMock1).times(3); replayAll(); tested.simpleMultipleNew(); verifyAll(); } @Test public void testSimpleMultipleNew_tooManyTimesExpected() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock1 = createMock(MyClass.class); expectNew(MyClass.class).andReturn(myClassMock1).times(4); replayAll(); tested.simpleMultipleNew(); try { verifyAll(); fail("Should throw AssertionError."); } catch (AssertionError e) { assertEquals("\n Expectation failure on verify:" + "\n samples.newmocking.MyClass(): expected: 4, actual: 3", e .getMessage()); } } @Test public void testSimpleMultipleNew_tooFewTimesExpected() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock1 = createMock(MyClass.class); expectNew(MyClass.class).andReturn(myClassMock1).times(2); replayAll(); try { tested.simpleMultipleNew(); fail("Should throw AssertionError."); } catch (AssertionError e) { assertEquals("\n Unexpected constructor call samples.newmocking.MyClass():" + "\n samples.newmocking.MyClass(): expected: 2, actual: 3", e.getMessage()); } } /** * Verifies that the issue * http://code.google.com/p/powermock/issues/detail?id=10 is solved. */ @Test public void testSimpleMultipleNewPrivate_tooFewTimesExpected() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock1 = createMock(MyClass.class); expectNew(MyClass.class).andReturn(myClassMock1).times(2); replayAll(); try { Whitebox.invokeMethod(tested, "simpleMultipleNewPrivate"); fail("Should throw AssertionError."); } catch (AssertionError e) { assertEquals("\n Unexpected constructor call samples.newmocking.MyClass():" + "\n samples.newmocking.MyClass(): expected: 2, actual: 3", e.getMessage()); } } @Test public void testSimpleMultipleNewPrivate_ok() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock1 = createMock(MyClass.class); expectNew(MyClass.class).andReturn(myClassMock1).times(3); replayAll(); Whitebox.invokeMethod(tested, "simpleMultipleNewPrivate"); } @Test public void testSimpleSingleNew_withOnce() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock1 = createMock(MyClass.class); expectNew(MyClass.class).andReturn(myClassMock1).once(); replayAll(); tested.simpleSingleNew(); verifyAll(); } @Test public void testSimpleSingleNew_withAtLeastOnce() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock1 = createMock(MyClass.class); expectNew(MyClass.class).andReturn(myClassMock1).atLeastOnce(); replayAll(); tested.simpleSingleNew(); verifyAll(); } @Test public void testSimpleMultipleNew_withAtLeastOnce() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock1 = createMock(MyClass.class); expectNew(MyClass.class).andReturn(myClassMock1).atLeastOnce(); replayAll(); tested.simpleMultipleNew(); verifyAll(); } @Test public void testSimpleMultipleNew_withRange_lowerBoundLessThan0() throws Exception { MyClass myClassMock1 = createMock(MyClass.class); try { expectNew(MyClass.class).andReturn(myClassMock1).times(-20, 2); fail("Should throw IllegalArgumentException."); } catch (IllegalArgumentException e) { assertEquals("minimum must be >= 0", e.getMessage()); } } @Test public void testSimpleMultipleNew_withRange_upperBoundLessThan0() throws Exception { MyClass myClassMock1 = createMock(MyClass.class); try { expectNew(MyClass.class).andReturn(myClassMock1).times(-1, -2); fail("Should throw IllegalArgumentException."); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().contains("<=")); } } @Test public void testSimpleMultipleNew_withRange_upperBoundLessThanLowerBound() throws Exception { MyClass myClassMock1 = createMock(MyClass.class); try { expectNew(MyClass.class).andReturn(myClassMock1).times(10, 2); fail("Should throw IllegalArgumentException."); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().contains("<=")); } } @Test public void testSimpleMultipleNew_withRange_OK() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock1 = createMock(MyClass.class); expectNew(MyClass.class).andReturn(myClassMock1).times(1, 5); replayAll(); tested.simpleMultipleNew(); verifyAll(); } @Test public void testSimpleMultipleNew_anyTimes() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock1 = createMock(MyClass.class); expectNew(MyClass.class).andReturn(myClassMock1).anyTimes(); replayAll(); tested.simpleMultipleNew(); verifyAll(); } @Test public void testSimpleMultipleNew_withRange_notWithinRange() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock1 = createMock(MyClass.class); expectNew(MyClass.class).andReturn(myClassMock1).times(5, 7); replayAll(); tested.simpleMultipleNew(); try { verifyAll(); fail("Should throw AssertionError."); } catch (AssertionError e) { assertEquals("\n Expectation failure on verify:" + "\n samples.newmocking.MyClass(): expected: between 5 and 7, actual: 3", e.getMessage()); } } @Test public void testAlternativeFlow() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); expectNew(DataInputStream.class, new Object[] { null }).andThrow(new RuntimeException("error")); replayAll(); InputStream stream = tested.alternativePath(); verifyAll(); assertNotNull("The returned inputstream should not be null.", stream); assertTrue("The returned inputstream should be an instance of ByteArrayInputStream.", stream instanceof ByteArrayInputStream); } @Test public void testSimpleMultipleNewPrivate_tooManyTimesExpected() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock1 = createMock(MyClass.class); expectNew(MyClass.class).andReturn(myClassMock1).times(4); replayAll(); try { Whitebox.invokeMethod(tested, "simpleMultipleNewPrivate"); verifyAll(); fail("Should throw an exception!."); } catch (AssertionError e) { assertEquals("\n Expectation failure on verify:" + "\n samples.newmocking.MyClass(): expected: 4, actual: 3", e .getMessage()); } } @Test public void testNewWithArguments() throws Exception { final int numberOfTimes = 2; final String expected = "used"; ExpectNewDemo tested = new ExpectNewDemo(); ExpectNewServiceUser expectNewServiceImplMock = createMock(ExpectNewServiceUser.class); Service serviceMock = createMock(Service.class); expectNew(ExpectNewServiceUser.class, serviceMock, numberOfTimes).andReturn(expectNewServiceImplMock); expect(expectNewServiceImplMock.useService()).andReturn(expected); replayAll(); assertEquals(expected, tested.newWithArguments(serviceMock, numberOfTimes)); verifyAll(); } @Test public void testNewWithVarArgs() throws Exception { final String firstString = "hello"; final String secondString = "world"; ExpectNewDemo tested = new ExpectNewDemo(); VarArgsConstructorDemo varArgsConstructorDemoMock = createMock(VarArgsConstructorDemo.class); expectNew(VarArgsConstructorDemo.class, firstString, secondString).andReturn(varArgsConstructorDemoMock); expect(varArgsConstructorDemoMock.getAllMessages()).andReturn(new String[] { firstString, secondString }); replayAll(); String[] varArgs = tested.newVarArgs(firstString, secondString); assertEquals(2, varArgs.length); assertEquals(firstString, varArgs[0]); assertEquals(secondString, varArgs[1]); verifyAll(); } @Test public void testNewWhenTheExpectedConstructorIsNotFound() throws Exception { final Object object = new Object(); try { expectNew(VarArgsConstructorDemo.class, object); fail("Should throw ConstructorNotFoundException!"); } catch (ConstructorNotFoundException e) { assertEquals("No constructor found in class '" + VarArgsConstructorDemo.class.getName() + "' with parameter types: [ " + object.getClass().getName() + " ].", e.getMessage()); } } @Test public void testNewWithVarArgsConstructorWhenOneArgumentIsOfASubType() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); Service serviceMock = createMock(Service.class); VarArgsConstructorDemo varArgsConstructorDemoMock = createMock(VarArgsConstructorDemo.class); final Service serviceSubTypeInstance = new Service() { @Override public String getServiceMessage() { return "message"; } }; expectNew(VarArgsConstructorDemo.class, serviceSubTypeInstance, serviceMock).andReturn(varArgsConstructorDemoMock); expect(varArgsConstructorDemoMock.getAllServices()).andReturn(new Service[] { serviceMock }); replayAll(); Service[] varArgs = tested.newVarArgs(serviceSubTypeInstance, serviceMock); assertEquals(1, varArgs.length); assertSame(serviceMock, varArgs[0]); verifyAll(); } @Test public void testNewWithArrayVarArgs() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); VarArgsConstructorDemo varArgsConstructorDemoMock = createMock(VarArgsConstructorDemo.class); final byte[] byteArrayOne = new byte[] { 42 }; final byte[] byteArrayTwo = new byte[] { 17 }; expectNew(VarArgsConstructorDemo.class, byteArrayOne, byteArrayTwo).andReturn(varArgsConstructorDemoMock); expect(varArgsConstructorDemoMock.getByteArrays()).andReturn(new byte[][] { byteArrayOne }); replayAll(); byte[][] varArgs = tested.newVarArgs(byteArrayOne, byteArrayTwo); assertEquals(1, varArgs.length); assertSame(byteArrayOne, varArgs[0]); verifyAll(); } @Test public void testNewWithArrayVarArgsAndMatchers() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); VarArgsConstructorDemo varArgsConstructorDemoMock = createMock(VarArgsConstructorDemo.class); final byte[] byteArrayOne = new byte[] { 42 }; final byte[] byteArrayTwo = new byte[] { 17 }; expectNew(VarArgsConstructorDemo.class, aryEq(byteArrayOne), aryEq(byteArrayTwo)).andReturn(varArgsConstructorDemoMock); expect(varArgsConstructorDemoMock.getByteArrays()).andReturn(new byte[][] { byteArrayOne }); replayAll(); byte[][] varArgs = tested.newVarArgsWithMatchers(); assertEquals(1, varArgs.length); assertSame(byteArrayOne, varArgs[0]); verifyAll(); } @Test public void testNewWithArrayVarArgsWhenFirstArgumentIsNullAndSubseqentArgumentsAreNotNull() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); VarArgsConstructorDemo varArgsConstructorDemoMock = createMock(VarArgsConstructorDemo.class); final byte[] byteArrayOne = null; final byte[] byteArrayTwo = new byte[] { 17 }; expectNew(VarArgsConstructorDemo.class, byteArrayOne, byteArrayTwo).andReturn(varArgsConstructorDemoMock); expect(varArgsConstructorDemoMock.getByteArrays()).andReturn(new byte[][] { byteArrayTwo }); replayAll(); byte[][] varArgs = tested.newVarArgs(byteArrayOne, byteArrayTwo); assertEquals(1, varArgs.length); assertSame(byteArrayTwo, varArgs[0]); verifyAll(); } @Test public void testNewWithArrayVarArgsWhenFirstArgumentIsNotNullButSubseqentArgumentsAreNull() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); VarArgsConstructorDemo varArgsConstructorDemoMock = createMock(VarArgsConstructorDemo.class); final byte[] byteArrayOne = new byte[] { 42 }; final byte[] byteArrayTwo = null; expectNew(VarArgsConstructorDemo.class, byteArrayOne, byteArrayTwo).andReturn(varArgsConstructorDemoMock); expect(varArgsConstructorDemoMock.getByteArrays()).andReturn(new byte[][] { byteArrayOne }); replayAll(); byte[][] varArgs = tested.newVarArgs(byteArrayOne, byteArrayTwo); assertEquals(1, varArgs.length); assertSame(byteArrayOne, varArgs[0]); verifyAll(); } @Test public void testNewWithArrayVarArgsWhenFirstArgumentIsNullSecondArgumentIsNotNullAndThirdArgumentIsNull() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); VarArgsConstructorDemo varArgsConstructorDemoMock = createMock(VarArgsConstructorDemo.class); final byte[] byteArrayOne = null; final byte[] byteArrayTwo = new byte[] { 42 }; final byte[] byteArrayThree = null; expectNew(VarArgsConstructorDemo.class, byteArrayOne, byteArrayTwo, byteArrayThree).andReturn(varArgsConstructorDemoMock); expect(varArgsConstructorDemoMock.getByteArrays()).andReturn(new byte[][] { byteArrayTwo }); replayAll(); byte[][] varArgs = tested.newVarArgs(byteArrayOne, byteArrayTwo, byteArrayThree); assertEquals(1, varArgs.length); assertSame(byteArrayTwo, varArgs[0]); verifyAll(); } @Test public void testNewWithArrayVarArgsWhenAllArgumentsAreNull() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); VarArgsConstructorDemo varArgsConstructorDemoMock = createMock(VarArgsConstructorDemo.class); final byte[] byteArrayOne = null; final byte[] byteArrayTwo = null; expectNew(VarArgsConstructorDemo.class, byteArrayOne, byteArrayTwo).andReturn(varArgsConstructorDemoMock); expect(varArgsConstructorDemoMock.getByteArrays()).andReturn(new byte[][] { byteArrayTwo }); replayAll(); byte[][] varArgs = tested.newVarArgs(byteArrayOne, byteArrayTwo); assertEquals(1, varArgs.length); assertSame(byteArrayTwo, varArgs[0]); verifyAll(); } @Test public void testNewWithWrongArgument() throws Exception { final int numberOfTimes = 2; final String expected = "used"; ExpectNewDemo tested = new ExpectNewDemo(); ExpectNewServiceUser expectNewServiceImplMock = createMock(ExpectNewServiceUser.class); Service serviceMock = createMock(Service.class); expectNew(ExpectNewServiceUser.class, serviceMock, numberOfTimes).andReturn(expectNewServiceImplMock); expect(expectNewServiceImplMock.useService()).andReturn(expected); replayAll(); try { assertEquals(expected, tested.newWithWrongArguments(serviceMock, numberOfTimes)); verifyAll(); fail("Should throw AssertionError!"); } catch (AssertionError e) { assertEquals( "\n Unexpected constructor call samples.expectnew.ExpectNewServiceUser(EasyMock for interface samples.Service, 4 (int)):" + "\n samples.expectnew.ExpectNewServiceUser(EasyMock for interface samples.Service, 2 (int)): expected: 1, actual: 0", e.getMessage()); } } @Test public void testExpectNewButNoNewCallWasMade() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock1 = createMock(MyClass.class); expectNew(MyClass.class).andReturn(myClassMock1).once(); replayAll(); try { tested.makeDate(); verifyAll(); fail("Should throw AssertionError!"); } catch (AssertionError e) { assertTrue(e.getMessage().contains(MyClass.class.getName() + "(): expected: 1, actual: 0")); } } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/privateandfinal/PrivateFinalTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.privateandfinal; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.privateandfinal.PrivateFinal; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; import static org.junit.Assert.assertEquals; import static org.powermock.api.easymock.PowerMock.createPartialMock; import static org.powermock.api.easymock.PowerMock.expectPrivate; /** * Test class to demonstrate private+final method mocking. */ @RunWith(PowerMockRunner.class) @PrepareForTest(PrivateFinal.class) public class PrivateFinalTest { @Test public void testMockPrivatAndFinal() throws Exception { PrivateFinal tested = createPartialMock(PrivateFinal.class, "sayIt"); String expected = "Hello altered World"; expectPrivate(tested, "sayIt", "name").andReturn(expected); replay(tested); String actual = tested.say("name"); verify(tested); assertEquals("Expected and actual did not match", expected, actual); } @Test public void testMultiplePartialMocksOfSameType() throws Exception { PrivateFinal tested1 = createPartialMock(PrivateFinal.class, "sayIt"); String expected1 = "Hello altered World"; expectPrivate(tested1, "sayIt", "name").andReturn(expected1); replay(tested1); PrivateFinal tested2 = createPartialMock(PrivateFinal.class, "sayIt"); String expected2 = "Hello qweqweqwe"; expectPrivate(tested2, "sayIt", "name").andReturn(expected2); replay(tested2); String actual1 = tested1.say("name"); verify(tested1); assertEquals("Expected and actual did not match", expected1, actual1); String actual2 = tested2.say("name"); verify(tested2); assertEquals("Expected and actual did not match", expected2, actual2); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/privatefield/MockSelfPrivateFieldServiceClassTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.privatefield; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.Service; import samples.privatefield.MockSelfPrivateFieldServiceClass; import static org.easymock.EasyMock.createMock; import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertEquals; import static org.powermock.api.easymock.PowerMock.*; import static org.powermock.reflect.Whitebox.setInternalState; /** * A test class that demonstrate how to test classes that uses a private field * for a service and has no corresponding setter and at the same time mocking a * method of the actual test class. This is approach is common in DI frameworks * like Guice and Wicket IoC. * * @author Johan Haleby */ @RunWith(PowerMockRunner.class) @PrepareForTest(MockSelfPrivateFieldServiceClass.class) public class MockSelfPrivateFieldServiceClassTest { @Test public void testGetCompositeMessage() throws Exception { MockSelfPrivateFieldServiceClass tested = createPartialMock(MockSelfPrivateFieldServiceClass.class, "getOwnMessage"); Service serviceMock = createMock(Service.class); setInternalState(tested, "service", serviceMock, MockSelfPrivateFieldServiceClass.class); final String expected = "Hello world"; expectPrivate(tested, "getOwnMessage").andReturn("Hello"); expect(serviceMock.getServiceMessage()).andReturn(" world"); replay(serviceMock); replay(tested); final String actual = tested.getCompositeMessage(); verify(serviceMock); verify(tested); assertEquals(expected, actual); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/privatefield/SimplePrivateFieldServiceClassTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.privatefield; import org.junit.Test; import samples.Service; import samples.privatefield.SimplePrivateFieldServiceClass; import static org.easymock.EasyMock.createMock; import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertEquals; import static org.powermock.api.easymock.PowerMock.replay; import static org.powermock.api.easymock.PowerMock.verify; import static org.powermock.reflect.Whitebox.setInternalState; /** * A test class that demonstrate how to test class that uses a private field for * a Service and has no corresponding setter. This is approach is common in DI * frameworks like Guice and Wicket IoC. * * @author Johan Haleby */ public class SimplePrivateFieldServiceClassTest { @Test public void testSimplePrivateFieldServiceClass() throws Exception { SimplePrivateFieldServiceClass tested = new SimplePrivateFieldServiceClass(); Service serviceMock = createMock(Service.class); setInternalState(tested, "service", serviceMock, SimplePrivateFieldServiceClass.class); final String expected = "Hello world!"; expect(serviceMock.getServiceMessage()).andReturn(expected); replay(serviceMock); final String actual = tested.useService(); verify(serviceMock); assertEquals(expected, actual); } @Test public void testSimplePrivateFieldServiceClassTypeSafe() throws Exception { SimplePrivateFieldServiceClass tested = new SimplePrivateFieldServiceClass(); Service serviceMock = createMock(Service.class); setInternalState(tested, serviceMock); final String expected = "Hello world!"; expect(serviceMock.getServiceMessage()).andReturn(expected); replay(serviceMock); final String actual = tested.useService(); verify(serviceMock); assertEquals(expected, actual); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/privatemocking/PrivateMethodDemoTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.privatemocking; import org.easymock.EasyMock; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.reflect.Whitebox; import samples.privatemocking.PrivateMethodDemo; import java.lang.reflect.Method; import static org.junit.Assert.assertEquals; import static org.powermock.api.easymock.PowerMock.*; /** * Test class to demonstrate private method mocking. * * @author Johan Haleby */ @RunWith(PowerMockRunner.class) @PrepareForTest(PrivateMethodDemo.class) public class PrivateMethodDemoTest { @Test public void testMockPrivateMethod() throws Exception { PrivateMethodDemo tested = createPartialMock(PrivateMethodDemo.class, "sayIt", String.class); String expected = "Hello altered World"; expectPrivate(tested, "sayIt", "name").andReturn(expected); replay(tested); String actual = tested.say("name"); verify(tested); assertEquals("Expected and actual did not match", expected, actual); } @Test public void testMockPrivateMethod_withArgument() throws Exception { PrivateMethodDemo tested = new PrivateMethodDemo(); String expected = "Hello altered World"; String actual = Whitebox.invokeMethod(tested, "sayIt", "altered World"); assertEquals("Expected and actual did not match", expected, actual); } @Test public void testInvokePrivateMethod() throws Exception { PrivateMethodDemo tested = new PrivateMethodDemo(); String expected = "Hello world"; String actual = Whitebox.invokeMethod(tested, "sayIt"); assertEquals("Expected and actual did not match", expected, actual); } @Test public void testMethodCallingPrimitiveTestMethod() throws Exception { PrivateMethodDemo tested = createPartialMock(PrivateMethodDemo.class, "aTestMethod", int.class); final int expected = 42; expectPrivate(tested, "aTestMethod", new Class[] { int.class }, 10) .andReturn(expected); replay(tested); final int actual = tested.methodCallingPrimitiveTestMethod(); verify(tested); assertEquals("Expected and actual did not match", expected, actual); } @Test public void testMethodCallingWrappedTestMethod() throws Exception { PrivateMethodDemo tested = createPartialMock(PrivateMethodDemo.class, "aTestMethod", Integer.class); final int expected = 42; expectPrivate(tested, "aTestMethod", new Class[] { Integer.class }, new Integer(15)).andReturn(expected); replay(tested); final int actual = tested.methodCallingWrappedTestMethod(); verify(tested); assertEquals("Expected and actual did not match", expected, actual); } @Test public void testMethodCallingWrappedTestMethod_reflectiveMethodLookup() throws Exception { PrivateMethodDemo tested = createPartialMock(PrivateMethodDemo.class, "aTestMethod", Integer.class); final Method methodToExpect = PrivateMethodDemo.class .getDeclaredMethod("aTestMethod", Integer.class); final int expected = 42; expectPrivate(tested, methodToExpect, 15).andReturn(expected); replay(tested); final int actual = tested.methodCallingWrappedTestMethod(); verify(tested); assertEquals("Expected and actual did not match", expected, actual); } @Test public void testExpectPrivateWithArrayMatcher() throws Exception { PrivateMethodDemo tested = createPartialMock(PrivateMethodDemo.class, "doArrayInternal"); expectPrivate(tested, "doArrayInternal", EasyMock .aryEq((Object[]) new String[] { "hello" })); replay(tested); tested.doArrayStuff("hello"); verify(tested); } @Test public void testExpectPrivateWithObjectMatcher() throws Exception { PrivateMethodDemo tested = createPartialMock(PrivateMethodDemo.class, "doObjectInternal"); expectPrivate(tested, "doObjectInternal", EasyMock .isA(CharSequence.class)); replay(tested); tested.doObjectStuff("hello"); verify(tested); } @Test public void testExpectPrivateMethodWithVarArgsParameters() throws Exception { final String methodToExpect = "varArgsMethod"; final int expected = 7; final int valueA = 2; final int valueB = 3; PrivateMethodDemo tested = createPartialMock(PrivateMethodDemo.class, methodToExpect); expectPrivate(tested, methodToExpect, valueA, valueB).andReturn( expected); replay(tested); assertEquals(expected, tested.invokeVarArgsMethod(valueA, valueB)); verify(tested); } @Test public void testExpectPrivateMethodWithoutSpecifyingMethodName_firstArgumentIsOfStringType() throws Exception { final String expected = "Hello world"; PrivateMethodDemo tested = createPartialMock(PrivateMethodDemo.class, "sayIt"); expectPrivate(tested, (String) null, "firstName", " ", "lastName") .andReturn(expected); replay(tested); assertEquals(expected, tested.enhancedSay("firstName", "lastName")); verify(tested); } @Test public void testExpectPrivateMethodWithoutSpecifyingMethodName() throws Exception { final String expected = "Hello world"; PrivateMethodDemo tested = createPartialMock(PrivateMethodDemo.class, "doSayYear"); expectPrivate(tested, 22, "name").andReturn(expected); replay(tested); assertEquals(expected, tested.sayYear("name", 22)); verify(tested); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/reflection/ReflectionInstantiatorTest.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.reflection; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.reflection.ReflectionInstantiator; import samples.reflection.UseMe; import static org.junit.Assert.assertTrue; @RunWith(PowerMockRunner.class) @PrepareForTest( { UseMe.class }) public class ReflectionInstantiatorTest { @Test public void whenClassIsInstantiatedUsingReflectionMakeSureItCanBeCastedToPowerMockLoadedVersionOfTheClass() throws Exception { ReflectionInstantiator reflectionInstantiator = new ReflectionInstantiator(); assertTrue( "Reflection instantiation doesn't work, Thread context class-loader not set to MockCL", reflectionInstantiator.instantiateUseMe()); } @Test @PrepareForTest(UseMe.class) public void whenClassIsInstantiatedUsingReflectionMakeSureItCanBeCastedToPowerMockLoadedVersionOfTheClassWhenUsingChunking() throws Exception { ReflectionInstantiator reflectionInstantiator = new ReflectionInstantiator(); assertTrue( "Reflection instantiation doesn't work, Thread context class-loader not set to MockCL", reflectionInstantiator.instantiateUseMe()); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/replayall/ReplayAllForExpectNewTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.replayall; import org.easymock.EasyMock; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.Service; import samples.expectnew.ExpectNewDemo; import samples.expectnew.ExpectNewServiceUser; import samples.newmocking.MyClass; import java.io.IOException; import static org.easymock.EasyMock.expect; import static org.junit.Assert.*; import static org.powermock.api.easymock.PowerMock.*; /** * The purpose of this test is to try-out the replay all functionality in * PowerMock in combination with expectNew. */ @RunWith(PowerMockRunner.class) @PrepareForTest( { MyClass.class, ExpectNewDemo.class }) public class ReplayAllForExpectNewTest { @Test public void testNewWithCheckedException() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); final String expectedFailMessage = "testing checked exception"; expectNew(MyClass.class).andThrow(new IOException(expectedFailMessage)); replayAll(); try { tested.throwExceptionAndWrapInRunTimeWhenInvoction(); fail("Should throw a checked Exception!"); } catch (RuntimeException e) { assertTrue(e.getCause() instanceof IOException); assertEquals(expectedFailMessage, e.getMessage()); } verifyAll(); } @Test public void testGetMessage() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock = createMock(MyClass.class); expectNew(MyClass.class).andReturn(myClassMock); String expected = "Hello altered World"; expect(myClassMock.getMessage()).andReturn("Hello altered World"); replayAll(); String actual = tested.getMessage(); verifyAll(); assertEquals("Expected and actual did not match", expected, actual); } @Test public void testReplayAllWithExpectNewWhenTheClassBeingConstructedIsNotPreparedForTest() throws Exception { final int numberOfTimes = 2; final String expected = "used"; ExpectNewDemo tested = new ExpectNewDemo(); ExpectNewServiceUser expectNewServiceImplMock = createMock(ExpectNewServiceUser.class); Service serviceMock = createMock(Service.class); expectNew(ExpectNewServiceUser.class, serviceMock, numberOfTimes).andReturn(expectNewServiceImplMock); expect(expectNewServiceImplMock.useService()).andReturn(expected); replayAll(); assertEquals(expected, tested.newWithArguments(serviceMock, numberOfTimes)); verifyAll(); } @Test public void testReplayAllWithAdditionalMocks() throws Exception { final int numberOfTimes = 2; final String expected = "used"; ExpectNewDemo tested = new ExpectNewDemo(); ExpectNewServiceUser expectNewServiceImplMock = EasyMock.createMock(ExpectNewServiceUser.class); Service serviceMock = createMock(Service.class); expectNew(ExpectNewServiceUser.class, serviceMock, numberOfTimes).andReturn(expectNewServiceImplMock); expect(expectNewServiceImplMock.useService()).andReturn(expected); replayAll(expectNewServiceImplMock); assertEquals(expected, tested.newWithArguments(serviceMock, numberOfTimes)); verifyAll(); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/replayall/ReplayAllForStaticMethodsTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.replayall; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.staticandinstance.StaticAndInstanceDemo; import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertEquals; import static org.powermock.api.easymock.PowerMock.*; /** * The purpose of this test is to try-out the replay all functionality in * PowerMock in combination with static and instance mocking. */ @RunWith(PowerMockRunner.class) @PrepareForTest(StaticAndInstanceDemo.class) public class ReplayAllForStaticMethodsTest { @Test public void testMockStaticMethodAndInstanceMethod() throws Exception { mockStaticPartial(StaticAndInstanceDemo.class, "getStaticMessage"); StaticAndInstanceDemo tested = createPartialMock(StaticAndInstanceDemo.class, "getPrivateMessage"); final String staticExpected = "a static message"; expect(StaticAndInstanceDemo.getStaticMessage()).andReturn(staticExpected); final String privateExpected = "A private message "; expectPrivate(tested, "getPrivateMessage").andReturn(privateExpected); replayAll(); String actual = tested.getMessage(); verifyAll(); assertEquals(privateExpected + staticExpected, actual); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/resetmock/ResetForStaticMethodsTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.resetmock; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.singleton.StaticService; import static org.powermock.api.easymock.PowerMock.*; /** * Asserts that it works to reset mocks for static methods even after verify has * been invoked. */ @RunWith(PowerMockRunner.class) @PrepareForTest(StaticService.class) public class ResetForStaticMethodsTest { @Test public void assertThatResetWorksForStaticMethods() throws InterruptedException { mockStatic(StaticService.class); StaticService.sayHello(); expectLastCall().once(); replay(StaticService.class); StaticService.sayHello(); verify(StaticService.class); reset(StaticService.class); StaticService.sayHello(); expectLastCall().once(); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/resetmock/ResetMockTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.resetmock; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.expectnew.ExpectNewDemo; import samples.newmocking.MyClass; import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertEquals; import static org.powermock.api.easymock.PowerMock.*; /** * Tests to verify that the reset functionality works. */ @RunWith(PowerMockRunner.class) @PrepareForTest(ExpectNewDemo.class) public class ResetMockTest { @Test public void assertManualResetWorks() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock = createMock(MyClass.class); expectNew(MyClass.class).andReturn(myClassMock); expect(myClassMock.getMessage()).andReturn("message"); replayAll(); String message = tested.getMessage(); verifyAll(); assertEquals("message", message); reset(myClassMock); reset(MyClass.class); expectNew(MyClass.class).andReturn(myClassMock); expect(myClassMock.getMessage()).andReturn("message"); replayAll(); message = tested.getMessage(); verifyAll(); assertEquals("message", message); } @Test public void assertManualResetWorksWhenMixingInstanceAndClassMocks() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock = createMock(MyClass.class); expectNew(MyClass.class).andReturn(myClassMock); expect(myClassMock.getMessage()).andReturn("message"); replayAll(); String message = tested.getMessage(); verifyAll(); assertEquals("message", message); reset(myClassMock, MyClass.class); expectNew(MyClass.class).andReturn(myClassMock); expect(myClassMock.getMessage()).andReturn("message"); replayAll(); message = tested.getMessage(); verifyAll(); assertEquals("message", message); } @Test public void assertResetAllWorks() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock = createMock(MyClass.class); expectNew(MyClass.class).andReturn(myClassMock); expect(myClassMock.getMessage()).andReturn("message"); replayAll(); String message = tested.getMessage(); verifyAll(); assertEquals("message", message); resetAll(); expectNew(MyClass.class).andReturn(myClassMock); expect(myClassMock.getMessage()).andReturn("message"); replayAll(); message = tested.getMessage(); verifyAll(); assertEquals("message", message); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/servletmocking/SampleServletTest.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.servletmocking; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.servletmocking.SampleServlet; import javax.servlet.http.HttpServletResponse; import java.io.PrintWriter; import static org.easymock.EasyMock.expect; import static org.powermock.api.easymock.PowerMock.*; @RunWith(PowerMockRunner.class) @PrepareForTest(SampleServlet.class) public class SampleServletTest { @Test public void doGet() throws Exception { SampleServlet servlet = new SampleServlet(); HttpServletResponse response = createMock(HttpServletResponse.class); PrintWriter writer = createMock(PrintWriter.class); expect(response.getWriter()).andReturn(writer); writer.write("out"); replay(response, writer); servlet.doGet(null, response); verify(response, writer); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/simplereturn/SimpleReturnExampleUserTest.java ================================================ package samples.junit4.simplereturn; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.simplereturn.SimpleReturnExample; import samples.simplereturn.SimpleReturnExampleUser; import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertEquals; import static org.powermock.api.easymock.PowerMock.*; @RunWith(PowerMockRunner.class) @PrepareForTest(SimpleReturnExample.class) public class SimpleReturnExampleUserTest { @Test public void testCreateMockDelegatedToEasyMock() throws Exception { SimpleReturnExample mock = createMock(SimpleReturnExample.class); expect(mock.mySimpleMethod()).andReturn(2); replay(mock); assertEquals(2, new SimpleReturnExampleUser(mock).myMethod()); verify(mock); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/singleton/LogicAndTestInSameClassTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.singleton; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.singleton.StaticService; import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertEquals; import static org.powermock.api.easymock.PowerMock.*; /** * A simple test that asserts that it's possible execute a test from the same * class that defines the logic to test. */ @RunWith(PowerMockRunner.class) @PrepareForTest( { StaticService.class, LogicAndTestInSameClassTest.class }) public class LogicAndTestInSameClassTest { private static String invokeMethod() { return StaticService.say("hello"); } @Test public void assertThatTestAndInstanceCanBeInSameClass() throws Exception { mockStatic(StaticService.class); String expected = "Hello altered World"; expect(StaticService.say("hello")).andReturn("Hello altered World"); replayAll(); assertEquals(expected, LogicAndTestInSameClassTest.invokeMethod()); verifyAll(); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/singleton/MockStaticTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.singleton; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.reflect.Whitebox; import samples.singleton.StaticHelper; import samples.singleton.StaticService; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.expectLastCall; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.powermock.api.easymock.PowerMock.*; /** * Test class to demonstrate static, static+final, static+native and * static+final+native methods mocking. * * @author Johan Haleby * @author Jan Kronquist */ @RunWith(PowerMockRunner.class) @PrepareForTest( { StaticService.class, StaticHelper.class }) public class MockStaticTest { @Test public void testMockStatic() throws Exception { mockStatic(StaticService.class); String expected = "Hello altered World"; expect(StaticService.say("hello")).andReturn("Hello altered World"); replay(StaticService.class); String actual = StaticService.say("hello"); verify(StaticService.class); assertEquals("Expected and actual did not match", expected, actual); // Singleton still be mocked by now. try { StaticService.say("world"); fail("Should throw AssertionError!"); } catch (AssertionError e) { assertEquals("\n Unexpected method call StaticService.say(\"world\"):", e.getMessage()); } } @Test public void testMockStaticFinal() throws Exception { mockStatic(StaticService.class); String expected = "Hello altered World"; expect(StaticService.sayFinal("hello")).andReturn("Hello altered World"); replay(StaticService.class); String actual = StaticService.sayFinal("hello"); verify(StaticService.class); assertEquals("Expected and actual did not match", expected, actual); // Singleton still be mocked by now. try { StaticService.sayFinal("world"); fail("Should throw AssertionError!"); } catch (AssertionError e) { assertEquals("\n Unexpected method call StaticService.sayFinal(\"world\"):", e.getMessage()); } } @Test public void testMockStaticNative() throws Exception { mockStatic(StaticService.class); String expected = "Hello altered World"; expect(StaticService.sayNative("hello")).andReturn("Hello altered World"); replay(StaticService.class); String actual = StaticService.sayNative("hello"); verify(StaticService.class); assertEquals("Expected and actual did not match", expected, actual); } @Test public void testMockStaticFinalNative() throws Exception { mockStatic(StaticService.class); String expected = "Hello altered World"; expect(StaticService.sayFinalNative("hello")).andReturn("Hello altered World"); replay(StaticService.class); String actual = StaticService.sayFinalNative("hello"); verify(StaticService.class); assertEquals("Expected and actual did not match", expected, actual); } @Test public void mockAStaticMethod() throws Exception { mockStatic(StaticService.class); String expected = "qwe"; expect(StaticService.doStatic(5)).andReturn(expected); replay(StaticService.class); String actual = StaticService.doStatic(5); assertEquals(expected, actual); verify(StaticService.class); } @Test public void mockMockStatic_times2() throws Exception { mockStatic(StaticHelper.class); StaticHelper.sayHelloHelper(); expectLastCall().times(2); replay(StaticHelper.class); StaticService.sayHello(); verify(StaticHelper.class); } @Test public void mockStaticCallingOtherStatic() throws Exception { mockStatic(StaticHelper.class); StaticHelper.sayHelloAgain(); expectLastCall().times(2); replay(StaticHelper.class); StaticService.sayHelloAgain(); verify(StaticHelper.class); } @Test public void testMockPrivateStatic() throws Exception { mockStaticPartial(StaticService.class, "sayPrivateStatic", String.class); final String expected = "Hello world"; expectPrivate(StaticService.class, "sayPrivateStatic", "name").andReturn(expected); replay(StaticService.class); String actual = Whitebox.invokeMethod(StaticService.class, "sayPrivateStatic", "name"); verify(StaticService.class); assertEquals(expected, actual); } @Test public void testMockPrivateFinalStatic() throws Exception { mockStaticPartial(StaticService.class, "sayPrivateFinalStatic", String.class); final String expected = "Hello world"; expectPrivate(StaticService.class, "sayPrivateFinalStatic", "name").andReturn(expected); replay(StaticService.class); String actual = Whitebox.invokeMethod(StaticService.class, "sayPrivateFinalStatic", "name"); verify(StaticService.class); assertEquals(expected, actual); } @Test public void testMockPrivateNativeFinalStatic() throws Exception { mockStaticPartial(StaticService.class, "sayPrivateNativeFinalStatic", String.class); final String expected = "Hello world"; expectPrivate(StaticService.class, "sayPrivateNativeFinalStatic", "name").andReturn(expected); replay(StaticService.class); String actual = Whitebox.invokeMethod(StaticService.class, "sayPrivateNativeFinalStatic", "name"); verify(StaticService.class); assertEquals(expected, actual); } @Test public void innerClassesWork() { assertEquals(17, StaticService.getNumberFromInner()); } @Test public void innerInstanceClassesWork() { assertEquals(23, StaticService.getNumberFromInnerInstance()); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/singleton/SimpleStaticServiceTest.java ================================================ package samples.junit4.singleton; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.singleton.SimpleStaticService; import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.powermock.api.easymock.PowerMock.*; @RunWith(PowerMockRunner.class) @PrepareForTest(SimpleStaticService.class) public class SimpleStaticServiceTest { @Test public void testMockStatic() throws Exception { mockStatic(SimpleStaticService.class); final String expected = "Hello altered World"; expect(SimpleStaticService.say("hello")).andReturn("Hello altered World"); replay(SimpleStaticService.class); final String actual = SimpleStaticService.say("hello"); verify(SimpleStaticService.class); assertEquals("Expected and actual did not match", expected, actual); // Singleton still be mocked by now. try { SimpleStaticService.say("world"); fail("Should throw AssertionError!"); } catch (final AssertionError e) { assertEquals("\n Unexpected method call SimpleStaticService.say(\"world\"):", e.getMessage()); } } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/stackoverflow/EvilHashCode.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.stackoverflow; public class EvilHashCode { //Required to produce error public String s = returnS(); public String returnS() { return "s"; } @Override public int hashCode() { return evilHashCode(); } public int evilHashCode() { return 3; } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/stackoverflow/StackOverFlowTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.stackoverflow; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; /** * Make sure we don't get a stackOverFlowError here. Thanks to ride.sputnik for * reporting this! */ @RunWith(PowerMockRunner.class) @PrepareForTest(EvilHashCode.class) public class StackOverFlowTest { @Test public void testStackOverFlowShouldNotOccur() throws Exception { new EvilHashCode(); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/staticandinstance/StaticAndInstanceDemoTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.staticandinstance; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.staticandinstance.StaticAndInstanceDemo; import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertEquals; import static org.powermock.api.easymock.PowerMock.*; @RunWith(PowerMockRunner.class) @PrepareForTest(StaticAndInstanceDemo.class) public class StaticAndInstanceDemoTest { @Test public void testMockStaticMethodAndInstanceMethod() throws Exception { mockStaticPartial(StaticAndInstanceDemo.class, "getStaticMessage"); StaticAndInstanceDemo tested = createPartialMock(StaticAndInstanceDemo.class, "getPrivateMessage"); final String staticExpected = "a static message"; expect(StaticAndInstanceDemo.getStaticMessage()).andReturn( staticExpected); final String privateExpected = "A private message "; expectPrivate(tested, "getPrivateMessage").andReturn(privateExpected); replay(tested); replay(StaticAndInstanceDemo.class); String actual = tested.getMessage(); verify(tested); verify(StaticAndInstanceDemo.class); assertEquals(privateExpected + staticExpected, actual); } @Test public void testMockPrivateButNotStatic() throws Exception { StaticAndInstanceDemo tested = createPartialMock(StaticAndInstanceDemo.class, "getPrivateMessage"); final String privateExpected = "A private message "; expectPrivate(tested, "getPrivateMessage").andReturn(privateExpected); replay(tested); String actual = tested.getMessage(); verify(tested); assertEquals(privateExpected + "hello world!", actual); } @Test public void testMockStaticButNotInstance() throws Exception { StaticAndInstanceDemo tested = new StaticAndInstanceDemo(); mockStaticPartial(StaticAndInstanceDemo.class, "getStaticMessage"); final String staticExpected = "static message"; expect(StaticAndInstanceDemo.getStaticMessage()).andReturn( staticExpected); replay(StaticAndInstanceDemo.class); String actual = tested.getMessage(); verify(StaticAndInstanceDemo.class); assertEquals("Private " + staticExpected, actual); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/staticandinstance/StaticAndInstanceWithConstructorCodeDemoTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.staticandinstance; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.staticandinstance.StaticAndInstanceDemo; import samples.staticandinstance.StaticAndInstanceWithConstructorCodeDemo; import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertEquals; import static org.powermock.api.easymock.PowerMock.*; /** * The purpose of this test class is to verify that the * http://code.google.com/p/powermock/issues/detail?id=4 is fixed. * */ @RunWith(PowerMockRunner.class) @PrepareForTest(StaticAndInstanceDemo.class) public class StaticAndInstanceWithConstructorCodeDemoTest { @Test public void testStaticAndInstanceWithConstructor() throws Exception { StaticAndInstanceDemo staticAndInstanceDemoMock = createMock(StaticAndInstanceDemo.class); StaticAndInstanceWithConstructorCodeDemo tested = new StaticAndInstanceWithConstructorCodeDemo( staticAndInstanceDemoMock); niceReplayAndVerify(); mockStaticPartial(StaticAndInstanceDemo.class, "getStaticMessage"); final String instanceExpected = "value"; expect(staticAndInstanceDemoMock.getMessage()).andReturn( instanceExpected); final String staticExpected = "a static message"; expect(StaticAndInstanceDemo.getStaticMessage()).andReturn( staticExpected); replay(StaticAndInstanceDemo.class, staticAndInstanceDemoMock, tested); String actual = tested.getMessage(); verify(StaticAndInstanceDemo.class, staticAndInstanceDemoMock, tested); assertEquals(staticExpected + instanceExpected, actual); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/staticinitializer/AbstractStaticInitializerTest.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.staticinitializer; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor; import org.powermock.modules.junit4.PowerMockRunner; import samples.staticinitializer.AbstractStaticInitializerExample; import static org.junit.Assert.assertEquals; @RunWith(PowerMockRunner.class) @SuppressStaticInitializationFor("samples.staticinitializer.AbstractStaticInitializerExample") public class AbstractStaticInitializerTest { @Test public void suppressStaticInitializerInAbstractClass() throws Exception { assertEquals("something", AbstractStaticInitializerExample.getStaticString()); } @Test public void suppressStaticInitializerInAbstractClassWhenInstantiated() throws Exception { AbstractStaticInitializerExample tested = new AbstractStaticInitializerExample() {}; assertEquals("something", tested.getString()); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/staticinitializer/EvilStaticInitializerExampleTest.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.staticinitializer; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor; import org.powermock.modules.junit4.PowerMockRunner; import samples.staticinitializer.EvilStaticInitializerExample; import static org.hamcrest.core.IsInstanceOf.instanceOf; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; /** * Test that demonstrates a (naive) example of when chunking may be handy. */ @RunWith(PowerMockRunner.class) public class EvilStaticInitializerExampleTest { @Test @SuppressStaticInitializationFor("samples.staticinitializer.EvilStaticInitializerExample") public void assertNativeCodeInvocationWorks() { EvilStaticInitializerExample tested = new EvilStaticInitializerExample(); assertThat(tested.doSomeNativeStuffUsingTheLoadedSystemLibrary(), instanceOf(String.class)); } @Test public void assertCorrectErrorMessageIfLibraryNotFound() { try { new EvilStaticInitializerExample(); fail("Should throw unsatisfied link error!"); } catch (UnsatisfiedLinkError error) { assertEquals(error.getMessage(), EvilStaticInitializerExample.FAILED_TO_LOAD_LIBRARY_MESSAGE); } } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/staticinitializer/InterfaceStaticInitializerExampleTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.staticinitializer; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor; import org.powermock.modules.junit4.PowerMockRunner; import samples.staticinitializer.InterfaceComputation; import static org.junit.Assert.assertEquals; @RunWith(PowerMockRunner.class) @SuppressStaticInitializationFor( { "samples.staticinitializer.InterfaceA", "samples.staticinitializer.InterfaceB", "samples.staticinitializer.InterfaceC" }) public class InterfaceStaticInitializerExampleTest { @Test public void testSupressStaticInitializer() throws Exception { assertEquals(0, InterfaceComputation.calculateWithinHierarchy()); } @Test public void testSupressStaticInitializer2() throws Exception { assertEquals(0, InterfaceComputation.calculateWithReference()); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/staticinitializer/StaticInitializerExampleTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.staticinitializer; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.reflect.Whitebox; import samples.staticinitializer.StaticInitializerExample; import java.util.HashSet; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; @RunWith(PowerMockRunner.class) @SuppressStaticInitializationFor("samples.staticinitializer.StaticInitializerExample") public class StaticInitializerExampleTest { @Test public void testSupressStaticInitializerAndSetFinalField() throws Exception { assertNull("Should be null because the static initializer should be suppressed", StaticInitializerExample.getMySet()); final HashSet hashSet = new HashSet(); Whitebox.setInternalState(StaticInitializerExample.class, "mySet", hashSet); assertSame(hashSet, Whitebox.getInternalState(StaticInitializerExample.class, "mySet")); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/strict/StrictDemoTest.java ================================================ package samples.junit4.strict; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.strict.StrictDemo; import static org.powermock.api.easymock.PowerMock.*; /** * This is a simple test case for the {@link StrictDemo} class that demonstrates * that strict method mocking works. * */ @RunWith(PowerMockRunner.class) @PrepareForTest(StrictDemo.class) public class StrictDemoTest { @Test public void testCallB_notStrict() throws Exception { StrictDemo tested = createPartialMock(StrictDemo.class, "A", "B"); expectPrivate(tested, "B").times(1); expectPrivate(tested, "A").times(1); replay(tested); tested.callAThenB(); verify(tested); } @Test(expected = AssertionError.class) public void testCallB_strict_failure() throws Exception { StrictDemo tested = createStrictPartialMock(StrictDemo.class, "A", "B"); expectPrivate(tested, "B").times(1); expectPrivate(tested, "A").times(1); replay(tested); tested.callAThenB(); verify(tested); } @Test public void testCallB_strict_ok() throws Exception { StrictDemo tested = createStrictPartialMock(StrictDemo.class, "A", "B"); expectPrivate(tested, "A").times(1); expectPrivate(tested, "B").times(1); replay(tested); tested.callAThenB(); verify(tested); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/stubmethod/StubMethodTest.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.stubmethod; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.reflect.exceptions.MethodNotFoundException; import org.powermock.reflect.exceptions.TooManyMethodsFoundException; import samples.suppressmethod.SuppressMethod; import static junit.framework.Assert.fail; import static org.junit.Assert.assertEquals; import static org.powermock.api.support.membermodification.MemberMatcher.method; import static org.powermock.api.support.membermodification.MemberModifier.stub; @RunWith(PowerMockRunner.class) @PrepareForTest(SuppressMethod.class) public class StubMethodTest { @Test public void whenStubbingInstanceMethodTheMethodReturnsTheStubbedValue() throws Exception { String expectedValue = "Hello"; stub(method(SuppressMethod.class, "getObject")).toReturn(expectedValue); SuppressMethod tested = new SuppressMethod(); assertEquals(expectedValue, tested.getObject()); assertEquals(expectedValue, tested.getObject()); } @Test public void whenStubbingStaticMethodTheMethodReturnsTheStubbedValue() throws Exception { String expectedValue = "Hello"; stub(method(SuppressMethod.class, "getObjectStatic")).toReturn(expectedValue); assertEquals(expectedValue, SuppressMethod.getObjectStatic()); assertEquals(expectedValue, SuppressMethod.getObjectStatic()); } @Test public void whenStubbingInstanceMethodWithPrimiteValueTheMethodReturnsTheStubbedValue() throws Exception { float expectedValue = 4; stub(method(SuppressMethod.class, "getFloat")).toReturn(expectedValue); SuppressMethod tested = new SuppressMethod(); assertEquals(expectedValue, tested.getFloat(), 0.0f); assertEquals(expectedValue, tested.getFloat(), 0.0f); } @Test(expected = TooManyMethodsFoundException.class) public void whenSeveralMethodsFoundThenTooManyMethodsFoundExceptionIsThrown() throws Exception { stub(method(SuppressMethod.class, "sameName")); } @Test(expected = MethodNotFoundException.class) public void whenNoMethodsFoundThenMethodNotFoundExceptionIsThrown() throws Exception { stub(method(SuppressMethod.class, "notFound")); } @Test public void whenStubbingInstanceMethodByPassingTheMethodTheMethodReturnsTheStubbedValue() throws Exception { String expected = "Hello"; stub(method(SuppressMethod.class, "getObject")).toReturn(expected); SuppressMethod tested = new SuppressMethod(); assertEquals(expected, tested.getObject()); assertEquals(expected, tested.getObject()); } @Test public void whenStubbingStaticMethodByPassingTheMethodTheMethodReturnsTheStubbedValue() throws Exception { String expected = "Hello"; stub(method(SuppressMethod.class, "getObjectStatic")).toReturn(expected); assertEquals(expected, SuppressMethod.getObjectStatic()); assertEquals(expected, SuppressMethod.getObjectStatic()); } @Test(expected = ClassCastException.class) public void whenStubbingInstanceMethodWithWrongReturnTypeThenClasscastExceptionIsThrown() throws Exception { String illegalReturnType = "Hello"; stub(method(SuppressMethod.class, "getFloat")).toReturn(illegalReturnType); SuppressMethod tested = new SuppressMethod(); tested.getFloat(); } @Test public void whenStubbingInstanceMethodToThrowExceptionTheMethodThrowsTheStubbedException() throws Exception { Exception expected = new Exception("message"); stub(method(SuppressMethod.class, "getObject")).toThrow(expected); SuppressMethod tested = new SuppressMethod(); try { tested.getObject(); fail(); } catch (Exception e) { assertEquals("message", e.getMessage()); } } @Test public void whenStubbingStaticMethodToThrowExceptionTheMethodThrowsTheStubbedException() throws Exception { Exception expected = new Exception("message"); stub(method(SuppressMethod.class, "getObjectStatic")).toThrow(expected); try { SuppressMethod.getObjectStatic(); fail(); } catch (Exception e) { assertEquals("message", e.getMessage()); } } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/suppressconstructor/CreateUnmockedTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.suppressconstructor; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.easymock.PowerMock; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.reflect.Whitebox; import samples.suppressconstructor.SuppressConstructorDemo; import samples.suppressconstructor.SuppressSpecificConstructorDemo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; @RunWith(PowerMockRunner.class) public class CreateUnmockedTest { @Test public void testUnmockedWithNoConstructorAndReplayVerify() throws Exception { SuppressSpecificConstructorDemo object = Whitebox.newInstance(SuppressSpecificConstructorDemo.class); PowerMock.niceReplayAndVerify(); PowerMock.replay(object); assertEquals("Hello", object.getHello()); PowerMock.verify(object); } @Test public void testUnmockedWithConstructorAndAllowReplay() throws Exception { PowerMock.niceReplayAndVerify(); SuppressConstructorDemo object = new SuppressConstructorDemo("Hello"); PowerMock.replay(object); assertEquals("Hello", object.getMessage()); PowerMock.verify(object); } @Test public void testUnmockedWithReplayCausesException() throws Exception { SuppressConstructorDemo object = new SuppressConstructorDemo("Hello"); try { PowerMock.replay(object); fail("Replay should only work on mocks"); } catch (RuntimeException e) { // ignore } } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/suppressconstructor/SuppressConstructorDemoTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.suppressconstructor; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.easymock.PowerMock; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.suppressconstructor.SuppressConstructorDemo; import samples.suppressconstructor.SuppressConstructorSubclassDemo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.powermock.api.easymock.PowerMock.*; import static org.powermock.api.support.membermodification.MemberMatcher.constructor; import static org.powermock.api.support.membermodification.MemberModifier.suppress; /** * This test demonstrates how to tell PowerMock to avoid executing constructor * code for a certain class. This is crucial in certain tests where the * constructor or a subclass's constructor performs operations that are of no * concern to the unit test of the actual class or if the constructor performs * operations, such as getting services from a runtime environment that has not * been initialized. In normal situations you're forced to create an integration * or function test for the class instead (and thus the runtime environment is * available). This is not particularly good when it comes to testing method * logic. PowerMock solves these problems by letting you specify the * {@link PowerMock#suppressConstructor(Class...)} method */ @RunWith(PowerMockRunner.class) @PrepareForTest(SuppressConstructorDemo.class) public class SuppressConstructorDemoTest { /** * This test makes sure that the real constructor has never been called. */ @Test public void testSuppressConstructor() throws Exception { suppress(constructor(SuppressConstructorDemo.class)); final SuppressConstructorDemo tested = new SuppressConstructorDemo("a message"); assertNull("Message should have been null since we're skipping the execution of the constructor code.", tested.getMessage()); } /** * This test makes sure that the real parent constructor has never been * called. */ @Test public void testSuppressParentConstructor() throws Exception { suppress(constructor(SuppressConstructorSubclassDemo.class)); final SuppressConstructorDemo tested = new SuppressConstructorDemo("a message"); assertNull("Message should have been null since we're skipping the execution of the constructor code.", tested.getMessage()); } /** * This test makes sure that it's possible to also mock methods from the * class under test at the same time as skipping constructor execution. */ @Test public void testPartialMockingAndSuppressParentConstructor() throws Exception { suppress(constructor(SuppressConstructorSubclassDemo.class)); final SuppressConstructorDemo tested = createPartialMock(SuppressConstructorDemo.class, "returnAMessage"); final String expected = "Hello world!"; expectPrivate(tested, "returnAMessage").andReturn(expected); replay(tested); final String actual = tested.getMyOwnMessage(); verify(tested); assertEquals(expected, actual); assertNull("Message should have been null since we're skipping the execution of the constructor code.", tested.getMessage()); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/suppressconstructor/SuppressConstructorHierarchyDemoTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.suppressconstructor; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.suppressconstructor.InvokeConstructor; import samples.suppressconstructor.SuppressConstructorHierarchy; import static org.junit.Assert.*; import static org.powermock.api.support.membermodification.MemberMatcher.constructor; import static org.powermock.api.support.membermodification.MemberModifier.suppress; @PrepareForTest(SuppressConstructorHierarchy.class) @RunWith(PowerMockRunner.class) public class SuppressConstructorHierarchyDemoTest { @Test public void testSuppressConstructorHierarchy() throws Exception { suppress(constructor(SuppressConstructorHierarchy.class)); final String message = new InvokeConstructor().doStuff("qwe"); assertNull("Message should have been null since we're skipping the execution of the constructor code. Message was \"" + message + "\".", message); } @Test @PrepareForTest public void testNotSuppressConstructorWithoutByteCodeManipulation() throws Exception { try { new SuppressConstructorHierarchy("message"); fail("Should throw RuntimeException since we're running this test with a new class loader!"); } catch (RuntimeException e) { assertEquals("This should be suppressed!!", e.getMessage()); } } @Test public void testNotSuppressConstructorWithByteCodeManipulation() throws Exception { try { new SuppressConstructorHierarchy("message"); fail("Should throw RuntimeException since we're running this test with a new class loader!"); } catch (RuntimeException e) { assertEquals("This should be suppressed!!", e.getMessage()); } } /** * This simple test demonstrate that it's possible to continue execution * with the default {@code PrepareForTest} settings (i.e. using a * byte-code manipulated version of the SuppressConstructorHierarchyDemo * class). */ @Test public void testSuppressConstructorHierarchyAgain() throws Exception { suppress(constructor(SuppressConstructorHierarchy.class)); SuppressConstructorHierarchy tested = new SuppressConstructorHierarchy("message"); assertEquals(42, tested.getNumber()); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/suppressconstructor/SuppressNonParentConstructorDemoTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.suppressconstructor; import org.junit.Test; import org.powermock.reflect.Whitebox; import samples.suppressconstructor.SuppressNonParentConstructorDemo; import static org.junit.Assert.assertEquals; public class SuppressNonParentConstructorDemoTest { @Test public void testNewInstanceWithoutInvokingConstructor() throws Exception { SuppressNonParentConstructorDemo constructorDemo = Whitebox .newInstance(SuppressNonParentConstructorDemo.class); assertEquals("Hello", constructorDemo.getHello()); } @Test(expected = IllegalStateException.class) public void testNewInstanceInvokingConstructor() throws Exception { new SuppressNonParentConstructorDemo("failing"); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/suppressfield/ItemRepositoryTest.java ================================================ package samples.junit4.suppressfield; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.reflect.Whitebox; import samples.suppressfield.ItemRepository; import static org.powermock.api.support.membermodification.MemberMatcher.field; import static org.powermock.api.support.membermodification.MemberMatcher.fields; import static org.powermock.api.support.membermodification.MemberModifier.suppress; @RunWith(PowerMockRunner.class) @PrepareForTest( { ItemRepository.class }) @SuppressStaticInitializationFor("samples.suppressfield.ItemRepository") public class ItemRepositoryTest { @Test(expected = NullPointerException.class) public void testaddItem() throws Exception { suppress(fields(field(ItemRepository.class, "itemMap"), field(ItemRepository.class, "totalItems"))); ItemRepository objRep = Whitebox.newInstance(ItemRepository.class); objRep.addItem("key", "value"); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/suppressfield/SuppressFieldTest.java ================================================ package samples.junit4.suppressfield; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.suppressfield.SuppressField; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.powermock.api.support.membermodification.MemberMatcher.field; import static org.powermock.api.support.membermodification.MemberMatcher.fields; import static org.powermock.api.support.membermodification.MemberModifier.suppress; /** * Unit tests that asserts that field suppression works. */ @RunWith(PowerMockRunner.class) @PrepareForTest(SuppressField.class) public class SuppressFieldTest { @Test public void assertThatSpecificStaticFinalFieldSuppressionWorks() throws Exception { suppress(field(SuppressField.class, "MY_OBJECT")); assertNull(SuppressField.getMyObject()); } @Ignore("Final primitive types doesn't work, see issue at https://github.com/jayway/powermock/issues/105") @Test public void assertThatSpecificStaticFinalPrimitiveFieldSuppressionWorks() throws Exception { suppress(field(SuppressField.class, "MY_VALUE")); assertEquals(0, SuppressField.getMyValue()); } @Ignore("Final primitive types doesn't work, see issue at https://github.com/jayway/powermock/issues/105") @Test public void assertThatSpecificInstanceFinalPrimitiveFieldSuppressionWorks() throws Exception { suppress(field(SuppressField.class, "myBoolean")); SuppressField suppressField = new SuppressField(); assertEquals(false, suppressField.isMyBoolean()); } @Test public void assertThatSpecificInstanceFinalFieldSuppressionWorks() throws Exception { suppress(field(SuppressField.class, "myWrappedBoolean")); SuppressField suppressField = new SuppressField(); assertNull(suppressField.getMyWrappedBoolean()); } @Test public void assertThatSpecificPrimitiveInstanceFieldSuppressionWorks() throws Exception { suppress(field(SuppressField.class, "myChar")); SuppressField suppressField = new SuppressField(); assertEquals(' ', suppressField.getMyChar()); } @Test public void assertThatSpecificInstanceFieldSuppressionWorks() throws Exception { suppress(field(SuppressField.class, "mySecondValue")); SuppressField suppressField = new SuppressField(); assertNull(suppressField.getMySecondValue()); } @Test public void assertThatSpecificInstanceFieldSuppressionWhenSpecifingClassAndFieldNameWorks() throws Exception { suppress(field(SuppressField.class, "mySecondValue")); SuppressField suppressField = new SuppressField(); assertNull(suppressField.getMySecondValue()); } @Test public void assertThatMultipleInstanceFieldSuppressionWorks() throws Exception { suppress(fields(SuppressField.class, "mySecondValue", "myChar")); SuppressField suppressField = new SuppressField(); assertNull(suppressField.getMySecondValue()); assertEquals(' ', suppressField.getMyChar()); assertEquals(Boolean.TRUE, suppressField.getMyWrappedBoolean()); } // TODO Add final tests here as well when they work @Test public void assertThatAllFieldSuppressionWorks() throws Exception { suppress(fields(SuppressField.class)); SuppressField suppressField = new SuppressField(); assertNull(suppressField.getMySecondValue()); assertEquals(' ', suppressField.getMyChar()); assertNull(suppressField.getMyWrappedBoolean()); assertNull(SuppressField.getMyObject()); } @Test public void assertThatObjectIsNeverInstansiated() throws Exception { suppress(field(SuppressField.class, "domainObject")); SuppressField suppressField = new SuppressField(); assertNull(suppressField.getDomainObject()); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/suppressmethod/SuppressMethodTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.suppressmethod; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.singleton.StaticExample; import samples.suppressmethod.SuppressMethod; import samples.suppressmethod.SuppressMethodExample; import samples.suppressmethod.SuppressMethodParent; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.powermock.api.support.membermodification.MemberMatcher.method; import static org.powermock.api.support.membermodification.MemberMatcher.methods; import static org.powermock.api.support.membermodification.MemberMatcher.methodsDeclaredIn; import static org.powermock.api.support.membermodification.MemberModifier.suppress; @RunWith(PowerMockRunner.class) @PrepareForTest( { SuppressMethod.class, SuppressMethodExample.class, StaticExample.class }) public class SuppressMethodTest { @Test public void testGetObject() throws Exception { suppress(method(SuppressMethod.class, "getObject")); SuppressMethod tested = new SuppressMethod(); assertNull("A method returning Object should return null after suppressing method code.", tested.getObject()); } @Test public void testSuppressMultipleMethods() throws Exception { suppress(methods(SuppressMethod.class, "getObject", "getShort")); SuppressMethod tested = new SuppressMethod(); assertNull("A method returning Object should return null after suppressing method code.", tested.getObject()); assertEquals("A method returning a short should return 0 after suppressing method code.", 0, tested.getShort()); } @Test public void testGetObjectStatic() throws Exception { suppress(method(SuppressMethod.class, "getObjectStatic")); assertNull("A method returning Object should return null after suppressing method code.", SuppressMethod .getObjectStatic()); } @Test public void testGetByte() throws Exception { suppress(method(SuppressMethod.class, "getByte")); SuppressMethod tested = new SuppressMethod(); assertEquals("A method returning a byte should return 0 after suppressing method code.", 0, tested.getByte()); } @Test public void testGetShort() throws Exception { suppress(method(SuppressMethod.class, "getShort")); SuppressMethod tested = new SuppressMethod(); assertEquals("A method returning a short should return 0 after suppressing method code.", 0, tested.getShort()); } @Test public void testGetInt() throws Exception { suppress(method(SuppressMethod.class, "getInt")); SuppressMethod tested = new SuppressMethod(); assertEquals("A method returning an int should return 0 after suppressing method code.", 0, tested.getInt()); } @Test public void testGetLong() throws Exception { suppress(method(SuppressMethod.class, "getLong")); SuppressMethod tested = new SuppressMethod(); assertEquals("A method returning a long should return 0 after suppressing method code.", 0, tested.getLong()); } @Test public void testGetBoolean() throws Exception { suppress(method(SuppressMethod.class, "getBoolean")); SuppressMethod tested = new SuppressMethod(); assertFalse("A method returning a boolean should return false after suppressing method code.", tested .getBoolean()); } @Test public void testGetFloat() throws Exception { suppress(method(SuppressMethod.class, "getFloat")); SuppressMethod tested = new SuppressMethod(); assertEquals("A method returning a float should return 0.0f after suppressing method code.", 0.0f, tested .getFloat(), 0); } @Test public void testGetDouble() throws Exception { suppress(method(SuppressMethod.class, "getDouble")); SuppressMethod tested = new SuppressMethod(); assertEquals("A method returning a double should return 0.0d after suppressing method code.", 0.0d, tested .getDouble(), 0); } @Test public void testGetDouble_parameter() throws Exception { suppress(method(SuppressMethod.class, "getDouble", new Class[] { double.class })); SuppressMethod tested = new SuppressMethod(); assertEquals("A method returning a double should return 0.0d after suppressing method code.", 0.0d, tested .getDouble(8.7d), 0); } @Test public void testInvokeVoid() throws Exception { suppress(method(SuppressMethod.class, "invokeVoid", new Class[] { StringBuilder.class })); SuppressMethod tested = new SuppressMethod(); // Should not cause an NPE when suppressing code. tested.invokeVoid(null); } @Test public void testInvokeVoid_noParameterTypeSupplied() throws Exception { suppress(method(SuppressMethod.class, "invokeVoid")); SuppressMethod tested = new SuppressMethod(); // Should not cause an NPE when suppressing code. tested.invokeVoid(null); } @Test public void suppressAllMethodsInMultipleClasses() throws Exception { suppress(methodsDeclaredIn(SuppressMethod.class, SuppressMethodExample.class)); SuppressMethod tested1 = new SuppressMethod(); SuppressMethodExample tested2 = new SuppressMethodExample(); // Should not cause an NPE when suppressing code. tested1.invokeVoid(null); assertNull(tested1.getObject()); assertEquals(0, tested1.getInt()); assertNull(tested2.getObject()); } @Test public void suppressPublicStaticMethod() throws Exception { suppress(method(StaticExample.class, "staticVoidMethod")); StaticExample.staticVoidMethod(); } @Test public void suppressOverridingMethod() throws Exception { suppress(method(SuppressMethod.class, "myMethod")); SuppressMethod tested = new SuppressMethod(); assertEquals(0, tested.myMethod()); } @Test public void testSuppressMethodInParentOnly() throws Exception { suppress(method(SuppressMethodParent.class, "myMethod")); SuppressMethod tested = new SuppressMethod(); assertEquals(20, tested.myMethod()); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/swing/ReallySimpleSwingDemoTest.java ================================================ package samples.junit4.swing; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.swing.ReallySimpleSwingDemo; import javax.swing.*; import static org.junit.Assume.assumeTrue; import static org.powermock.api.easymock.PowerMock.*; /** * Unit test that makes sure that PowerMock works with Swing components. */ @RunWith(PowerMockRunner.class) @PrepareForTest(JOptionPane.class) public class ReallySimpleSwingDemoTest { @Test public void assertThatPowerMockWorksWithSwingComponents() throws Exception { // Currently this tests fails on Java 8, see issue 504. assumeTrue(Float.valueOf(System.getProperty("java.specification.version")) < 1.8f); final String message = "powermock"; mockStatic(JOptionPane.class); JOptionPane.showMessageDialog(null, message); expectLastCall().once(); replayAll(); new ReallySimpleSwingDemo().displayMessage(message); verifyAll(); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/system/FieldMockDefect.java ================================================ package samples.junit4.system; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.lang.reflect.Field; import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertEquals; import static org.powermock.api.easymock.PowerMock.*; /** * * The reason why it fails is because we create a new instance of the field * using Whitebox but then hashCode doesn't work because it's missing * constructor args. *

* * if (Field.class.isAssignableFrom(mock.getClass())) { * Whitebox.setInternalState(mock, "clazz", (Object) Object.class); * Whitebox.setInternalState(mock, "name", Object.class.getName()); } * */ @RunWith(PowerMockRunner.class) @PrepareForTest(Field.class) public class FieldMockDefect { @Test public void test() { final Field fieldMock = createMock(Field.class); expect(fieldMock.getName()).andReturn("foo"); replayAll(); assertEquals("foo", new ClassUnderTest().foo(fieldMock)); verifyAll(); } private static final class ClassUnderTest { public String foo(Field field) { return field.getName(); } } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/system/SystemClassUserTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.system; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.system.SystemClassUser; import java.net.InetAddress; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import java.util.Collections; import java.util.LinkedList; import java.util.List; import static org.easymock.EasyMock.anyLong; import static org.easymock.EasyMock.expect; import static org.junit.Assert.*; import static org.powermock.api.easymock.PowerMock.*; /** * Demonstrates PowerMock's ability to mock non-final and final system classes. * To mock a system class you need to prepare the calling class for testing. * I.e. let's say you're testing class A which interacts with URLEncoder then * you would do: * *

 *
 * @PrepareForTest({A.class})
 *
 * 
*/ @RunWith(PowerMockRunner.class) @PrepareForTest( { SystemClassUser.class }) public class SystemClassUserTest { @Test public void assertThatMockingOfNonFinalSystemClassesWorks() throws Exception { mockStatic(URLEncoder.class); expect(URLEncoder.encode("string", "enc")).andReturn("something"); replayAll(); assertEquals("something", new SystemClassUser().performEncode()); verifyAll(); } @Test public void assertThatMockingOfTheRuntimeSystemClassWorks() throws Exception { mockStatic(Runtime.class); Runtime runtimeMock = createMock(Runtime.class); Process processMock = createMock(Process.class); expect(Runtime.getRuntime()).andReturn(runtimeMock); expect(runtimeMock.exec("command")).andReturn(processMock); replayAll(); assertSame(processMock, new SystemClassUser().executeCommand()); verifyAll(); } @Test public void assertThatMockingOfFinalSystemClassesWorks() throws Exception { mockStatic(System.class); expect(System.getProperty("property")).andReturn("my property"); replayAll(); assertEquals("my property", new SystemClassUser().getSystemProperty()); verifyAll(); } @Test public void assertThatPartialMockingOfFinalSystemClassesWorks() throws Exception { mockStaticPartial(System.class, "nanoTime"); expect(System.nanoTime()).andReturn(2L); replayAll(); new SystemClassUser().doMoreComplicatedStuff(); assertEquals("2", System.getProperty("nanoTime")); verifyAll(); } @Test public void assertThatMockingOfCollectionsWork() throws Exception { List list = new LinkedList(); mockStatic(Collections.class); Collections.shuffle(list); expectLastCall().once(); replayAll(); new SystemClassUser().shuffleCollection(list); verifyAll(); } @Test public void assertThatPartialMockingOfFinalSystemClassesWorksForNonVoidMethods() throws Exception { mockStaticPartial(System.class, "getProperty"); expect(System.getProperty("property")).andReturn("my property"); replayAll(); final SystemClassUser systemClassUser = new SystemClassUser(); systemClassUser.copyProperty("to", "property"); verifyAll(); } @Test public void assertThatMockingStringWorks() throws Exception { mockStatic(String.class); final String string = "string"; final String args = "args"; final String returnValue = "returnValue"; expect(String.format(string, args)).andReturn(returnValue); replayAll(); final SystemClassUser systemClassUser = new SystemClassUser(); assertEquals(systemClassUser.format(string, args), returnValue); verifyAll(); } @Test public void mockingStaticVoidMethodWorks() throws Exception { mockStatic(Thread.class); Thread.sleep(anyLong()); expectLastCall().once(); replayAll(); long startTime = System.currentTimeMillis(); final SystemClassUser systemClassUser = new SystemClassUser(); systemClassUser.threadSleep(); long endTime = System.currentTimeMillis(); assertTrue(endTime - startTime < 5000); verifyAll(); } @Test public void mockingInstanceMethodOfFinalSystemClassWorks() throws Exception { URL url = createMock(URL.class); URLConnection urlConnection = createMock(URLConnection.class); expect(url.openConnection()).andStubReturn(urlConnection); replayAll(); final SystemClassUser systemClassUser = new SystemClassUser(); assertSame(urlConnection, systemClassUser.useURL(url)); verifyAll(); } @Test public void mockingURLWorks() throws Exception { URL url = createMock(URL.class); URLConnection urlConnectionMock = createMock(URLConnection.class); expect(url.openConnection()).andReturn(urlConnectionMock); replayAll(); assertSame(url.openConnection(), urlConnectionMock); verifyAll(); } @Test public void mockingFinalMethodsInSystemClassesWorks() throws Exception { ClassLoader cl1 = createMock(ClassLoader.class); ClassLoader cl2 = createMock(ClassLoader.class); expect(cl1.getParent()).andReturn(cl2); replayAll(); assertSame(cl1.getParent(), cl2); verifyAll(); } @Test public void mockingInetAddressWorks() throws Exception { final InetAddress mock = createMock(InetAddress.class); mockStatic(InetAddress.class); expect(InetAddress.getLocalHost()).andReturn(mock); replayAll(); final SystemClassUser systemClassUser = new SystemClassUser(); assertSame(mock, systemClassUser.getLocalHost()); verifyAll(); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/testhierarchy/RunWithHierarchyTest.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.testhierarchy; import org.junit.Test; import org.powermock.core.classloader.annotations.PrepareForTest; import samples.finalmocking.FinalDemo; //@RunWith(PowerMockRunner.class) @PrepareForTest(FinalDemo.class) public class RunWithHierarchyTest extends TestParent { @Test public void testname() throws Exception { } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/testhierarchy/TestParent.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.testhierarchy; import org.junit.runner.RunWith; import org.powermock.modules.junit4.PowerMockRunner; @RunWith(PowerMockRunner.class) public abstract class TestParent { } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/verify/AssertVerifyWorksTest.java ================================================ package samples.junit4.verify; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.singleton.StaticHelper; import samples.singleton.StaticService; import static org.easymock.EasyMock.expectLastCall; import static org.powermock.api.easymock.PowerMock.*; /** * This test asserts that the * http://code.google.com/p/powermock/issues/detail?id=73 issue is resolved. */ @RunWith(PowerMockRunner.class) @PrepareForTest( { StaticHelper.class, StaticService.class }) public class AssertVerifyWorksTest { @Test public void testMockStaticWorks() throws Exception { mockStaticPartial(StaticService.class, "sayHello"); mockStatic(StaticHelper.class); StaticService.sayHello(); expectLastCall().once(); StaticHelper.sayHelloHelper(); expectLastCall().once(); replay(StaticService.class); replay(StaticHelper.class); StaticService.assertThatVerifyWorksForMultipleMocks(); verify(StaticService.class); verify(StaticHelper.class); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/junit4/whitebox/PowerMockConstructorFiltrationTest.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.whitebox; import org.junit.Test; import org.powermock.reflect.internal.WhiteboxImpl; import samples.whitebox.ClassWithPowerMockGeneratedConstructor; import java.lang.reflect.Constructor; import static org.junit.Assert.assertEquals; public class PowerMockConstructorFiltrationTest { @Test public void findUniqueConstructorOrThrowExceptionFiltersPowerMockConstructors() throws Exception { Constructor actualConstructor = WhiteboxImpl.findUniqueConstructorOrThrowException(ClassWithPowerMockGeneratedConstructor.class, (Object) null); assertEquals(ClassWithPowerMockGeneratedConstructor.class.getConstructor(String.class), actualConstructor); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/methodhierarchy/MethodInvocationDemoTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.methodhierarchy; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.reflect.Whitebox; import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertEquals; import static org.powermock.api.easymock.PowerMock.*; /** * Test that verifies that it's possible to invoke and create partial mocks of * private and/protected methods in a hierarchy. */ @RunWith(PowerMockRunner.class) @PrepareForTest( { MethodInvocationDemo.class }) public class MethodInvocationDemoTest { @Test public void testCreatePartialMockForAProtectedMethodInASubclass() throws Exception { final String value = "another string"; final String getTheStringMethodName = "getTheString"; MethodInvocationDemo tested = createPartialMock(MethodInvocationDemo.class, getTheStringMethodName); expect(tested.getTheString()).andReturn(value); replay(tested); assertEquals(value, Whitebox.invokeMethod(tested, "getString")); verify(tested); } @Test @Ignore("Mabey this is impossible to achieve") public void testCreatePartialMockForAProtectedMethodInASpecificSubclass() throws Exception { final String value = "another string"; final String getTheStringMethodName = "getTheString"; MethodInvocationDemo tested = createPartialMock(MethodInvocationDemo.class, MethodInvocationDemoGrandParent.class, getTheStringMethodName); expectPrivate(tested, getTheStringMethodName, MethodInvocationDemoGrandParent.class).andReturn(value); replay(tested); assertEquals("MethodInvocationDemoParent wrapped " + value, tested.getTheString()); verify(tested); } @Test public void testWhenClassUnderTestIsAnAnonymousInnerClass() throws Exception { MethodInvocationDemo tested = new MethodInvocationDemo() { }; assertEquals("MethodInvocationDemoParent wrapped a string from MethodInvocationDemoGrandParent", Whitebox.invokeMethod(tested, "getString")); } @Test public void testInvokePrivateMethodInSuperClassWhenClassUnderTestIsAnAnonymousInnerClass() throws Exception { MethodInvocationDemo tested = new MethodInvocationDemo() { }; assertEquals("MethodInvocationDemoParent", Whitebox.invokeMethod(tested, MethodInvocationDemoParent.class, "getString")); } @Test public void testInvokeProtectedMethodWhenClassUnderTestIsAnAnonymousInnerClass() throws Exception { MethodInvocationDemo tested = new MethodInvocationDemo() { }; assertEquals("MethodInvocationDemoParent wrapped a string from MethodInvocationDemoGrandParent", tested.getTheString()); } @Test public void testInvokeProtectedMethodWhenClassUnderTestIsAnAnonymousInnerClassUsingWithbox() throws Exception { MethodInvocationDemo tested = new MethodInvocationDemo() { }; assertEquals("MethodInvocationDemoParent wrapped a string from MethodInvocationDemoGrandParent", Whitebox.invokeMethod(tested, "getTheString")); } @Test public void testInvokeSpecificMethodInHierarchy() throws Exception { MethodInvocationDemo tested = new MethodInvocationDemo(); assertEquals("MethodInvocationDemoGrandParent", Whitebox.invokeMethod(tested, MethodInvocationDemoGrandParent.class, "getString", (Object[]) new Class[0])); } @Test public void testInvokeSpecificMethodInHierarchyWithArguments() throws Exception { MethodInvocationDemo tested = new MethodInvocationDemo(); assertEquals("MethodInvocationDemoGrandParent: 2", Whitebox.invokeMethod(tested, MethodInvocationDemoGrandParent.class, "getString", new Class[] { int.class }, 2)); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/packageprivate/PackagePrivateClassTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.packageprivate; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import static org.junit.Assert.assertEquals; import static org.powermock.api.easymock.PowerMock.*; /** * Verifies that the issue at * http://code.google.com/p/powermock/issues/detail?id=32 is solved. */ @RunWith(PowerMockRunner.class) @PrepareForTest(PackagePrivateClass.class) public class PackagePrivateClassTest { @Test public void testMockAPackagePrivateClass() throws Exception { final String returnAValueMethodName = "returnAValue"; final int expected = 23; PackagePrivateClass tested = createPartialMock(PackagePrivateClass.class, returnAValueMethodName); expectPrivate(tested, returnAValueMethodName).andReturn(expected); replay(tested); assertEquals(expected, tested.getValue()); verify(tested); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/suppressconstructor/SuppressDefaultConstructorTest.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.suppressconstructor; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import static junit.framework.Assert.assertEquals; import static org.powermock.api.support.membermodification.MemberMatcher.constructor; import static org.powermock.api.support.membermodification.MemberMatcher.defaultConstructorIn; import static org.powermock.api.support.membermodification.MemberModifier.suppress; @RunWith(PowerMockRunner.class) @PrepareForTest(AppaleList.class) public class SuppressDefaultConstructorTest { @Test public void powerMockCanSuppressDefaultConstructor() { suppress(defaultConstructorIn(AppaleList.class)); AppaleList appaleList = new AppaleList(); String str = appaleList.getAll(); assertEquals(str, "str"); } @Test(expected = IllegalArgumentException.class) public void powerMockSuppressesOnlyDefaultConstructorWhenUsingDefaultConstructorIn() { suppress(defaultConstructorIn(AppaleList.class)); new AppaleList("something"); } @Test public void powerMockCanSuppressDefaultConstructorUsingConstructorMethod() { suppress(constructor(AppaleList.class, new Class[0])); AppaleList appaleList = new AppaleList(); String str = appaleList.getAll(); assertEquals(str, "str"); } @Test(expected = IllegalArgumentException.class) public void powerMockSuppressesOnlyDefaultConstructorWhenApplicable() { suppress(constructor(AppaleList.class, new Class[0])); new AppaleList("something"); } } ================================================ FILE: tests/easymock/junit4/src/test/java/samples/suppressconstructor/SuppressSpecificConstructorDemoTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.suppressconstructor; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import static org.junit.Assert.fail; import static org.powermock.api.support.membermodification.MemberMatcher.constructor; import static org.powermock.api.support.membermodification.MemberModifier.suppress; @RunWith(PowerMockRunner.class) @PrepareForTest( { SuppressSpecificConstructorDemo.class, SuppressSpecificConstructorDemoTest.class }) public class SuppressSpecificConstructorDemoTest { @Test public void testMockStringConstructor() throws Exception { suppress(constructor(SuppressSpecificConstructorDemo.class, String.class)); // This should be fine new SuppressSpecificConstructorDemo("This expection should not occur"); // This should not be fine! try { new SuppressSpecificConstructorDemo(); fail("Should have thrown IllegalStateException!"); } catch (IllegalStateException e) { // assertEquals("", e.getMessage()); } } } ================================================ FILE: tests/easymock/junit4-agent/src/test/java/samples/powermockito/junit4/agent/AnnotationUsageTest.java ================================================ /* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.agent; import org.easymock.Mock; import org.easymock.TestSubject; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.powermock.modules.junit4.rule.PowerMockRule; import samples.Service; import samples.annotationbased.AnnotationDemo; import java.util.Arrays; import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertEquals; import static org.powermock.api.easymock.PowerMock.replay; @RunWith(Parameterized.class) public class AnnotationUsageTest { @Rule public PowerMockRule rule = new PowerMockRule(); @TestSubject private final AnnotationDemo tested = new AnnotationDemo(); @SuppressWarnings("unused") @Mock private Service server; private final String fooId; public AnnotationUsageTest(String fooId) { this.fooId = fooId; } @Parameterized.Parameters() public static Iterable data() { return Arrays.asList(new Object[][]{ {"1"}, {"2"} }); } @Before public void setUp() { expect(server.getServiceMessage()).andReturn(fooId); replay(server); } @Test public void annotationsAreEnabledWhenUsingTheJUnitRule() { String serviceMessage = tested.getServiceMessage(); assertEquals(fooId, serviceMessage); } } ================================================ FILE: tests/easymock/junit4-agent/src/test/java/samples/powermockito/junit4/agent/LargeMethodTest.java ================================================ package samples.powermockito.junit4.agent; import org.junit.Rule; import org.junit.Test; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.rule.PowerMockRule; import samples.largemethod.MethodExceedingJvmLimit; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertNull; import static junit.framework.Assert.assertSame; import static junit.framework.Assert.assertTrue; import static junit.framework.Assert.fail; import static org.easymock.EasyMock.expect; import static org.powermock.api.easymock.PowerMock.method; import static org.powermock.api.easymock.PowerMock.mockStatic; import static org.powermock.api.easymock.PowerMock.replayAll; import static org.powermock.api.easymock.PowerMock.suppress; @PrepareForTest(MethodExceedingJvmLimit.class) public class LargeMethodTest { @Rule public PowerMockRule powerMockRule = new PowerMockRule(); @Test public void largeMethodShouldBeOverridden() { try { MethodExceedingJvmLimit.init(); fail("Method should be overridden and exception should be thrown"); } catch (Exception e) { assertSame(IllegalAccessException.class, e.getClass()); assertTrue(e.getMessage().contains("Method was too large and after instrumentation exceeded JVM limit")); } } @Test public void largeMethodShouldBeAbleToBeSuppressed() { suppress(method(MethodExceedingJvmLimit.class, "init")); assertNull("Suppressed method should return: null", MethodExceedingJvmLimit.init()); } @Test public void largeMethodShouldBeAbleToBeMocked() { mockStatic(MethodExceedingJvmLimit.class); expect(MethodExceedingJvmLimit.init()).andReturn("ok"); replayAll(); assertEquals("Mocked method should return: ok", "ok", MethodExceedingJvmLimit.init()); } @Test(expected = IllegalStateException.class) public void largeMethodShouldBeAbleToBeMockedAndThrowException() { mockStatic(MethodExceedingJvmLimit.class); expect(MethodExceedingJvmLimit.init()).andThrow(new IllegalStateException()); replayAll(); MethodExceedingJvmLimit.init(); } } ================================================ FILE: tests/easymock/junit4-legacy/src/test/java/samples/junit4/legacy/annotationbased/AnnotationDemoWithSetupMethodTest.java ================================================ package samples.junit4.legacy.annotationbased; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.easymock.annotation.Mock; import org.powermock.modules.junit4.legacy.PowerMockRunner; import samples.Service; import samples.annotationbased.AnnotationDemo; import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertEquals; import static org.powermock.api.easymock.PowerMock.replayAll; import static org.powermock.api.easymock.PowerMock.verifyAll; /** * Verifies that PowerMock test listeners works correctly with setup methods. */ @RunWith(PowerMockRunner.class) public class AnnotationDemoWithSetupMethodTest { @Mock private Service serviceMock; private AnnotationDemo tested; @Before public void setup() { tested = new AnnotationDemo(serviceMock); } @Test public void assertInjectionWorked() throws Exception { final String expected = "mock"; expect(serviceMock.getServiceMessage()).andReturn(expected); replayAll(); assertEquals(expected, tested.getServiceMessage()); verifyAll(); } } ================================================ FILE: tests/easymock/junit4-legacy/src/test/java/samples/junit4/legacy/annotationbased/FinalDemoWithAnnotationInjectionTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.legacy.annotationbased; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.easymock.annotation.Mock; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.legacy.PowerMockRunner; import samples.finalmocking.FinalDemo; import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.powermock.api.easymock.PowerMock.replay; import static org.powermock.api.easymock.PowerMock.verify; /** * Test class to demonstrate non-static final mocking. * */ @RunWith(PowerMockRunner.class) @PrepareForTest(FinalDemo.class) public class FinalDemoWithAnnotationInjectionTest { @Mock private FinalDemo tested; @Test public void testSay() throws Exception { String expected = "Hello altered World"; expect(tested.say("hello")).andReturn("Hello altered World"); replay(tested); String actual = tested.say("hello"); verify(tested); assertEquals("Expected and actual did not match", expected, actual); // Should still be mocked by now. try { tested.say("world"); fail("Should throw AssertionError!"); } catch (AssertionError e) { assertEquals("\n Unexpected method call FinalDemo.say(\"world\"):", e.getMessage()); } } @Test public void testSayFinalNative() throws Exception { String expected = "Hello altered World"; expect(tested.sayFinalNative("hello")).andReturn("Hello altered World"); replay(tested); String actual = tested.sayFinalNative("hello"); verify(tested); assertEquals("Expected and actual did not match", expected, actual); // Should still be mocked by now. try { tested.sayFinalNative("world"); fail("Should throw AssertionError!"); } catch (AssertionError e) { assertEquals("\n Unexpected method call FinalDemo.sayFinalNative(\"world\"):", e.getMessage()); } } } ================================================ FILE: tests/easymock/junit4-legacy/src/test/java/samples/junit4/legacy/noannotation/NoAnnotationUsageTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.legacy.noannotation; import junit.framework.TestCase; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.legacy.PowerMockRunner; import samples.staticandinstance.StaticAndInstanceDemo; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.easymock.EasyMock.expect; import static org.powermock.api.easymock.PowerMock.*; /** * Test case that demonstrates the ability to run test cases not annotated with * {@link Test} when extending from {@link TestCase} using JUnit4 legacy * (4.0-4.3). */ @RunWith(PowerMockRunner.class) @PrepareForTest(StaticAndInstanceDemo.class) public class NoAnnotationUsageTest extends TestCase { public void testShouldMockPrivateAndStaticMethod() throws Exception { mockStaticPartial(StaticAndInstanceDemo.class, "getStaticMessage"); StaticAndInstanceDemo tested = createPartialMock(StaticAndInstanceDemo.class, "getPrivateMessage"); final String staticExpected = "a static message"; expect(StaticAndInstanceDemo.getStaticMessage()).andReturn(staticExpected); final String privateExpected = "A private message "; expectPrivate(tested, "getPrivateMessage").andReturn(privateExpected); replay(tested); replay(StaticAndInstanceDemo.class); assertThat(tested.getMessage()).isEqualTo(privateExpected + staticExpected); verify(tested); verify(StaticAndInstanceDemo.class); } } ================================================ FILE: tests/easymock/junit4-legacy/src/test/java/samples/junit4/legacy/noannotation/SetUpAndTearDownWhenExtendingTestCaseTest.java ================================================ package samples.junit4.legacy.noannotation; import junit.framework.TestCase; import org.junit.runner.RunWith; import org.powermock.modules.junit4.legacy.PowerMockRunner; @RunWith(PowerMockRunner.class) public class SetUpAndTearDownWhenExtendingTestCaseTest extends TestCase { private static final String INITIAL_MESSAGE = ""; private static final String SET_UP_MESSAGE = "setUp"; private static final String TEST_MESSAGE = "test"; private static String CURRENT_MESSAGE = INITIAL_MESSAGE; @Override protected void setUp() throws Exception { assertEquals(INITIAL_MESSAGE, CURRENT_MESSAGE); CURRENT_MESSAGE = SET_UP_MESSAGE; } @Override protected void tearDown() throws Exception { assertEquals(TEST_MESSAGE, CURRENT_MESSAGE); } public void testSomething() throws Exception { assertEquals(SET_UP_MESSAGE, CURRENT_MESSAGE); CURRENT_MESSAGE = TEST_MESSAGE; } } ================================================ FILE: tests/easymock/junit4-legacy/src/test/java/samples/junit4/legacy/noannotation/SetUpAndTearDownWhenNotExtendingTestCaseTest.java ================================================ package samples.junit4.legacy.noannotation; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.modules.junit4.legacy.PowerMockRunner; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; @RunWith(PowerMockRunner.class) public class SetUpAndTearDownWhenNotExtendingTestCaseTest { private static final String INITIAL_MESSAGE = ""; private static String CURRENT_MESSAGE = INITIAL_MESSAGE; public void setUp() throws Exception { fail("Should not call setUp"); } public void tearDown() throws Exception { fail("Should not call tearDown"); } @Test public void testSomething() throws Exception { assertEquals(INITIAL_MESSAGE, CURRENT_MESSAGE); } } ================================================ FILE: tests/easymock/junit4-legacy/src/test/java/samples/junit4/legacy/singleton/MockStaticTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.legacy.singleton; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.legacy.PowerMockRunner; import org.powermock.reflect.Whitebox; import samples.singleton.StaticHelper; import samples.singleton.StaticService; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.expectLastCall; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.powermock.api.easymock.PowerMock.*; /** * Test class to demonstrate static, static+final, static+native and * static+final+native methods mocking. * * @author Johan Haleby * @author Jan Kronquist */ @RunWith(PowerMockRunner.class) @PrepareForTest( { StaticService.class, StaticHelper.class }) public class MockStaticTest { @Test public void testSay() throws Exception { mockStatic(StaticService.class); String expected = "Hello altered World"; expect(StaticService.say("hello")).andReturn("Hello altered World"); replay(StaticService.class); String actual = StaticService.say("hello"); verify(StaticService.class); assertEquals("Expected and actual did not match", expected, actual); // Singleton still be mocked by now. try { StaticService.say("world"); fail("Should throw AssertionError!"); } catch (AssertionError e) { assertEquals("\n Unexpected method call StaticService.say(\"world\"):", e.getMessage()); } } @Test public void testSayFinal() throws Exception { mockStatic(StaticService.class); String expected = "Hello altered World"; expect(StaticService.sayFinal("hello")).andReturn("Hello altered World"); replay(StaticService.class); String actual = StaticService.sayFinal("hello"); verify(StaticService.class); assertEquals("Expected and actual did not match", expected, actual); // Singleton still be mocked by now. try { StaticService.sayFinal("world"); fail("Should throw AssertionError!"); } catch (AssertionError e) { assertEquals("\n Unexpected method call StaticService.sayFinal(\"world\"):", e.getMessage()); } } @Test public void testSayNative() throws Exception { mockStatic(StaticService.class); String expected = "Hello altered World"; expect(StaticService.sayNative("hello")).andReturn("Hello altered World"); replay(StaticService.class); String actual = StaticService.sayNative("hello"); verify(StaticService.class); assertEquals("Expected and actual did not match", expected, actual); } @Test public void sayFinalNative() throws Exception { mockStatic(StaticService.class); String expected = "Hello altered World"; expect(StaticService.sayFinalNative("hello")).andReturn("Hello altered World"); replay(StaticService.class); String actual = StaticService.sayFinalNative("hello"); verify(StaticService.class); assertEquals("Expected and actual did not match", expected, actual); } @Test public void mockAStaticMethod() throws Exception { mockStatic(StaticService.class); String expected = "qwe"; expect(StaticService.doStatic(5)).andReturn(expected); replay(StaticService.class); String actual = StaticService.doStatic(5); assertEquals(expected, actual); verify(StaticService.class); } @Test public void mockSayHello() throws Exception { mockStatic(StaticHelper.class); StaticHelper.sayHelloHelper(); expectLastCall().times(2); replay(StaticHelper.class); StaticService.sayHello(); verify(StaticHelper.class); } @Test public void mockSayHelloAgain() throws Exception { mockStatic(StaticHelper.class); StaticHelper.sayHelloAgain(); expectLastCall().times(2); replay(StaticHelper.class); StaticService.sayHelloAgain(); verify(StaticHelper.class); } @Test public void testSayPrivateStatic() throws Exception { mockStaticPartial(StaticService.class, "sayPrivateStatic", String.class); final String expected = "Hello world"; expectPrivate(StaticService.class, "sayPrivateStatic", "name").andReturn(expected); replay(StaticService.class); String actual = Whitebox.invokeMethod(StaticService.class, "sayPrivateStatic", "name"); verify(StaticService.class); assertEquals(expected, actual); } @Test public void testSayPrivateFinalStatic() throws Exception { mockStaticPartial(StaticService.class, "sayPrivateFinalStatic", String.class); final String expected = "Hello world"; expectPrivate(StaticService.class, "sayPrivateFinalStatic", "name").andReturn(expected); replay(StaticService.class); String actual = Whitebox.invokeMethod(StaticService.class, "sayPrivateFinalStatic", "name"); verify(StaticService.class); assertEquals(expected, actual); } @Test public void innerClassesWork() { assertThat(StaticService.getNumberFromInner()).isEqualTo(17); } @Test public void innerInstanceClassesWork() { assertThat(StaticService.getNumberFromInnerInstance()).isEqualTo(23); } } ================================================ FILE: tests/easymock/junit4-legacy/src/test/java/samples/junit4/legacy/suppressconstructor/SuppressConstructorHierarchyDemoTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.legacy.suppressconstructor; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.legacy.PowerMockRunner; import samples.suppressconstructor.SuppressConstructorHeirarchyEvilGrandParent; import samples.suppressconstructor.SuppressConstructorHierarchy; import samples.suppressconstructor.SuppressConstructorHierarchyParent; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.junit.Assert.*; import static org.powermock.api.support.membermodification.MemberMatcher.constructor; import static org.powermock.api.support.membermodification.MemberModifier.suppress; @PrepareForTest( { SuppressConstructorHierarchy.class, SuppressConstructorHierarchyParent.class, SuppressConstructorHeirarchyEvilGrandParent.class }) @RunWith(PowerMockRunner.class) public class SuppressConstructorHierarchyDemoTest { @Test public void testSuppressConstructor() throws Exception { suppress(constructor(SuppressConstructorHierarchy.class)); SuppressConstructorHierarchy tested = new SuppressConstructorHierarchy("message"); final String message = tested.getMessage(); assertNull("Message should have been null since we're skipping the execution of the constructor code. Message was \"" + message + "\".", message); } @Test @PrepareForTest public void testNotSuppressConstructor() throws Exception { try { new SuppressConstructorHierarchy("message"); fail("Should throw RuntimeException since we're running this test with a new class loader!"); } catch (RuntimeException e) { assertEquals("This should be suppressed!!", e.getMessage()); } } /** * This simple test demonstrate that it's possible to continue execution * with the default {@code PrepareForTest} settings (i.e. using a * byte-code manipulated version of the SuppressConstructorHierarchyDemo * class). */ @Test public void testGetNumber() throws Exception { suppress(constructor(SuppressConstructorHierarchy.class)); SuppressConstructorHierarchy tested = new SuppressConstructorHierarchy("message"); assertThat(tested.getNumber()).isEqualTo(42); } } ================================================ FILE: tests/easymock/junit410/src/test/java/samples/junit410/assume/AssumeForJUnit410Test.java ================================================ package samples.junit410.assume; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.modules.junit4.PowerMockRunner; import static org.junit.Assume.assumeTrue; @RunWith(PowerMockRunner.class) public class AssumeForJUnit410Test { @Test public void assumesWorkWithPowerMockForJUnit410() throws Exception { // When assumeTrue(false); } } ================================================ FILE: tests/easymock/junit410/src/test/java/samples/junit410/expectnew/ExpectNewDemoTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit410.expectnew; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.expectnew.ExpectNewDemo; import samples.junit4.expectnew.ExpectNewCases; import samples.newmocking.MyClass; import java.io.DataInputStream; /** * Test class to demonstrate new instance mocking using expectNew(..). * */ @RunWith(PowerMockRunner.class) @PrepareForTest( { MyClass.class, ExpectNewDemo.class, DataInputStream.class }) public class ExpectNewDemoTest extends ExpectNewCases{ } ================================================ FILE: tests/easymock/junit410/src/test/java/samples/junit410/expectnew/ExpectNewOfFinalSystemClassTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit410.expectnew; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.expectnew.ExpectNewOfFinalSystemClassDemo; import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertEquals; import static org.powermock.api.easymock.PowerMock.*; @RunWith(PowerMockRunner.class) @PrepareForTest( { ExpectNewOfFinalSystemClassDemo.class }) public class ExpectNewOfFinalSystemClassTest { @Test public void assertThatExpectNewWorksForFinalSystemClasses() throws Exception { String mock = createMock(String.class); expectNew(String.class, "My String").andReturn(mock); expect(mock.charAt(0)).andReturn('o'); replayAll(); assertEquals('o', new ExpectNewOfFinalSystemClassDemo().getFirstChar()); verifyAll(); } } ================================================ FILE: tests/easymock/junit410/src/test/java/samples/junit410/github668/Github668.java ================================================ package samples.junit410.github668; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.easymock.annotation.Mock; import org.powermock.api.extension.listener.AnnotationEnabler; import org.powermock.core.classloader.annotations.PowerMockListener; import org.powermock.modules.junit4.PowerMockRunner; import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.powermock.api.easymock.PowerMock.replayAll; /** * */ @RunWith(PowerMockRunner.class) @PowerMockListener(AnnotationEnabler.class) public class Github668 { @Mock private IncidentPropertyChangeDAO incidentPropertyChangeDAO; @Test public void mockClassShouldInjected() { assertNotNull(incidentPropertyChangeDAO); } @Test public void shouldBeAbleMockMethodsOfInjected() { expect(incidentPropertyChangeDAO.getIncident()).andReturn("value"); replayAll(incidentPropertyChangeDAO); assertEquals("value",incidentPropertyChangeDAO.getIncident()); } } ================================================ FILE: tests/easymock/junit410/src/test/java/samples/junit410/github668/IncidentPropertyChangeDAO.java ================================================ package samples.junit410.github668; /** * */ public interface IncidentPropertyChangeDAO { String getIncident(); } ================================================ FILE: tests/easymock/junit410/src/test/java/samples/junit410/github668/package-info.java ================================================ /** * \@Mock fields are not injected anymore (1.6.5 regression) * https://github.com/jayway/powermock/issues/668 */ package samples.junit410.github668; ================================================ FILE: tests/easymock/junit410/src/test/java/samples/junit410/rules/AssertThatJUnit410RulesWorks.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit410.rules; import org.junit.Rule; import org.junit.Test; import org.junit.rules.MethodRule; import org.junit.rules.TestName; import org.junit.runner.RunWith; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.Statement; import org.powermock.modules.junit4.PowerMockRunner; import java.util.LinkedList; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; /** * This test demonstrates that JUnit 4.10 rules works together with PowerMock */ @RunWith(PowerMockRunner.class) public class AssertThatJUnit410RulesWorks { private static Object BEFORE = new Object(); private List objects = new LinkedList(); @Rule public MyRule rule = new MyRule(); @Rule public TestName testName = new TestName(); @Test public void assertThatJUnit410RulesWorks() throws Exception { assertEquals(1, objects.size()); assertSame(BEFORE, objects.get(0)); assertEquals("assertThatJUnit410RulesWorks", testName.getMethodName()); } private class MyRule implements MethodRule { public Statement apply(final Statement base, FrameworkMethod method, Object target) { return new Statement() { @Override public void evaluate() throws Throwable { objects.add(BEFORE); base.evaluate(); } }; } } } ================================================ FILE: tests/easymock/junit410/src/test/java/samples/junit410/rules/ExceptionHandlingRuleTest.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit410.rules; import org.junit.Before; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.junit410.rules.impl.SimpleEasyMockJUnitRule; import samples.rule.SimpleThingCreator; import samples.rule.SimpleThingImpl; import samples.rule.ThingToTest; import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertEquals; import static org.powermock.api.easymock.PowerMock.*; @RunWith(PowerMockRunner.class) @PrepareForTest(SimpleThingCreator.class) public class ExceptionHandlingRuleTest { @Rule public SimpleEasyMockJUnitRule mocks = new SimpleEasyMockJUnitRule(); private SimpleThingImpl simpleThingMock = mocks.createMock(SimpleThingImpl.class); // object under test private ThingToTest testThing; @Before public void setUp() throws Exception { mockStatic(SimpleThingCreator.class); expect(SimpleThingCreator.createSimpleThing()).andReturn(simpleThingMock); replay(SimpleThingCreator.class); verify(SimpleThingCreator.class); } @Test @Ignore("This test SHOULD fail but how do we expect it when verification happens in the rule?") public void exceptionThrownByRuleFailsTheTest() throws Exception { final String expectedName = "Smith"; expect(simpleThingMock.getThingName()).andReturn(expectedName); mocks.replay(); assertEquals("wrong name", expectedName, testThing.getName()); // verify will be called by rule } } ================================================ FILE: tests/easymock/junit410/src/test/java/samples/junit410/rules/NoRuleAssertionErrorTest.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit410.rules; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.modules.junit4.PowerMockRunner; import static org.junit.Assert.assertTrue; @RunWith(PowerMockRunner.class) public class NoRuleAssertionErrorTest { @Test(expected = AssertionError.class) public void assertionErrorIsThrownOnFailureWhenNoRulesDefined() throws Exception { assertTrue(false); } } ================================================ FILE: tests/easymock/junit410/src/test/java/samples/junit410/rules/impl/SimpleEasyMockJUnitRule.java ================================================ package samples.junit410.rules.impl; import org.easymock.IMocksControl; import org.junit.rules.MethodRule; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.Statement; import static org.easymock.EasyMock.createControl; /** * A JUnit rule that resets all mocks before each test and verifies the mocks after the test */ public class SimpleEasyMockJUnitRule implements MethodRule { final IMocksControl control; boolean recording = true; public Error caughtError = null; /** * Create the rule using the default EasyMock.createControl() */ public SimpleEasyMockJUnitRule() { this(createControl()); } /** * Create the rule using the IMocksControl that you provide * * @param control * The provided IMocksControl to use for testing */ public SimpleEasyMockJUnitRule(IMocksControl control) { this.control = control; } public T createMock(Class toMock) { return control.createMock(toMock); } public void reset() { recording = true; control.reset(); } public void replay() { recording = false; control.replay(); } public void verify() { control.verify(); } @Override public Statement apply(final Statement base, final FrameworkMethod method, final Object target) { return new Statement() { @Override public void evaluate() throws Throwable { reset(); base.evaluate(); if (!recording) { verify(); // only verify if no exceptions were thrown } } }; } } ================================================ FILE: tests/easymock/junit412/src/test/java/samples/junit412/bug/github755/TwoObjectsAnnotatedTest.java ================================================ package samples.junit412.bug.github755; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.easymock.annotation.Mock; import org.powermock.api.easymock.annotation.MockNice; import org.powermock.modules.junit4.PowerMockRunner; import samples.newmocking.SomeDependency; import static org.assertj.core.api.Java6Assertions.assertThat; @RunWith(PowerMockRunner.class) public class TwoObjectsAnnotatedTest { @Mock private String obj1; @Mock private String obj2; @MockNice private SomeDependency someClass1; @MockNice private SomeDependency someClass2; @Test public void should_create_mock_for_all_fields_annotated_Mock() { assertThat(obj1).isNotNull(); assertThat(obj2).isNotNull(); } @Test public void should_create_mock_for_all_fields_annotated_MockNice() { assertThat(someClass1).isNotNull(); assertThat(someClass2).isNotNull(); } } ================================================ FILE: tests/easymock/junit412/src/test/java/samples/junit412/bug/github755/package-info.java ================================================ /** * @Mock annotation from easymock api does not work for two fields of the same type. * */ package samples.junit412.bug.github755; ================================================ FILE: tests/easymock/junit412/src/test/java/samples/junit412/expectnew/ExpectNewDemoTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit412.expectnew; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.expectnew.ExpectNewDemo; import samples.junit4.expectnew.ExpectNewCases; import samples.newmocking.MyClass; import java.io.DataInputStream; /** * Test class to demonstrate new instance mocking using expectNew(..). * */ @RunWith(PowerMockRunner.class) @PrepareForTest( { MyClass.class, ExpectNewDemo.class, DataInputStream.class }) public class ExpectNewDemoTest extends ExpectNewCases { } ================================================ FILE: tests/easymock/junit412/src/test/java/samples/junit412/expectnew/ExpectNewOfFinalSystemClassTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit412.expectnew; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.expectnew.ExpectNewOfFinalSystemClassDemo; import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertEquals; import static org.powermock.api.easymock.PowerMock.createMock; import static org.powermock.api.easymock.PowerMock.expectNew; import static org.powermock.api.easymock.PowerMock.replayAll; import static org.powermock.api.easymock.PowerMock.verifyAll; @RunWith(PowerMockRunner.class) @PrepareForTest( { ExpectNewOfFinalSystemClassDemo.class }) public class ExpectNewOfFinalSystemClassTest { @Test public void assertThatExpectNewWorksForFinalSystemClasses() throws Exception { String mock = createMock(String.class); expectNew(String.class, "My String").andReturn(mock); expect(mock.charAt(0)).andReturn('o'); replayAll(); assertEquals('o', new ExpectNewOfFinalSystemClassDemo().getFirstChar()); verifyAll(); } } ================================================ FILE: tests/easymock/junit412/src/test/java/samples/junit412/github668/Github668Test.java ================================================ package samples.junit412.github668; import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({TwoMockFieldsWithDifferentTypesClass.class, TwoMockFieldsWithSameTypeCase.class}) public class Github668Test { } ================================================ FILE: tests/easymock/junit412/src/test/java/samples/junit412/github668/IncidentPropertyChangeDAO.java ================================================ package samples.junit412.github668; /** * */ public interface IncidentPropertyChangeDAO { String getIncident(); } ================================================ FILE: tests/easymock/junit412/src/test/java/samples/junit412/github668/TwoMockFieldsWithDifferentTypesClass.java ================================================ package samples.junit412.github668; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.easymock.annotation.Mock; import org.powermock.api.extension.listener.AnnotationEnabler; import org.powermock.core.classloader.annotations.PowerMockListener; import org.powermock.modules.junit4.PowerMockRunner; import samples.Service; import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.powermock.api.easymock.PowerMock.replayAll; /** * */ @RunWith(PowerMockRunner.class) @PowerMockListener(AnnotationEnabler.class) public class TwoMockFieldsWithDifferentTypesClass { @Mock private IncidentPropertyChangeDAO incidentPropertyChangeDAO; @Mock private Service serviceMock; @Test public void mockClassShouldInjected() { assertNotNull(incidentPropertyChangeDAO); assertNotNull(serviceMock); } @Test public void shouldBeAbleMockMethodsOfInjected() { expect(incidentPropertyChangeDAO.getIncident()).andReturn("value"); expect(serviceMock.getServiceMessage()).andReturn("value"); replayAll(incidentPropertyChangeDAO, serviceMock); assertEquals("value", incidentPropertyChangeDAO.getIncident()); assertEquals("value", serviceMock.getServiceMessage()); } } ================================================ FILE: tests/easymock/junit412/src/test/java/samples/junit412/github668/TwoMockFieldsWithSameTypeCase.java ================================================ package samples.junit412.github668; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.easymock.annotation.Mock; import org.powermock.api.extension.listener.AnnotationEnabler; import org.powermock.core.classloader.annotations.PowerMockListener; import org.powermock.modules.junit4.PowerMockRunner; import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.powermock.api.easymock.PowerMock.replayAll; /** * */ @RunWith(PowerMockRunner.class) @PowerMockListener(AnnotationEnabler.class) public class TwoMockFieldsWithSameTypeCase { @Mock(fieldName = "incidentPropertyChangeDAO") private IncidentPropertyChangeDAO incidentPropertyChangeDAO; @Mock(fieldName = "propertyChangeDAO") private IncidentPropertyChangeDAO propertyChangeDAO; @Test public void mockClassShouldInjected() { assertNotNull(incidentPropertyChangeDAO); assertNotNull(propertyChangeDAO); } @Test public void shouldBeAbleMockMethodsOfInjected() { expect(incidentPropertyChangeDAO.getIncident()).andReturn("value"); expect(propertyChangeDAO.getIncident()).andReturn("value1"); replayAll(incidentPropertyChangeDAO,propertyChangeDAO); assertEquals("value", incidentPropertyChangeDAO.getIncident()); assertEquals("value1", propertyChangeDAO.getIncident()); } } ================================================ FILE: tests/easymock/junit412/src/test/java/samples/junit412/github668/package-info.java ================================================ /** * \@Mock fields are not injected anymore (1.6.5 regression) * https://github.com/jayway/powermock/issues/668 */ package samples.junit412.github668; ================================================ FILE: tests/easymock/junit45/src/main/java/demo/org/powermock/modules/test/junit45/failure/MyClass.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package demo.org.powermock.modules.test.junit45.failure; public class MyClass { public int sum(int a, int b) throws MyException { if (MyUtils.isValid(a)) throw new MyException(); else return a + b; } } ================================================ FILE: tests/easymock/junit45/src/main/java/demo/org/powermock/modules/test/junit45/failure/MyException.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package demo.org.powermock.modules.test.junit45.failure; public class MyException extends Exception { private static final long serialVersionUID = -222072316863858540L; } ================================================ FILE: tests/easymock/junit45/src/main/java/demo/org/powermock/modules/test/junit45/failure/MyUtils.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package demo.org.powermock.modules.test.junit45.failure; public class MyUtils { public static boolean isValid(int a) { return a > 10; } } ================================================ FILE: tests/easymock/junit45/src/test/java/demo/org/powermock/modules/test/junit45/failure/AssertThatJUnit45FailuresWorkTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package demo.org.powermock.modules.test.junit45.failure; import org.easymock.EasyMock; import org.junit.Test; import org.junit.internal.AssumptionViolatedException; import org.junit.runner.RunWith; import org.powermock.api.easymock.PowerMock; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl; import static org.junit.Assert.assertTrue; /** * This test asserts that JUnit 4.5 failures works as expected. Previously the * {@link PowerMockJUnit44RunnerDelegateImpl} got a {@link NoClassDefFoundError} * when trying to load JUnit 4.4's {@link AssumptionViolatedException} which has * been moved in JUnit 4.5. Thanks to Manuel Fern�ndez S�nchez de la Blanca for * creating this test case to prove the issue. * */ @RunWith(PowerMockRunner.class) @PrepareForTest(MyUtils.class) public class AssertThatJUnit45FailuresWorkTest { @Test(expected = AssumptionViolatedException.class) public void testAssumptionViolatedException() throws MyException { throw new AssumptionViolatedException("Not true!"); } @Test(expected = MyException.class) public void testSum() throws MyException { PowerMock.mockStatic(MyUtils.class); EasyMock.expect(MyUtils.isValid(1)).andReturn(true); PowerMock.replay(MyUtils.class); MyClass myclass = new MyClass(); int result = myclass.sum(1, 2); PowerMock.verify(MyUtils.class); assertTrue(result == 3); } @Test(expected = MyException.class) public void testSum2() throws MyException { MyClass myclass = new MyClass(); myclass.sum(100, 2); } } ================================================ FILE: tests/easymock/junit47/src/test/java/samples/junit4/annotationbased/FinalDemoWithAnnotationInjectionAndFieldDefaulterTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.annotationbased; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.easymock.annotation.Mock; import org.powermock.core.classloader.annotations.PowerMockListener; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.core.testlisteners.FieldDefaulter; import org.powermock.modules.junit4.PowerMockRunner; import samples.finalmocking.FinalDemo; import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.powermock.api.easymock.PowerMock.replay; import static org.powermock.api.easymock.PowerMock.verify; /** * Test class to demonstrate non-static final mocking with multiple test * listeners for JUnit 4.7. * */ @RunWith(PowerMockRunner.class) @PrepareForTest(FinalDemo.class) @PowerMockListener( { FieldDefaulter.class }) public class FinalDemoWithAnnotationInjectionAndFieldDefaulterTest { @SuppressWarnings("unused") // Asserts that the FieldDefaulter handles primitive types. private int intType = 6; @Mock private FinalDemo tested; @Test public void testSay() throws Exception { String expected = "Hello altered World"; expect(tested.say("hello")).andReturn("Hello altered World"); replay(tested); String actual = tested.say("hello"); verify(tested); assertEquals("Expected and actual did not match", expected, actual); // Should still be mocked by now. try { tested.say("world"); fail("Should throw AssertionError!"); } catch (AssertionError e) { assertEquals("\n Unexpected method call FinalDemo.say(\"world\"):", e.getMessage()); } } @Test public void testSayFinalNative() throws Exception { String expected = "Hello altered World"; expect(tested.sayFinalNative("hello")).andReturn("Hello altered World"); replay(tested); String actual = tested.sayFinalNative("hello"); verify(tested); assertEquals("Expected and actual did not match", expected, actual); // Should still be mocked by now. try { tested.sayFinalNative("world"); fail("Should throw AssertionError!"); } catch (AssertionError e) { assertEquals("\n Unexpected method call FinalDemo.sayFinalNative(\"world\"):", e.getMessage()); } } } ================================================ FILE: tests/easymock/junit47/src/test/java/samples/junit4/expectnew/ExpectNewDemoTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.expectnew; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.expectnew.ExpectNewDemo; import samples.newmocking.MyClass; import java.io.DataInputStream; /** * Test class to demonstrate new instance mocking using expectNew(..). * */ @RunWith(PowerMockRunner.class) @PrepareForTest( { MyClass.class, ExpectNewDemo.class, DataInputStream.class }) public class ExpectNewDemoTest extends ExpectNewCases { } ================================================ FILE: tests/easymock/junit47/src/test/java/samples/junit4/expectnew/ExpectNewOfFinalSystemClassTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.expectnew; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.expectnew.ExpectNewOfFinalSystemClassDemo; import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertEquals; import static org.powermock.api.easymock.PowerMock.*; @RunWith(PowerMockRunner.class) @PrepareForTest( { ExpectNewOfFinalSystemClassDemo.class }) public class ExpectNewOfFinalSystemClassTest { @Test public void assertThatExpectNewWorksForFinalSystemClasses() throws Exception { String mock = createMock(String.class); expectNew(String.class, "My String").andReturn(mock); expect(mock.charAt(0)).andReturn('o'); replayAll(); assertEquals('o', new ExpectNewOfFinalSystemClassDemo().getFirstChar()); verifyAll(); } } ================================================ FILE: tests/easymock/junit47/src/test/java/samples/junit4/rules/AssertThatJUnit47RulesWorks.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.rules; import org.junit.Rule; import org.junit.Test; import org.junit.rules.MethodRule; import org.junit.rules.TestName; import org.junit.runner.RunWith; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.Statement; import org.powermock.modules.junit4.PowerMockRunner; import java.util.LinkedList; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; /** * This test demonstrates that JUnit 4.7 rules works together with PowerMock */ @RunWith(PowerMockRunner.class) public class AssertThatJUnit47RulesWorks { private static Object BEFORE = new Object(); private List objects = new LinkedList(); @Rule public MyRule rule = new MyRule(); @Rule public TestName testName = new TestName(); @Test public void assertThatJUnit47RulesWorks() throws Exception { assertEquals(1, objects.size()); assertSame(BEFORE, objects.get(0)); assertEquals("assertThatJUnit47RulesWorks", testName.getMethodName()); } private class MyRule implements MethodRule { @Override public Statement apply(final Statement base, FrameworkMethod method, Object target) { return new Statement() { @Override public void evaluate() throws Throwable { objects.add(BEFORE); base.evaluate(); } }; } } } ================================================ FILE: tests/easymock/junit47/src/test/java/samples/junit4/rules/NoRuleAssertionErrorTest.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.rules; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.modules.junit4.PowerMockRunner; import static org.junit.Assert.assertTrue; @RunWith(PowerMockRunner.class) public class NoRuleAssertionErrorTest { @Test(expected = AssertionError.class) public void assertionErrorIsThrownOnFailureWhenNoRulesDefined() throws Exception { assertTrue(false); } } ================================================ FILE: tests/easymock/junit47/src/test/java/samples/junit4/rules/RuleOrderTest.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.rules; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.powermock.modules.junit4.PowerMockRunner; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.assertThat; @RunWith(PowerMockRunner.class) public class RuleOrderTest { private static final String EMPTY_STRING = ""; @Rule public TemporaryFolder folder = new TemporaryFolder(); private String temporaryFileName = EMPTY_STRING; @Before public void setup() throws Exception { temporaryFileName = folder.newFile("tempFile").getPath(); } @Test public void rulesAreExecutedBeforeSetupMethods() throws Exception { assertThat(temporaryFileName, not(nullValue())); assertThat(temporaryFileName, not(equalTo(EMPTY_STRING))); } } ================================================ FILE: tests/easymock/junit47/src/test/java/samples/junit4/rules/ThrowingRuleTest.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit4.rules; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.powermock.modules.junit4.PowerMockRunner; /** * Asserts that expected expectation rules also works with the PowerMock JUnit * 4.7 runner. Asserts that issue 179 * has been resolved. Thanks to Andrei Ivanov for finding this bug. */ @RunWith(PowerMockRunner.class) public class ThrowingRuleTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void throwsNullPointerException() { thrown.expect(RuntimeException.class); throw new RuntimeException(); } @Test public void throwsNullPointerExceptionWithMessage() { thrown.expect(NullPointerException.class); thrown.expectMessage("What happened?"); throw new NullPointerException("What happened?"); } @Test(expected = NullPointerException.class) public void unexpectAssertionErrorFailsTestCorrectly() { throw new NullPointerException("What happened?"); } } ================================================ FILE: tests/easymock/junit48/src/test/java/samples/junit48/expectnew/ExpectNewDemoTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit48.expectnew; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.expectnew.ExpectNewDemo; import samples.junit4.expectnew.ExpectNewCases; import samples.newmocking.MyClass; import java.io.DataInputStream; /** * Test class to demonstrate new instance mocking using expectNew(..). * */ @RunWith(PowerMockRunner.class) @PrepareForTest( { MyClass.class, ExpectNewDemo.class, DataInputStream.class }) public class ExpectNewDemoTest extends ExpectNewCases{ } ================================================ FILE: tests/easymock/junit48/src/test/java/samples/junit48/expectnew/ExpectNewOfFinalSystemClassTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit48.expectnew; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.expectnew.ExpectNewOfFinalSystemClassDemo; import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertEquals; import static org.powermock.api.easymock.PowerMock.*; @RunWith(PowerMockRunner.class) @PrepareForTest( { ExpectNewOfFinalSystemClassDemo.class }) public class ExpectNewOfFinalSystemClassTest { @Test public void assertThatExpectNewWorksForFinalSystemClasses() throws Exception { String mock = createMock(String.class); expectNew(String.class, "My String").andReturn(mock); expect(mock.charAt(0)).andReturn('o'); replayAll(); assertEquals('o', new ExpectNewOfFinalSystemClassDemo().getFirstChar()); verifyAll(); } } ================================================ FILE: tests/easymock/junit48/src/test/java/samples/junit48/rules/AssertThatJUnit48RulesWorks.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit48.rules; import org.junit.Rule; import org.junit.Test; import org.junit.rules.MethodRule; import org.junit.rules.TestName; import org.junit.runner.RunWith; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.Statement; import org.powermock.modules.junit4.PowerMockRunner; import java.util.LinkedList; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; /** * This test demonstrates that JUnit 4.7 rules works together with PowerMock */ @RunWith(PowerMockRunner.class) public class AssertThatJUnit48RulesWorks { private static Object BEFORE = new Object(); private List objects = new LinkedList(); @Rule public MyRule rule = new MyRule(); @Rule public TestName testName = new TestName(); @Test public void assertThatJUnit47RulesWorks() throws Exception { assertEquals(1, objects.size()); assertSame(BEFORE, objects.get(0)); assertEquals("assertThatJUnit47RulesWorks", testName.getMethodName()); } private class MyRule implements MethodRule { @Override public Statement apply(final Statement base, FrameworkMethod method, Object target) { return new Statement() { @Override public void evaluate() throws Throwable { objects.add(BEFORE); base.evaluate(); } }; } } } ================================================ FILE: tests/easymock/junit48/src/test/java/samples/junit48/rules/ExceptionHandlingRuleTest.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit48.rules; import org.junit.Before; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.junit48.rules.impl.SimpleEasyMockJUnitRule; import samples.rule.SimpleThingCreator; import samples.rule.SimpleThingImpl; import samples.rule.ThingToTest; import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertEquals; import static org.powermock.api.easymock.PowerMock.*; @RunWith(PowerMockRunner.class) @PrepareForTest(SimpleThingCreator.class) public class ExceptionHandlingRuleTest { @Rule public SimpleEasyMockJUnitRule mocks = new SimpleEasyMockJUnitRule(); private SimpleThingImpl simpleThingMock = mocks.createMock(SimpleThingImpl.class); // object under test private ThingToTest testThing; @Before public void setUp() throws Exception { mockStatic(SimpleThingCreator.class); expect(SimpleThingCreator.createSimpleThing()).andReturn(simpleThingMock); replay(SimpleThingCreator.class); verify(SimpleThingCreator.class); } @Test @Ignore("This test SHOULD fail but how do we expect it when verification happens in the rule?") public void exceptionThrownByRuleFailsTheTest() throws Exception { final String expectedName = "Smith"; expect(simpleThingMock.getThingName()).andReturn(expectedName); mocks.replay(); assertEquals("wrong name", expectedName, testThing.getName()); // verify will be called by rule } } ================================================ FILE: tests/easymock/junit48/src/test/java/samples/junit48/rules/NoRuleAssertionErrorTest.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit48.rules; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.modules.junit4.PowerMockRunner; import static org.junit.Assert.assertTrue; @RunWith(PowerMockRunner.class) public class NoRuleAssertionErrorTest { @Test(expected = AssertionError.class) public void assertionErrorIsThrownOnFailureWhenNoRulesDefined() throws Exception { assertTrue(false); } } ================================================ FILE: tests/easymock/junit48/src/test/java/samples/junit48/rules/RuleOrderTest.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit48.rules; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.powermock.modules.junit4.PowerMockRunner; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.assertThat; @RunWith(PowerMockRunner.class) public class RuleOrderTest { private static final String EMPTY_STRING = ""; @Rule public TemporaryFolder folder = new TemporaryFolder(); private String temporaryFileName = EMPTY_STRING; @Before public void setup() throws Exception { temporaryFileName = folder.newFile("tempFile").getPath(); } @Test public void rulesAreExecutedBeforeSetupMethods() throws Exception { assertThat(temporaryFileName, not(nullValue())); assertThat(temporaryFileName, not(equalTo(EMPTY_STRING))); } } ================================================ FILE: tests/easymock/junit48/src/test/java/samples/junit48/rules/ThrowingRuleTest.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.junit48.rules; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.powermock.modules.junit4.PowerMockRunner; /** * Asserts that expected expectation rules also works with the PowerMock JUnit * 4.7 runner. Asserts that issue 179 * has been resolved. Thanks to Andrei Ivanov for finding this bug. */ @RunWith(PowerMockRunner.class) public class ThrowingRuleTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void throwsNullPointerException() { thrown.expect(RuntimeException.class); throw new RuntimeException(); } @Test public void throwsNullPointerExceptionWithMessage() { thrown.expect(NullPointerException.class); thrown.expectMessage("What happened?"); throw new NullPointerException("What happened?"); } @Test(expected = NullPointerException.class) public void unexpectAssertionErrorFailsTestCorrectly() { throw new NullPointerException("What happened?"); } } ================================================ FILE: tests/easymock/junit48/src/test/java/samples/junit48/rules/impl/SimpleEasyMockJUnitRule.java ================================================ package samples.junit48.rules.impl; import org.easymock.IMocksControl; import org.junit.rules.MethodRule; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.Statement; import static org.easymock.EasyMock.createControl; /** * A JUnit rule that resets all mocks before each test and verifies the mocks after the test */ public class SimpleEasyMockJUnitRule implements MethodRule { final IMocksControl control; boolean recording = true; public Error caughtError = null; /** * Create the rule using the default EasyMock.createControl() */ public SimpleEasyMockJUnitRule() { this(createControl()); } /** * Create the rule using the IMocksControl that you provide * * @param control * The provided IMocksControl to use for testing */ public SimpleEasyMockJUnitRule(IMocksControl control) { this.control = control; } public T createMock(Class toMock) { return control.createMock(toMock); } public void reset() { recording = true; control.reset(); } public void replay() { recording = false; control.replay(); } public void verify() { control.verify(); } @Override public Statement apply(final Statement base, final FrameworkMethod method, final Object target) { return new Statement() { @Override public void evaluate() throws Throwable { reset(); base.evaluate(); if (!recording) { verify(); // only verify if no exceptions were thrown } } }; } } ================================================ FILE: tests/easymock/testng/src/test/java/samples/testng/AnnotationDemoTest.java ================================================ package samples.testng; import org.powermock.api.easymock.annotation.Mock; import org.powermock.core.classloader.annotations.PrepareForTest; import org.testng.Assert; import org.testng.annotations.Test; import samples.Service; import samples.annotationbased.AnnotationDemo; import static org.easymock.EasyMock.expect; import static org.powermock.api.easymock.PowerMock.replayAll; import static org.powermock.api.easymock.PowerMock.verifyAll; /** * Verifies that PowerMock test listeners works correctly in TestNG. */ @PrepareForTest public class AnnotationDemoTest { @Mock private Service serviceMock; @Test public void assertInjectionWorked() throws Exception { AnnotationDemo tested = new AnnotationDemo(serviceMock); final String expected = "mock"; expect(serviceMock.getServiceMessage()).andReturn(expected); replayAll(); Assert.assertEquals(expected, tested.getServiceMessage()); verifyAll(); } } ================================================ FILE: tests/easymock/testng/src/test/java/samples/testng/AnnotationDemoWithBeforeMethodTest.java ================================================ package samples.testng; import org.powermock.api.easymock.annotation.Mock; import org.powermock.core.classloader.annotations.PrepareForTest; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import samples.Service; import samples.annotationbased.AnnotationDemo; import static org.easymock.EasyMock.expect; import static org.powermock.api.easymock.PowerMock.replayAll; import static org.powermock.api.easymock.PowerMock.verifyAll; /** * Verifies that PowerMock test listeners works correctly with before methods in * TestNG. */ public class AnnotationDemoWithBeforeMethodTest { @Mock private Service serviceMock; private AnnotationDemo tested; @BeforeMethod public void setup() { tested = new AnnotationDemo(serviceMock); } @Test @PrepareForTest public void assertInjectionWorked() throws Exception { final String expected = "mock"; expect(serviceMock.getServiceMessage()).andReturn(expected); replayAll(); Assert.assertEquals(expected, tested.getServiceMessage()); verifyAll(); } } ================================================ FILE: tests/easymock/testng/src/test/java/samples/testng/DocumentBuilderFactoryTest.java ================================================ package samples.testng; import org.testng.annotations.Test; import javax.xml.parsers.DocumentBuilderFactory; public class DocumentBuilderFactoryTest { @Test public void classesNotAnnotatedWithPrepareForTestAreNotLoadedByByPowerMockCl() throws Exception { DocumentBuilderFactory.newInstance(); } } ================================================ FILE: tests/easymock/testng/src/test/java/samples/testng/FinalTest.java ================================================ package samples.testng; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.testng.PowerMockTestCase; import org.testng.annotations.Test; import samples.finalmocking.FinalDemo; import static org.easymock.EasyMock.expect; import static org.powermock.api.easymock.PowerMock.*; import static org.testng.Assert.assertEquals; @PrepareForTest(FinalDemo.class) public class FinalTest extends PowerMockTestCase { @Test public void mockingFinalClassesAndMethodsWorkWithTestNGAndEasyMock() throws Exception { final FinalDemo finalDemo = createMock(FinalDemo.class); expect(finalDemo.say("something")).andReturn("something else"); replayAll(); final String actual = finalDemo.say("something"); verifyAll(); assertEquals("something else", actual); } } ================================================ FILE: tests/easymock/testng/src/test/java/samples/testng/MockStaticExtendsPowerMockTestCaseTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.testng; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.testng.PowerMockTestCase; import org.testng.Assert; import org.testng.annotations.Test; import samples.singleton.StaticHelper; import samples.singleton.StaticService; import static org.easymock.EasyMock.expect; import static org.powermock.api.easymock.PowerMock.*; /** * Test class to demonstrate static, static+final, static+native and * static+final+native methods mocking. * * @author Johan Haleby * @author Jan Kronquist */ @PrepareForTest( { StaticService.class, StaticHelper.class }) public class MockStaticExtendsPowerMockTestCaseTest extends PowerMockTestCase { @Test public void testMockStatic() throws Exception { mockStatic(StaticService.class); String expected = "Hello altered World"; expect(StaticService.say("hello")).andReturn("Hello altered World"); replay(StaticService.class); String actual = StaticService.say("hello"); verify(StaticService.class); Assert.assertEquals(expected, actual); // Singleton still be mocked by now. try { StaticService.say("world"); Assert.fail("Should throw AssertionError!"); } catch (AssertionError e) { Assert.assertEquals("\n Unexpected method call StaticService.say(\"world\"):", e.getMessage()); } } @Test public void testMockStaticFinal() throws Exception { mockStatic(StaticService.class); String expected = "Hello altered World"; expect(StaticService.sayFinal("hello")).andReturn("Hello altered World"); replay(StaticService.class); String actual = StaticService.sayFinal("hello"); verify(StaticService.class); Assert.assertEquals(expected, actual); // Singleton still be mocked by now. try { StaticService.sayFinal("world"); Assert.fail("Should throw AssertionError!"); } catch (AssertionError e) { Assert.assertEquals("\n Unexpected method call StaticService.sayFinal(\"world\"):", e.getMessage()); } } } ================================================ FILE: tests/easymock/testng/src/test/java/samples/testng/MockStaticTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.testng; import org.powermock.core.classloader.annotations.PrepareForTest; import org.testng.Assert; import org.testng.annotations.Test; import samples.singleton.StaticHelper; import samples.singleton.StaticService; import static org.easymock.EasyMock.expect; import static org.powermock.api.easymock.PowerMock.mockStatic; import static org.powermock.api.easymock.PowerMock.replay; import static org.powermock.api.easymock.PowerMock.verify; /** * Test class to demonstrate static, static+final, static+native and * static+final+native methods mocking. * * @author Johan Haleby * @author Jan Kronquist */ @PrepareForTest( { StaticService.class, StaticHelper.class }) public class MockStaticTest { @Test public void testMockStatic() throws Exception { mockStatic(StaticService.class); String expected = "Hello altered World"; expect(StaticService.say("hello")).andReturn("Hello altered World"); replay(StaticService.class); String actual = StaticService.say("hello"); verify(StaticService.class); Assert.assertEquals(expected, actual); } @Test public void testMockStaticFinal() throws Exception { mockStatic(StaticService.class); String expected = "Hello altered World"; expect(StaticService.sayFinal("hello")).andReturn("Hello altered World"); replay(StaticService.class); String actual = StaticService.sayFinal("hello"); verify(StaticService.class); Assert.assertEquals(expected, actual); } } ================================================ FILE: tests/easymock/testng/src/test/java/samples/testng/NotAnnotatedWithPrepareForTest.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.testng; import org.powermock.core.classloader.MockClassLoader; import org.testng.annotations.Test; import static org.testng.Assert.assertFalse; public class NotAnnotatedWithPrepareForTest { @Test public void classesNotAnnotatedWithPrepareForTestAreNotLoadedByPowerMockClassloader() throws Exception { final ClassLoader classLoader = getClass().getClassLoader(); assertFalse(MockClassLoader.class.getName().equals(classLoader.getClass().getName())); } } ================================================ FILE: tests/easymock/testng/src/test/java/samples/testng/PartialMockingWithBeforeClassTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.testng; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.testng.PowerMockTestCase; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import samples.privateandfinal.PrivateFinal; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; import static org.powermock.api.easymock.PowerMock.createPartialMock; import static org.powermock.api.easymock.PowerMock.expectPrivate; /** * Test class to demonstrate private+final method mocking. */ @PrepareForTest(PrivateFinal.class) public class PartialMockingWithBeforeClassTest extends PowerMockTestCase { private PrivateFinal tested; @BeforeClass public void setup() { tested = createPartialMock(PrivateFinal.class, "sayIt"); } @Test public void partialMockingWithMockCreatedInBeforeClassMethod() throws Exception { String expected = "Hello altered World"; expectPrivate(tested, "sayIt", "name").andReturn(expected); replay(tested); String actual = tested.say("name"); verify(tested); Assert.assertEquals(expected, actual); } } ================================================ FILE: tests/easymock/testng/src/test/java/samples/testng/PrivateFinalTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.testng; import org.powermock.core.classloader.annotations.PrepareForTest; import org.testng.Assert; import org.testng.annotations.Test; import samples.privateandfinal.PrivateFinal; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; import static org.powermock.api.easymock.PowerMock.createPartialMock; import static org.powermock.api.easymock.PowerMock.expectPrivate; /** * Test class to demonstrate private+final method mocking. */ @PrepareForTest(PrivateFinal.class) public class PrivateFinalTest { @Test public void testSay() throws Exception { PrivateFinal tested = createPartialMock(PrivateFinal.class, "sayIt"); String expected = "Hello altered World"; expectPrivate(tested, "sayIt", "name").andReturn(expected); replay(tested); String actual = tested.say("name"); verify(tested); Assert.assertEquals(expected, actual); } @Test public void testMultiMock() throws Exception { PrivateFinal tested1 = createPartialMock(PrivateFinal.class, "sayIt"); String expected1 = "Hello altered World"; expectPrivate(tested1, "sayIt", "name").andReturn(expected1); replay(tested1); PrivateFinal tested2 = createPartialMock(PrivateFinal.class, "sayIt"); String expected2 = "Hello qweqweqwe"; expectPrivate(tested2, "sayIt", "name").andReturn(expected2); replay(tested2); String actual1 = tested1.say("name"); verify(tested1); Assert.assertEquals(expected1, actual1); String actual2 = tested2.say("name"); verify(tested2); Assert.assertEquals(expected2, actual2); } } ================================================ FILE: tests/easymock/testng/src/test/java/samples/testng/SampleServletTest.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.testng; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.testng.PowerMockObjectFactory; import org.testng.IObjectFactory; import org.testng.annotations.ObjectFactory; import org.testng.annotations.Test; import samples.servletmocking.SampleServlet; import javax.servlet.http.HttpServletResponse; import java.io.PrintWriter; import static org.easymock.EasyMock.expect; import static org.powermock.api.easymock.PowerMock.*; @PrepareForTest(SampleServlet.class) public class SampleServletTest { @Test public void doGet() throws Exception { SampleServlet servlet = new SampleServlet(); HttpServletResponse response = createMock(HttpServletResponse.class); PrintWriter writer = createMock(PrintWriter.class); expect(response.getWriter()).andReturn(writer); writer.write("out"); replay(response, writer); servlet.doGet(null, response); verify(response, writer); } @ObjectFactory public IObjectFactory getObjectFactory() { return new PowerMockObjectFactory(); } } ================================================ FILE: tests/easymock/testng/src/test/java/samples/testng/StaticInitializerExampleTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.testng; import org.testng.annotations.Test; import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor; import org.powermock.reflect.Whitebox; import samples.staticinitializer.StaticInitializerExample; import java.util.HashSet; import static org.testng.Assert.*; import org.powermock.modules.testng.PowerMockTestCase; @SuppressStaticInitializationFor("samples.staticinitializer.StaticInitializerExample") public class StaticInitializerExampleTest extends PowerMockTestCase { @Test public void testSupressStaticInitializer() throws Exception { assertNull(StaticInitializerExample.getMySet(), "Should be null because the static initializer should be suppressed"); } @Test public void testSupressStaticInitializerAndSetFinalField() throws Exception { assertNull(StaticInitializerExample.getMySet(), "Should be null because the static initializer should be suppressed"); final HashSet hashSet = new HashSet(); Whitebox.setInternalState(StaticInitializerExample.class, "mySet", hashSet); assertSame(hashSet, Whitebox.getInternalState(StaticInitializerExample.class, "mySet")); } } ================================================ FILE: tests/easymock/testng/src/test/java/samples/testng/SystemClassUserTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.testng; import org.powermock.core.classloader.annotations.PrepareForTest; import org.testng.annotations.Test; import samples.system.SystemClassUser; import java.net.InetAddress; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import java.util.Collections; import java.util.LinkedList; import java.util.List; import static org.easymock.EasyMock.anyLong; import static org.easymock.EasyMock.expect; import static org.powermock.api.easymock.PowerMock.*; import static org.testng.Assert.assertSame; import static org.testng.Assert.assertTrue; import static org.testng.AssertJUnit.assertEquals; /** * Demonstrates PowerMock's ability to mock non-final and final system classes. * To mock a system class you need to prepare the calling class for testing. * I.e. let's say you're testing class A which interacts with URLEncoder then * you would do: * *
 *
 * @PrepareForTest({A.class})
 *
 * 
*/ @PrepareForTest( { SystemClassUser.class }) public class SystemClassUserTest { @Test public void assertThatMockingOfNonFinalSystemClassesWorks() throws Exception { mockStatic(URLEncoder.class); expect(URLEncoder.encode("string", "enc")).andReturn("something"); replayAll(); assertEquals("something", new SystemClassUser().performEncode()); verifyAll(); } @Test public void assertThatMockingOfTheRuntimeSystemClassWorks() throws Exception { mockStatic(Runtime.class); Runtime runtimeMock = createMock(Runtime.class); Process processMock = createMock(Process.class); expect(Runtime.getRuntime()).andReturn(runtimeMock); expect(runtimeMock.exec("command")).andReturn(processMock); replayAll(); assertSame(processMock, new SystemClassUser().executeCommand()); verifyAll(); } @Test public void assertThatMockingOfFinalSystemClassesWorks() throws Exception { mockStatic(System.class); expect(System.getProperty("property")).andReturn("my property"); replayAll(); assertEquals("my property", new SystemClassUser().getSystemProperty()); verifyAll(); } @Test public void assertThatPartialMockingOfFinalSystemClassesWorks() throws Exception { mockStaticPartial(System.class, "nanoTime"); expect(System.nanoTime()).andReturn(2L); replayAll(); new SystemClassUser().doMoreComplicatedStuff(); assertEquals("2", System.getProperty("nanoTime")); verifyAll(); } @Test public void assertThatMockingOfCollectionsWork() throws Exception { List list = new LinkedList(); mockStatic(Collections.class); Collections.shuffle(list); expectLastCall().once(); replayAll(); new SystemClassUser().shuffleCollection(list); verifyAll(); } @Test public void assertThatPartialMockingOfFinalSystemClassesWorksForNonVoidMethods() throws Exception { mockStaticPartial(System.class, "getProperty"); expect(System.getProperty("property")).andReturn("my property"); replayAll(); final SystemClassUser systemClassUser = new SystemClassUser(); systemClassUser.copyProperty("to", "property"); verifyAll(); } @Test public void assertThatMockingStringWorks() throws Exception { mockStatic(String.class); final String string = "string"; final String args = "args"; final String returnValue = "returnValue"; expect(String.format(string, args)).andReturn(returnValue); replayAll(); final SystemClassUser systemClassUser = new SystemClassUser(); assertEquals(systemClassUser.format(string, args), returnValue); verifyAll(); } @Test public void mockingStaticVoidMethodWorks() throws Exception { mockStatic(Thread.class); Thread.sleep(anyLong()); expectLastCall().once(); replayAll(); long startTime = System.currentTimeMillis(); final SystemClassUser systemClassUser = new SystemClassUser(); systemClassUser.threadSleep(); long endTime = System.currentTimeMillis(); assertTrue(endTime - startTime < 5000); verifyAll(); } @Test public void mockingInstanceMethodOfFinalSystemClassWorks() throws Exception { URL url = createMock(URL.class); URLConnection urlConnection = createMock(URLConnection.class); expect(url.openConnection()).andStubReturn(urlConnection); replayAll(); final SystemClassUser systemClassUser = new SystemClassUser(); assertSame(urlConnection, systemClassUser.useURL(url)); verifyAll(); } @Test public void mockingURLWorks() throws Exception { URL url = createMock(URL.class); URLConnection urlConnectionMock = createMock(URLConnection.class); expect(url.openConnection()).andReturn(urlConnectionMock); replayAll(); assertSame(url.openConnection(), urlConnectionMock); verifyAll(); } @Test public void mockingInetAddressWorks() throws Exception { final InetAddress mock = createMock(InetAddress.class); mockStatic(InetAddress.class); expect(InetAddress.getLocalHost()).andReturn(mock); replayAll(); final SystemClassUser systemClassUser = new SystemClassUser(); assertSame(mock, systemClassUser.getLocalHost()); verifyAll(); } } ================================================ FILE: tests/easymock/testng/suite.xml ================================================ ================================================ FILE: tests/easymock/testng-agent/src/test/java/samples/testng/agent/AnnotationDemoTest.java ================================================ package samples.testng.agent; import org.powermock.api.easymock.annotation.Mock; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.testng.PowerMockTestCase; import org.testng.Assert; import org.testng.annotations.Test; import samples.Service; import samples.annotationbased.AnnotationDemo; import static org.easymock.EasyMock.expect; import static org.powermock.api.easymock.PowerMock.replayAll; import static org.powermock.api.easymock.PowerMock.verifyAll; /** * Verifies that PowerMock test listeners works correctly in TestNG. */ @PrepareForTest public class AnnotationDemoTest extends PowerMockTestCase { @Mock private Service serviceMock; @Test public void assertInjectionWorked() throws Exception { AnnotationDemo tested = new AnnotationDemo(serviceMock); final String expected = "mock"; expect(serviceMock.getServiceMessage()).andReturn(expected); replayAll(); Assert.assertEquals(expected, tested.getServiceMessage()); verifyAll(); } } ================================================ FILE: tests/easymock/testng-agent/src/test/java/samples/testng/agent/AnnotationDemoWithBeforeMethodTest.java ================================================ package samples.testng.agent; import org.powermock.api.easymock.annotation.Mock; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.testng.PowerMockTestCase; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import samples.Service; import samples.annotationbased.AnnotationDemo; import static org.easymock.EasyMock.expect; import static org.powermock.api.easymock.PowerMock.replayAll; import static org.powermock.api.easymock.PowerMock.verifyAll; /** * Verifies that PowerMock test listeners works correctly with before methods in * TestNG. */ public class AnnotationDemoWithBeforeMethodTest extends PowerMockTestCase { @Mock private Service serviceMock; private AnnotationDemo tested; @BeforeMethod public void setup() { tested = new AnnotationDemo(serviceMock); } @Test @PrepareForTest public void assertInjectionWorked() throws Exception { final String expected = "mock"; expect(serviceMock.getServiceMessage()).andReturn(expected); replayAll(); Assert.assertEquals(expected, tested.getServiceMessage()); verifyAll(); } } ================================================ FILE: tests/easymock/testng-agent/src/test/java/samples/testng/agent/FinalDemoTest.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.testng.agent; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.testng.PowerMockTestCase; import org.testng.AssertJUnit; import org.testng.annotations.Test; import samples.finalmocking.FinalDemo; import static org.easymock.EasyMock.expect; import static org.powermock.api.easymock.PowerMock.*; import static org.testng.Assert.fail; import static org.testng.AssertJUnit.assertEquals; /** * Test class to demonstrate non-static final mocking. * */ @PrepareForTest(FinalDemo.class) public class FinalDemoTest extends PowerMockTestCase { @Test public void testSay() throws Exception { FinalDemo tested = createMock(FinalDemo.class); String expected = "Hello altered World"; expect(tested.say("hello")).andReturn("Hello altered World"); replay(tested); String actual = tested.say("hello"); verify(tested); AssertJUnit.assertEquals("Expected and actual did not match", expected, actual); // Should still be mocked by now. try { tested.say("world"); fail("Should throw AssertionError!"); } catch (AssertionError e) { assertEquals("\n Unexpected method call FinalDemo.say(\"world\"):", e.getMessage()); } } @Test public void testSayFinalNative() throws Exception { FinalDemo tested = createMock(FinalDemo.class); String expected = "Hello altered World"; expect(tested.sayFinalNative("hello")).andReturn("Hello altered World"); replay(tested); String actual = tested.sayFinalNative("hello"); verify(tested); assertEquals("Expected and actual did not match", expected, actual); // Should still be mocked by now. try { tested.sayFinalNative("world"); fail("Should throw AssertionError!"); } catch (AssertionError e) { assertEquals("\n Unexpected method call FinalDemo.sayFinalNative(\"world\"):", e.getMessage()); } } } ================================================ FILE: tests/easymock/testng-agent/src/test/java/samples/testng/agent/MockStaticExtendsPowerMockTestCaseTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.testng.agent; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.testng.PowerMockTestCase; import org.testng.Assert; import org.testng.annotations.Test; import samples.singleton.StaticHelper; import samples.singleton.StaticService; import static org.easymock.EasyMock.expect; import static org.powermock.api.easymock.PowerMock.*; /** * Test class to demonstrate static, static+final, static+native and * static+final+native methods mocking. * * @author Johan Haleby * @author Jan Kronquist */ @PrepareForTest( { StaticService.class, StaticHelper.class }) public class MockStaticExtendsPowerMockTestCaseTest extends PowerMockTestCase { @Test public void testMockStatic() throws Exception { mockStatic(StaticService.class); String expected = "Hello altered World"; expect(StaticService.say("hello")).andReturn("Hello altered World"); replay(StaticService.class); String actual = StaticService.say("hello"); verify(StaticService.class); Assert.assertEquals(expected, actual); // Singleton still be mocked by now. try { StaticService.say("world"); Assert.fail("Should throw AssertionError!"); } catch (AssertionError e) { Assert.assertEquals("\n Unexpected method call StaticService.say(\"world\"):", e.getMessage()); } } @Test public void testMockStaticFinal() throws Exception { mockStatic(StaticService.class); String expected = "Hello altered World"; expect(StaticService.sayFinal("hello")).andReturn("Hello altered World"); replay(StaticService.class); String actual = StaticService.sayFinal("hello"); verify(StaticService.class); Assert.assertEquals(expected, actual); // Singleton still be mocked by now. try { StaticService.sayFinal("world"); Assert.fail("Should throw AssertionError!"); } catch (AssertionError e) { Assert.assertEquals("\n Unexpected method call StaticService.sayFinal(\"world\"):", e.getMessage()); } } } ================================================ FILE: tests/easymock/testng-agent/src/test/java/samples/testng/agent/MockStaticTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.testng.agent; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.testng.PowerMockTestCase; import org.testng.Assert; import org.testng.annotations.Test; import samples.singleton.StaticHelper; import samples.singleton.StaticService; import static org.easymock.EasyMock.expect; import static org.powermock.api.easymock.PowerMock.mockStatic; import static org.powermock.api.easymock.PowerMock.replay; import static org.powermock.api.easymock.PowerMock.verify; /** * Test class to demonstrate static, static+final, static+native and * static+final+native methods mocking. * * @author Johan Haleby * @author Jan Kronquist */ @PrepareForTest( { StaticService.class, StaticHelper.class }) public class MockStaticTest extends PowerMockTestCase { @Test public void testMockStatic() throws Exception { mockStatic(StaticService.class); String expected = "Hello altered World"; expect(StaticService.say("hello")).andReturn("Hello altered World"); replay(StaticService.class); String actual = StaticService.say("hello"); verify(StaticService.class); Assert.assertEquals(expected, actual); } @Test public void testMockStaticFinal() throws Exception { mockStatic(StaticService.class); String expected = "Hello altered World"; expect(StaticService.sayFinal("hello")).andReturn("Hello altered World"); replay(StaticService.class); String actual = StaticService.sayFinal("hello"); verify(StaticService.class); Assert.assertEquals(expected, actual); } } ================================================ FILE: tests/easymock/testng-agent/src/test/java/samples/testng/agent/NotAnnotatedWithPrepareForTest.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.testng.agent; import org.powermock.core.classloader.MockClassLoader; import org.testng.annotations.Test; import static org.testng.Assert.assertFalse; public class NotAnnotatedWithPrepareForTest { @Test public void classesNotAnnotatedWithPrepareForTestAreNotLoadedByPowerMockClassloader() throws Exception { final ClassLoader classLoader = getClass().getClassLoader(); assertFalse(MockClassLoader.class.getName().equals(classLoader.getClass().getName())); } } ================================================ FILE: tests/easymock/testng-agent/src/test/java/samples/testng/agent/PartialMockingWithBeforeClassTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.testng.agent; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.testng.PowerMockTestCase; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import samples.privateandfinal.PrivateFinal; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; import static org.powermock.api.easymock.PowerMock.createPartialMock; import static org.powermock.api.easymock.PowerMock.expectPrivate; /** * Test class to demonstrate private+final method mocking. */ @PrepareForTest(PrivateFinal.class) public class PartialMockingWithBeforeClassTest extends PowerMockTestCase { private PrivateFinal tested; @BeforeClass public void setup() { tested = createPartialMock(PrivateFinal.class, "sayIt"); } @Test public void partialMockingWithMockCreatedInBeforeClassMethod() throws Exception { String expected = "Hello altered World"; expectPrivate(tested, "sayIt", "name").andReturn(expected); replay(tested); String actual = tested.say("name"); verify(tested); Assert.assertEquals(expected, actual); } } ================================================ FILE: tests/easymock/testng-agent/src/test/java/samples/testng/agent/PrivateFinalTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.testng.agent; import org.powermock.core.classloader.annotations.PrepareForTest; import org.testng.Assert; import org.testng.annotations.Test; import samples.privateandfinal.PrivateFinal; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; import static org.powermock.api.easymock.PowerMock.createPartialMock; import static org.powermock.api.easymock.PowerMock.expectPrivate; /** * Test class to demonstrate private+final method mocking. */ @PrepareForTest(PrivateFinal.class) public class PrivateFinalTest { @Test public void testSay() throws Exception { PrivateFinal tested = createPartialMock(PrivateFinal.class, "sayIt"); String expected = "Hello altered World"; expectPrivate(tested, "sayIt", "name").andReturn(expected); replay(tested); String actual = tested.say("name"); verify(tested); Assert.assertEquals(expected, actual); } @Test public void testMultiMock() throws Exception { PrivateFinal tested1 = createPartialMock(PrivateFinal.class, "sayIt"); String expected1 = "Hello altered World"; expectPrivate(tested1, "sayIt", "name").andReturn(expected1); replay(tested1); PrivateFinal tested2 = createPartialMock(PrivateFinal.class, "sayIt"); String expected2 = "Hello qweqweqwe"; expectPrivate(tested2, "sayIt", "name").andReturn(expected2); replay(tested2); String actual1 = tested1.say("name"); verify(tested1); Assert.assertEquals(expected1, actual1); String actual2 = tested2.say("name"); verify(tested2); Assert.assertEquals(expected2, actual2); } } ================================================ FILE: tests/easymock/testng-agent/src/test/java/samples/testng/agent/SampleServletTest.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.testng.agent; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.testng.PowerMockObjectFactory; import org.testng.IObjectFactory; import org.testng.annotations.ObjectFactory; import org.testng.annotations.Test; import samples.servletmocking.SampleServlet; import javax.servlet.http.HttpServletResponse; import java.io.PrintWriter; import static org.easymock.EasyMock.expect; import static org.powermock.api.easymock.PowerMock.*; @PrepareForTest(SampleServlet.class) public class SampleServletTest { @Test public void doGet() throws Exception { SampleServlet servlet = new SampleServlet(); HttpServletResponse response = createMock(HttpServletResponse.class); PrintWriter writer = createMock(PrintWriter.class); expect(response.getWriter()).andReturn(writer); writer.write("out"); replay(response, writer); servlet.doGet(null, response); verify(response, writer); } @ObjectFactory public IObjectFactory getObjectFactory() { return new PowerMockObjectFactory(); } } ================================================ FILE: tests/easymock/testng-agent/src/test/java/samples/testng/agent/SystemClassUserTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.testng.agent; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.testng.PowerMockTestCase; import org.testng.annotations.Test; import samples.system.SystemClassUser; import java.net.InetAddress; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import java.util.Collections; import java.util.LinkedList; import java.util.List; import static org.easymock.EasyMock.anyLong; import static org.easymock.EasyMock.expect; import static org.powermock.api.easymock.PowerMock.*; import static org.testng.Assert.assertSame; import static org.testng.Assert.assertTrue; import static org.testng.AssertJUnit.assertEquals; /** * Demonstrates PowerMock's ability to mock non-final and final system classes. * To mock a system class you need to prepare the calling class for testing. * I.e. let's say you're testing class A which interacts with URLEncoder then * you would do: * *
 *
 * @PrepareForTest({A.class})
 *
 * 
*/ @PrepareForTest( { SystemClassUser.class }) public class SystemClassUserTest extends PowerMockTestCase { @Test public void assertThatMockingOfNonFinalSystemClassesWorks() throws Exception { mockStatic(URLEncoder.class); expect(URLEncoder.encode("string", "enc")).andReturn("something"); replayAll(); assertEquals("something", new SystemClassUser().performEncode()); verifyAll(); } @Test public void assertThatMockingOfTheRuntimeSystemClassWorks() throws Exception { mockStatic(Runtime.class); Runtime runtimeMock = createMock(Runtime.class); Process processMock = createMock(Process.class); expect(Runtime.getRuntime()).andReturn(runtimeMock); expect(runtimeMock.exec("command")).andReturn(processMock); replayAll(); assertSame(processMock, new SystemClassUser().executeCommand()); verifyAll(); } @Test public void assertThatMockingOfFinalSystemClassesWorks() throws Exception { mockStatic(System.class); expect(System.getProperty("property")).andReturn("my property"); replayAll(); assertEquals("my property", new SystemClassUser().getSystemProperty()); verifyAll(); } @Test public void assertThatPartialMockingOfFinalSystemClassesWorks() throws Exception { mockStaticPartial(System.class, "nanoTime"); expect(System.nanoTime()).andReturn(2L); replayAll(); new SystemClassUser().doMoreComplicatedStuff(); assertEquals("2", System.getProperty("nanoTime")); verifyAll(); } @Test public void assertThatPartialMockingOfFinalSystemClassesWorksForNonVoidMethods() throws Exception { mockStaticPartial(System.class, "getProperty"); expect(System.getProperty("property")).andReturn("my property"); replayAll(); final SystemClassUser systemClassUser = new SystemClassUser(); systemClassUser.copyProperty("to", "property"); verifyAll(); } @Test public void assertThatMockingOfCollectionsWork() throws Exception { List list = new LinkedList(); mockStatic(Collections.class); Collections.shuffle(list); expectLastCall().once(); replayAll(); new SystemClassUser().shuffleCollection(list); verifyAll(); } @Test public void assertThatMockingStringWorks() throws Exception { mockStatic(String.class); final String string = "string"; final String args = "args"; final String returnValue = "returnValue"; expect(String.format(string, args)).andReturn(returnValue); replayAll(); final SystemClassUser systemClassUser = new SystemClassUser(); assertEquals(systemClassUser.format(string, args), returnValue); verifyAll(); } @Test public void mockingStaticVoidMethodWorks() throws Exception { mockStatic(Thread.class); Thread.sleep(anyLong()); expectLastCall().once(); replayAll(); long startTime = System.currentTimeMillis(); final SystemClassUser systemClassUser = new SystemClassUser(); systemClassUser.threadSleep(); long endTime = System.currentTimeMillis(); assertTrue(endTime - startTime < 5000); verifyAll(); } @Test public void mockingInstanceMethodOfFinalSystemClassWorks() throws Exception { URL url = createMock(URL.class); URLConnection urlConnection = createMock(URLConnection.class); expect(url.openConnection()).andStubReturn(urlConnection); replayAll(); final SystemClassUser systemClassUser = new SystemClassUser(); assertSame(urlConnection, systemClassUser.useURL(url)); verifyAll(); } @Test public void mockingURLWorks() throws Exception { URL url = createMock(URL.class); URLConnection urlConnectionMock = createMock(URLConnection.class); expect(url.openConnection()).andReturn(urlConnectionMock); replayAll(); assertSame(url.openConnection(), urlConnectionMock); verifyAll(); } @Test public void mockingInetAddressWorks() throws Exception { final InetAddress mock = createMock(InetAddress.class); mockStatic(InetAddress.class); expect(InetAddress.getLocalHost()).andReturn(mock); replayAll(); final SystemClassUser systemClassUser = new SystemClassUser(); assertSame(mock, systemClassUser.getLocalHost()); verifyAll(); } } ================================================ FILE: tests/easymock/testng-agent/suite.xml ================================================ ================================================ FILE: tests/java11/build.gradle ================================================ configure(project.subprojects) { subproject -> // TODO: uncomment the followings once gradle supports JDK11 // if (JavaVersion.current() != JavaVersion.VERSION_11) { // project.tasks.all { task -> task.enabled = false } // } dependencies { testCompile("junit:junit:${junitVersion}") { exclude group: 'org.hamcrest', module: 'hamcrest-core' } testCompile("org.hamcrest:hamcrest-core:${hamcrestVersion}") testCompile("org.assertj:assertj-core:${assertjVersion}") testCompile files(project(":tests:mockito:junit4").sourceSets.test.output) } // TODO: uncomment the followings once JDK11 is supported // compileJava { // sourceCompatibility = 11 // targetCompatibility = 11 // } // // compileTestJava { // sourceCompatibility = 11 // targetCompatibility = 11 // } } project(":tests:java11:mockito-junit4") { description = "Tests for Mockito module with JUnit 4.x. and Java11." dependencies { testCompile project(":powermock-modules:powermock-module-junit4") testCompile project(":powermock-api:powermock-api-mockito2") testCompile ("org.mockito:mockito-core:${mockitoVersion}"){ exclude group: 'net.bytebuddy', module: 'byte-buddy' exclude group: 'net.bytebuddy', module: 'byte-buddy-agent' } } } ================================================ FILE: tests/java11/mockito-junit4/src/main/java/samples/powermockito/junit4/bugs/github958/OuterClass.java ================================================ package samples.powermockito.junit4.bugs.github958; public class OuterClass { public static InnerSingleton theInstance = new InnerSingleton(); public static class InnerSingleton { public String name = "inner"; private InnerSingleton() {} } } ================================================ FILE: tests/java11/mockito-junit4/src/test/java/samples/powermockito/junit4/bugs/github958/Github958Test.java ================================================ package samples.powermockito.junit4.bugs.github958; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import static org.junit.Assert.*; @RunWith(PowerMockRunner.class) @PrepareForTest(OuterClass.class) public class Github958Test { @Test public void test() { assertEquals("inner", OuterClass.theInstance.name); } } ================================================ FILE: tests/java8/build.gradle ================================================ configure(project.subprojects) { subproject -> if (JavaVersion.current() != JavaVersion.VERSION_1_8) { project.tasks.all { task -> task.enabled = false } } dependencies { testCompile("junit:junit:${junitVersion}") { exclude group: 'org.hamcrest', module: 'hamcrest-core' } testCompile("org.hamcrest:hamcrest-core:${hamcrestVersion}") testCompile("org.assertj:assertj-core:${assertjVersion}") testCompile files(project(":tests:mockito:junit4").sourceSets.test.output) } compileJava { sourceCompatibility = 1.8 targetCompatibility = 1.8 } compileTestJava { sourceCompatibility = 1.8 targetCompatibility = 1.8 } } project(":tests:java8:mockito-junit4") { description = "Tests for Mockito module with JUnit 4.x. and Java8." dependencies { testCompile project(":powermock-modules:powermock-module-junit4") testCompile project(":powermock-api:powermock-api-mockito2") testCompile ("org.mockito:mockito-core:${mockitoVersion}"){ exclude group: 'net.bytebuddy', module: 'byte-buddy' exclude group: 'net.bytebuddy', module: 'byte-buddy-agent' } } } project(":tests:java8:easymock-junit4") { description = "Tests for Easymock module with JUnit 4.x. and Java8." dependencies { testCompile project(":powermock-api:powermock-api-easymock") testCompile project(":powermock-modules:powermock-module-junit4") testCompile("org.easymock:easymock:${easymockVersion}") testCompile("org.assertj:assertj-core:${assertjVersion}") testCompile("org.hamcrest:hamcrest-core:${hamcrestVersion}") } } project(":tests:java8:mockito-junit4-agent") { description = "Tests for Mockito module with JUnit 4.x. and Java8." dependencies { testCompile project(":powermock-api:powermock-api-mockito2") testCompile ("org.mockito:mockito-core:${mockitoVersion}"){ exclude group: 'net.bytebuddy', module: 'byte-buddy' exclude group: 'net.bytebuddy', module: 'byte-buddy-agent' } testCompile project(":powermock-modules:powermock-module-junit4-rule-agent") } def pathToAgent = project(":powermock-modules:powermock-module-javaagent").jar.outputs.files.getFiles().getAt(0) test { jvmArgs "-javaagent:${pathToAgent}" } } project(":tests:java8:mockito-junit4-rule-xstream") { description = "Tests for Mockito module with JUnit 4.x, Java8 and rules-xstream." dependencies { testCompile project(":powermock-modules:powermock-module-junit4-rule") testCompile project(":powermock-classloading:powermock-classloading-xstream") testCompile project(":powermock-api:powermock-api-mockito2") testCompile ("org.mockito:mockito-core:${mockitoVersion}"){ exclude group: 'net.bytebuddy', module: 'byte-buddy' exclude group: 'net.bytebuddy', module: 'byte-buddy-agent' } testCompile files(project(":tests:mockito:junit4").sourceSets.test.output) } } ================================================ FILE: tests/java8/easymock-junit4/src/main/java/samples/powermockito/junit4/bugs/github717/Instance.java ================================================ package samples.powermockito.junit4.bugs.github717; public class Instance { } ================================================ FILE: tests/java8/easymock-junit4/src/main/java/samples/powermockito/junit4/bugs/github717/InstanceFacade.java ================================================ package samples.powermockito.junit4.bugs.github717; public interface InstanceFacade { } ================================================ FILE: tests/java8/easymock-junit4/src/main/java/samples/powermockito/junit4/bugs/github717/InstanceFacadeImpl.java ================================================ package samples.powermockito.junit4.bugs.github717; import java.util.HashMap; import java.util.Map; import java.util.function.Consumer; public class InstanceFacadeImpl implements InstanceFacade { final Map> instanceStatusProcessors = new HashMap<>(); { instanceStatusProcessors.put(InstanceStatus.PENDING, instance -> { // NOP }); } } ================================================ FILE: tests/java8/easymock-junit4/src/main/java/samples/powermockito/junit4/bugs/github717/InstanceStatus.java ================================================ package samples.powermockito.junit4.bugs.github717; public enum InstanceStatus { PENDING } ================================================ FILE: tests/java8/easymock-junit4/src/test/java/samples/powermockito/junit4/bugs/github717/InstanceFacadeImplTest.java ================================================ package samples.powermockito.junit4.bugs.github717; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.extension.listener.AnnotationEnabler; import org.powermock.core.classloader.annotations.PowerMockListener; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import static org.powermock.api.easymock.PowerMock.replayAll; import static org.powermock.api.easymock.PowerMock.verifyAll; @RunWith(PowerMockRunner.class) @PowerMockListener(AnnotationEnabler.class) @PrepareForTest(InstanceFacadeImpl.class) public class InstanceFacadeImplTest { private InstanceFacadeImpl instanceFacade; @Before public void setup() throws Exception { instanceFacade = new InstanceFacadeImpl(); } @Test public void should_not_throw_exception() throws Exception { replayAll(); instanceFacade.instanceStatusProcessors.get(InstanceStatus.PENDING).accept(null); verifyAll(); } } ================================================ FILE: tests/java8/easymock-junit4/src/test/java/samples/powermockito/junit4/bugs/github717/package-info.java ================================================ /** * Regression: MethodNotFoundException * https://github.com/powermock/powermock/issues/717 * * org.powermock.reflect.exceptions.MethodNotFoundException: No methods matching the name(s) accept were found in the class hierarchy of class java.lang.Object. at org.powermock.reflect.internal.WhiteboxImpl.getMethods(WhiteboxImpl.java:1720) at org.powermock.reflect.internal.WhiteboxImpl.getMethods(WhiteboxImpl.java:1745) at org.powermock.reflect.internal.WhiteboxImpl.getBestMethodCandidate(WhiteboxImpl.java:983) at org.powermock.core.MockGateway$MockInvocation.findMethodToInvoke(MockGateway.java:317) at org.powermock.core.MockGateway$MockInvocation.init(MockGateway.java:356) at org.powermock.core.MockGateway$MockInvocation.(MockGateway.java:307) at org.powermock.core.MockGateway.doMethodCall(MockGateway.java:142) at org.powermock.core.MockGateway.methodCall(MockGateway.java:125) at InstanceFacadeImplTest.pendingInstanceStatusProcessorShouldDoNothing(InstanceFacadeI * */ package samples.powermockito.junit4.bugs.github717; ================================================ FILE: tests/java8/mockito-junit4/src/main/java/samples/powermockito/junit4/bugs/github510/ClassUsesInterface.java ================================================ package samples.powermockito.junit4.bugs.github510; /** * */ public class ClassUsesInterface { public String saySomething(){ return InterfaceWithStatic.sayHello(); } public String createAndSay(){ return InterfaceWithStatic.createAndSay(); } } ================================================ FILE: tests/java8/mockito-junit4/src/main/java/samples/powermockito/junit4/bugs/github510/ConstructorObject.java ================================================ package samples.powermockito.junit4.bugs.github510; /** * */ public class ConstructorObject { public String sayHello() { return null; } } ================================================ FILE: tests/java8/mockito-junit4/src/main/java/samples/powermockito/junit4/bugs/github510/InterfaceWithStatic.java ================================================ package samples.powermockito.junit4.bugs.github510; /** * */ public interface InterfaceWithStatic { static String sayHello(){ return "What's up?"; } static String createAndSay(){ return new ConstructorObject().sayHello(); } } ================================================ FILE: tests/java8/mockito-junit4/src/main/java/samples/powermockito/junit4/largemethod/InterfaceMethodExceedingJvmLimit.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package samples.powermockito.junit4.largemethod; /** * Example of class with method which after instrumentation is larger than JVM limit. */ public interface InterfaceMethodExceedingJvmLimit { /** * Method size after instrumentation is equal to 91265. */ static String init() { String a = "A"; a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A"; a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A"; a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A"; a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A"; a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A"; a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A"; a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A"; a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A"; a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A"; a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A"; a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A"; a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A"; a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A"; a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A"; a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A"; a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A"; a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A"; return a; } } ================================================ FILE: tests/java8/mockito-junit4/src/test/java/org/powermock/modules/junit4/largemethod/LargeMethodInInterfaceTest.java ================================================ package org.powermock.modules.junit4.largemethod; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.powermockito.junit4.largemethod.InterfaceMethodExceedingJvmLimit; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertNull; import static junit.framework.Assert.assertSame; import static junit.framework.Assert.assertTrue; import static junit.framework.Assert.fail; import static org.mockito.Mockito.when; import static org.powermock.api.mockito.PowerMockito.mockStatic; import static org.powermock.api.mockito.PowerMockito.verifyStatic; import static org.powermock.api.support.membermodification.MemberModifier.suppress; @RunWith(PowerMockRunner.class) @PrepareForTest(InterfaceMethodExceedingJvmLimit.class) public class LargeMethodInInterfaceTest { @Test public void largeMethodShouldBeOverridden() { try { InterfaceMethodExceedingJvmLimit.init(); fail("Method should be overridden and exception should be thrown"); } catch (Exception e) { assertSame(IllegalAccessException.class, e.getClass()); assertTrue(e.getMessage().contains("Method was too large and after instrumentation exceeded JVM limit")); } } @Test public void largeMethodShouldBeAbleToBeSuppressed() { suppress(PowerMockito.method(InterfaceMethodExceedingJvmLimit.class, "init")); assertNull("Suppressed method should return: null", InterfaceMethodExceedingJvmLimit.init()); } @Test public void largeMethodShouldBeAbleToBeMocked() { mockStatic(InterfaceMethodExceedingJvmLimit.class); when(InterfaceMethodExceedingJvmLimit.init()).thenReturn("ok"); assertEquals("Mocked method should return: ok", "ok", InterfaceMethodExceedingJvmLimit.init()); verifyStatic(InterfaceMethodExceedingJvmLimit.class); InterfaceMethodExceedingJvmLimit.init(); } @Test(expected = IllegalStateException.class) public void largeMethodShouldBeAbleToBeMockedAndThrowException() { mockStatic(InterfaceMethodExceedingJvmLimit.class); when(InterfaceMethodExceedingJvmLimit.init()).thenThrow(new IllegalStateException()); InterfaceMethodExceedingJvmLimit.init(); verifyStatic(InterfaceMethodExceedingJvmLimit.class); InterfaceMethodExceedingJvmLimit.init(); } } ================================================ FILE: tests/java8/mockito-junit4/src/test/java/samples/powermockito/junit4/bugs/github510/Github510Test.java ================================================ package samples.powermockito.junit4.bugs.github510; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.powermock.api.mockito.PowerMockito.mock; import static org.powermock.api.mockito.PowerMockito.mockStatic; import static org.powermock.api.mockito.PowerMockito.when; import static org.powermock.api.mockito.PowerMockito.whenNew; /** * */ @RunWith(PowerMockRunner.class) @PrepareForTest({InterfaceWithStatic.class, ConstructorObject.class}) public class Github510Test { public ClassUsesInterface classUsesInterface; @Before public void setUp() throws Exception { classUsesInterface = new ClassUsesInterface(); } @Test public void testSaySomething() throws Exception { final String value = "Hi Man"; mockStatic(InterfaceWithStatic.class); when(InterfaceWithStatic.sayHello()).thenReturn(value); assertThat(classUsesInterface.saySomething()).isEqualTo(value); } @Test public void testInterfaceStaticCallsConstructor() throws Exception { final String value = "Hi Man"; ConstructorObject constructorObject = mock(ConstructorObject.class); when(constructorObject.sayHello()).thenReturn(value); whenNew(ConstructorObject.class).withNoArguments().thenReturn(constructorObject); assertThat(classUsesInterface.createAndSay()).isEqualTo(value); } } ================================================ FILE: tests/java8/mockito-junit4/src/test/java/samples/powermockito/junit4/bugs/github510/package-info.java ================================================ /** * https://github.com/jayway/powermock/issues/510 */ package samples.powermockito.junit4.bugs.github510; ================================================ FILE: tests/java8/mockito-junit4-agent/src/main/java/samples/powermockito/junit4/bugs/github510/ClassUsesInterface.java ================================================ package samples.powermockito.junit4.bugs.github510; /** * */ public class ClassUsesInterface { public String saySomething(){ return InterfaceWithStatic.sayHello(); } } ================================================ FILE: tests/java8/mockito-junit4-agent/src/main/java/samples/powermockito/junit4/bugs/github510/InterfaceWithStatic.java ================================================ package samples.powermockito.junit4.bugs.github510; /** * */ public interface InterfaceWithStatic { static String sayHello(){ return "What's up?"; } } ================================================ FILE: tests/java8/mockito-junit4-agent/src/test/java/samples/powermockito/junit4/bugs/github510/ClassUsesInterfaceTest.java ================================================ package samples.powermockito.junit4.bugs.github510; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.rule.PowerMockRule; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.powermock.api.mockito.PowerMockito.mockStatic; import static org.powermock.api.mockito.PowerMockito.when; /** * */ @PrepareForTest(InterfaceWithStatic.class) public class ClassUsesInterfaceTest { @Rule public PowerMockRule powerMockRule = new PowerMockRule(); public ClassUsesInterface classUsesInterface; @Before public void setUp() throws Exception { classUsesInterface = new ClassUsesInterface(); mockStatic(InterfaceWithStatic.class); } @Test public void testSaySomething() throws Exception { final String value = "Hi Man"; when(InterfaceWithStatic.sayHello()).thenReturn(value); assertThat(classUsesInterface.saySomething()).isEqualTo(value); } } ================================================ FILE: tests/java8/mockito-junit4-rule-xstream/src/main/java/samples/powermockito/junit4/bugs/github510/ClassUsesInterface.java ================================================ package samples.powermockito.junit4.bugs.github510; /** * */ public class ClassUsesInterface { public String saySomething(){ return InterfaceWithStatic.sayHello(); } } ================================================ FILE: tests/java8/mockito-junit4-rule-xstream/src/main/java/samples/powermockito/junit4/bugs/github510/InterfaceWithStatic.java ================================================ package samples.powermockito.junit4.bugs.github510; /** * */ public interface InterfaceWithStatic { static String sayHello(){ return "What's up?"; } } ================================================ FILE: tests/java8/mockito-junit4-rule-xstream/src/test/java/samples/powermockito/junit4/bugs/github510/ClassUsesInterfaceTest.java ================================================ package samples.powermockito.junit4.bugs.github510; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.rule.PowerMockRule; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.powermock.api.mockito.PowerMockito.mockStatic; import static org.powermock.api.mockito.PowerMockito.when; /** * */ @PrepareForTest(InterfaceWithStatic.class) public class ClassUsesInterfaceTest { @Rule public PowerMockRule powerMockRule = new PowerMockRule(); public ClassUsesInterface classUsesInterface; @Before public void setUp() throws Exception { classUsesInterface = new ClassUsesInterface(); mockStatic(InterfaceWithStatic.class); } @Test public void testSaySomething() throws Exception { final String value = "Hi Man"; when(InterfaceWithStatic.sayHello()).thenReturn(value); assertThat(classUsesInterface.saySomething()).isEqualTo(value); } } ================================================ FILE: tests/junit4/src/test/java/samples/powermockito/junit4/bugs/github352/GitHub352Test.java ================================================ package samples.powermockito.junit4.bugs.github352; import org.junit.Test; import org.junit.runner.JUnitCore; import org.junit.runner.Request; import org.junit.runner.Result; import org.junit.runner.Runner; import org.powermock.modules.junit4.PowerMockRunner; import static org.assertj.core.api.Java6Assertions.assertThat; public class GitHub352Test { @Test public void testCountShouldBe3WhenRunWithDefaultRunner() { JUnitCore jUnitCore = new JUnitCore(); Result result = jUnitCore.run(MyTest.class); int testCount = result.getRunCount(); assertThat(testCount).describedAs("Test count not match to expected.", 3).isEqualTo(3); } @Test public void testCountShouldBe3WhenRunWithPowerMockRunner() { JUnitCore jUnitCore = new JUnitCore(); Request request = new Request() { @Override public Runner getRunner() { try { return new PowerMockRunner(MyTest.class); } catch (Exception e) { throw new RuntimeException(e); } } }; Result result = jUnitCore.run(request); int testCount = result.getRunCount(); assertThat(testCount).describedAs("Test count not match to expected.", 3).isEqualTo(3); } } ================================================ FILE: tests/junit4/src/test/java/samples/powermockito/junit4/bugs/github352/MyAbstractTest.java ================================================ package samples.powermockito.junit4.bugs.github352; import org.junit.Test; /** * */ public abstract class MyAbstractTest { @Test public abstract void test1(); @Test public abstract void test2(); } ================================================ FILE: tests/junit4/src/test/java/samples/powermockito/junit4/bugs/github352/MyTest.java ================================================ package samples.powermockito.junit4.bugs.github352; import org.junit.Test; /** * */ public class MyTest extends MyAbstractTest { //some setup code here @Override public void test1() { //some test code here } @Override public void test2() { //some test code here } @Test public void test3() { // some test code here } } ================================================ FILE: tests/junit4/src/test/java/samples/powermockito/junit4/bugs/github352/package-info.java ================================================ /** * https://github.com/jayway/powermock/issues/352 */ package samples.powermockito.junit4.bugs.github352; ================================================ FILE: tests/junit4/src/test/java/samples/powermockito/junit4/bugs/github722/GitHub722Test.java ================================================ package samples.powermockito.junit4.bugs.github722; import org.junit.Rule; import org.junit.Test; import org.junit.contrib.java.lang.system.DisallowWriteToSystemErr; import org.powermock.modules.junit4.internal.impl.DelegatingPowerMockRunner; import org.powermock.reflect.Whitebox; import java.lang.reflect.Method; import static org.assertj.core.api.Java6Assertions.assertThat; public class GitHub722Test { @Rule public final DisallowWriteToSystemErr disallowWriteToSystemErr = new DisallowWriteToSystemErr(); @Test public void testDelegatingPowerMockRunnerUseTheories() throws Exception { String[] methodsToRun = {"testUseTheoriesTest"}; DelegatingPowerMockRunner test = new DelegatingPowerMockRunner(UseTheoriesTest.class, methodsToRun, null); Method[] methods = Whitebox.getInternalState(test, "testMethods"); String expected = "testUseTheoriesTest"; int expectedSize = 1; assertThat(methods.length).describedAs("Check array size").isEqualTo(expectedSize); assertThat(methods[0].getName()).describedAs("Test using Theory annotation").isEqualTo(expected); } @Test public void testDelegatingPowerMockRunnerUseJUnit() throws Exception { String[] methodsToRun = {"testJUnitTest"}; DelegatingPowerMockRunner test = new DelegatingPowerMockRunner(UseJUnitTest.class, methodsToRun, null); Method[] methods = Whitebox.getInternalState(test, "testMethods"); String expected = "testJUnitTest"; int expectedSize = 1; assertThat(methods.length).describedAs("Check array size").isEqualTo(expectedSize); assertThat(methods[0].getName()).describedAs("Test using Theory annotation").isEqualTo(expected); } } ================================================ FILE: tests/junit4/src/test/java/samples/powermockito/junit4/bugs/github722/UseJUnitTest.java ================================================ package samples.powermockito.junit4.bugs.github722; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.modules.junit4.PowerMockRunner; @RunWith(PowerMockRunner.class) public class UseJUnitTest { @Test public void testJUnitTest() { //some test code here } } ================================================ FILE: tests/junit4/src/test/java/samples/powermockito/junit4/bugs/github722/UseTheoriesTest.java ================================================ package samples.powermockito.junit4.bugs.github722; import org.junit.runner.RunWith; import org.junit.experimental.theories.Theories; import org.junit.experimental.theories.Theory; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunnerDelegate; @RunWith(PowerMockRunner.class) @PowerMockRunnerDelegate(Theories.class) public class UseTheoriesTest { @Theory public void testUseTheoriesTest() { //some test code here } } ================================================ FILE: tests/junit4/src/test/java/samples/powermockito/junit4/bugs/github733/GitHub733Test.java ================================================ package samples.powermockito.junit4.bugs.github733; import org.junit.Test; import org.powermock.modules.junit4.internal.impl.testcaseworkaround.PowerMockJUnit4MethodValidator; public class GitHub733Test { @Test public void testPowerMockJUnit4MethodValidatorAcceptsTestAnnotatedMethods() throws Exception { PowerMockJUnit4MethodValidator validator = new PowerMockJUnit4MethodValidator(new UseTestAnnotatedTest(UseTestAnnotatedTest.MethodToTest.class)); validator.validateInstanceMethods(); } } ================================================ FILE: tests/junit4/src/test/java/samples/powermockito/junit4/bugs/github733/UseTestAnnotatedTest.java ================================================ package samples.powermockito.junit4.bugs.github733; import org.junit.Test; import org.junit.experimental.runners.Enclosed; import org.junit.internal.runners.TestClass; import org.junit.runner.RunWith; import org.powermock.modules.junit4.PowerMockRunner; @RunWith(Enclosed.class) public class UseTestAnnotatedTest extends TestClass { public UseTestAnnotatedTest(Class klass) { super(klass); } @RunWith(PowerMockRunner.class) public static class MethodToTest { @Test public void genericMethod() { // no prefix of test for method name } } } ================================================ FILE: tests/mockito/build.gradle ================================================ configure(project.subprojects){ subproject -> dependencies { testCompile project(":tests:utils") testCompile("org.hamcrest:hamcrest-core:${hamcrestVersion}") testCompile("org.assertj:assertj-core:${assertjVersion}") testCompile project(":powermock-api:powermock-api-mockito2") testCompile ("org.mockito:mockito-core:${mockitoVersion}"){ exclude group: 'net.bytebuddy', module: 'byte-buddy' exclude group: 'net.bytebuddy', module: 'byte-buddy-agent' } } } project(":tests:mockito:junit4") { description = "Tests for Mockito module with JUnit 4.x." dependencies { testCompile project(":powermock-modules:powermock-module-junit4") testCompile("junit:junit:${junitVersion}"){ exclude group:'org.hamcrest', module:'hamcrest-core' } testCompile ("org.jacoco:org.jacoco.core:${jacocoVersion}") testCompile ("org.eclipse.jdt:core:${eclipseJdt}") } test{ exclude "**/*Cases*" } } project(":tests:mockito:inline") { description = "Tests for Mockito 2 inline mock maker" dependencies { testCompile project(":powermock-modules:powermock-module-junit4") testCompile("junit:junit:${junitVersion}"){ exclude group:'org.hamcrest', module:'hamcrest-core' } } test{ exclude "**/*Cases*" } } project(":tests:mockito:junit49") { description = "Tests for Mockito module with JUnit 4.9.x." dependencies { testCompile project(":tests:utils") testCompile project(":powermock-modules:powermock-module-junit4") testCompile("junit:junit:4.9"){ exclude group:'org.hamcrest', module:'hamcrest-core' } } } project(":tests:mockito:junit4-agent"){ description = "Tests for PowerMock Java agent with JUnit4 and Mockito." dependencies { testCompile project(":powermock-modules:powermock-module-junit4-rule-agent") testCompile("junit:junit:${junitVersion}"){ exclude group:'org.hamcrest', module:'hamcrest-core' } testCompile files(project(":tests:mockito:junit4").sourceSets.test.output) } def pathToAgent = project(":powermock-modules:powermock-module-javaagent").jar.outputs.files.getFiles().getAt(0) test { jvmArgs "-javaagent:${pathToAgent}" } } project(":tests:mockito:junit4-rule-objenesis") { description = "Tests for PowerMock Rule using Objenesis Deepcloning." dependencies { testCompile project(":powermock-modules:powermock-module-junit4-rule") testCompile project(":powermock-classloading:powermock-classloading-objenesis") testCompile("junit:junit:${junitVersion}"){ exclude group:'org.hamcrest', module:'hamcrest-core' } testCompile files(project(":tests:mockito:junit4").sourceSets.test.output) } } project(":tests:mockito:junit4-rule-xstream") { description = "Tests for PowerMock Rule using Xstream Deepcloning." dependencies { testCompile project(":powermock-modules:powermock-module-junit4-rule") testCompile project(":powermock-classloading:powermock-classloading-xstream") testCompile("junit:junit:${junitVersion}"){ exclude group:'org.hamcrest', module:'hamcrest-core' } testCompile files(project(":tests:mockito:junit4").sourceSets.test.output) } } project(":tests:mockito:junit4-delegate") { description = "Tests for PowerMock JUnit4 runner-delegate and Mockito." dependencies { testCompile project(":powermock-modules:powermock-module-junit4") testCompile("junit:junit:${junitVersion}"){ exclude group:'org.hamcrest', module:'hamcrest-core' } testCompile("pl.pragmatists:JUnitParams:1.0.5") testCompile files(project(":tests:mockito:junit4").sourceSets.test.output) } test{ scanForTestClasses = false include(["**/*Tests.class", "**/*Test.class"]) // Since we set scanForTestClasses to false, we need to filter out inner // classes with the "$" pattern; otherwise, using -Dtest.single=MyTests to // run MyTests by itself will fail if MyTests contains any inner classes. exclude(["**/Abstract*.class", '**/*$*']) } } project(":tests:mockito:testng"){ description = "Tests for Mockito module with TestNG." dependencies { testCompile(project(":powermock-core")) testCompile(project(":powermock-modules:powermock-module-testng")) testCompile("org.testng:testng:${testngVersion}") testCompile files(project(":tests:mockito:junit4").sourceSets.test.output) } test{ useTestNG(){ suites 'suite.xml' environment "mockitoVersion", "${mockitoVersion}" } } } ================================================ FILE: tests/mockito/inline/src/main/java/samples/powermockito/inline/bugs/github793/FinalClass.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package samples.powermockito.inline.bugs.github793; public final class FinalClass { public String ask(){ return "Hello, man!"; } public final void say(String message){ throw new RuntimeException(message); } } ================================================ FILE: tests/mockito/inline/src/main/java/samples/powermockito/inline/bugs/github793/StaticClass.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package samples.powermockito.inline.bugs.github793; public class StaticClass { public static String ask(){ return "Hello, man!"; } public static void say(String message){ throw new RuntimeException(message); } } ================================================ FILE: tests/mockito/inline/src/test/java/samples/powermockito/inline/bugs/github793/MockitoFinalClassMockingTest.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package samples.powermockito.inline.bugs.github793; import org.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.junit.Test; import org.mockito.Mockito; import org.powermock.api.mockito.MockitoVersion; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowable; import static org.junit.Assume.assumeTrue; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.when; public class MockitoFinalClassMockingTest { @Test public void should_mock_final_class_with_using_mockito_inline_mock_creator() { assumeTrue("Test make seances only for Mockito 2", MockitoVersion.isMockito2()); FinalClass mock = Mockito.mock(FinalClass.class); String value = "Why me?"; when(mock.ask()).thenReturn(value); assertThat(mock.ask()) .as("Mock for final class works") .isEqualTo(value); } @Test public void should_mock_final_method_with_using_mockito_inline_mock_creator() { assumeTrue("Test make seances only for Mockito 2", MockitoVersion.isMockito2()); final FinalClass mock = Mockito.mock(FinalClass.class); final String value = "Why me?"; doNothing().when(mock).say(value); Throwable throwable = catchThrowable(new ThrowingCallable() { @Override public void call() throws Throwable { mock.say(value); } }); assertThat(throwable) .as("Mock for final method works") .isNull(); } } ================================================ FILE: tests/mockito/inline/src/test/java/samples/powermockito/inline/bugs/github793/PartialMockingExampleTest.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.inline.bugs.github793; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.partialmocking.PartialMockingExample; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.verify; import static org.powermock.api.mockito.PowerMockito.doReturn; import static org.powermock.api.mockito.PowerMockito.spy; /** * Asserts that partial mocking (spying) with PowerMockito works for non-final * methods. */ @RunWith(PowerMockRunner.class) @PrepareForTest(PartialMockingExample.class) public class PartialMockingExampleTest { @Test public void validatingSpiedObjectGivesCorrectNumberOfExpectedInvocations() throws Exception { final String expected = "TEST VALUE"; PartialMockingExample underTest = spy(new PartialMockingExample()); doReturn(expected).when(underTest).methodToMock(); assertEquals(expected, underTest.methodToTest()); verify(underTest).methodToTest(); verify(underTest).methodToMock(); } @Test public void validatingSpiedObjectGivesCorrectNumberOfExpectedInvocationsForMockito() throws Exception { final String expected = "TEST VALUE"; PartialMockingExample underTest = Mockito.spy(new PartialMockingExample()); doReturn(expected).when(underTest).methodToMock(); assertEquals(expected, underTest.methodToTest()); verify(underTest).methodToTest(); verify(underTest).methodToMock(); } } ================================================ FILE: tests/mockito/inline/src/test/java/samples/powermockito/inline/bugs/github793/PowerMockStaticMockingTest.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package samples.powermockito.inline.bugs.github793; import org.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.exceptions.verification.NoInteractionsWanted; import org.powermock.api.mockito.MockitoVersion; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.assertj.core.api.Java6Assertions.assertThatThrownBy; import static org.junit.Assume.assumeTrue; import static org.mockito.Mockito.when; @RunWith(PowerMockRunner.class) @PrepareForTest(StaticClass.class) public class PowerMockStaticMockingTest { @Test public void should_mock_static_method_when_mockito_inline_mock_creator_for_mockito_tests() { assumeTrue("Test makes sense only for Mockito 2 & 3 & 4", MockitoVersion.isMockito2() || MockitoVersion.isMockito3() || MockitoVersion.isMockito4()); PowerMockito.mockStatic(StaticClass.class); String value = "Why me?"; when(StaticClass.ask()).thenReturn(value); assertThat(StaticClass.ask()) .as("Mock for static method works") .isEqualTo(value); } @Test public void should_verify_static_method_when_mockito_inline_mock_creator_for_mockito_tests() throws Exception { assumeTrue("Test makes sense only for Mockito 2 & 3 & 4", MockitoVersion.isMockito2() || MockitoVersion.isMockito3() || MockitoVersion.isMockito4()); PowerMockito.mockStatic(StaticClass.class); final String value = "Why me?"; PowerMockito.doNothing().when(StaticClass.class,"say", value); assertThatThrownBy(new ThrowingCallable() { @Override public void call() throws Throwable { StaticClass.say(value); PowerMockito.verifyNoMoreInteractions(StaticClass.class); } }).as("Verify exception is thrown") .isInstanceOf(NoInteractionsWanted.class); } } ================================================ FILE: tests/mockito/inline/src/test/resources/org/powermock/extensions/configuration.properties ================================================ mockito.mock-maker-class=mock-maker-inline ================================================ FILE: tests/mockito/junit4/src/main/java/samples/powermockito/junit4/bugs/github731/AType.java ================================================ package samples.powermockito.junit4.bugs.github731; public class AType { } ================================================ FILE: tests/mockito/junit4/src/main/java/samples/powermockito/junit4/bugs/github731/OptionalInterface.java ================================================ package samples.powermockito.junit4.bugs.github731; public interface OptionalInterface { } ================================================ FILE: tests/mockito/junit4/src/main/java/samples/powermockito/junit4/bugs/github731/SomeInterface.java ================================================ package samples.powermockito.junit4.bugs.github731; public interface SomeInterface { T get(); } ================================================ FILE: tests/mockito/junit4/src/main/java/samples/powermockito/junit4/bugs/github801/GlobalPowerMockIgnore.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package samples.powermockito.junit4.bugs.github801; public class GlobalPowerMockIgnore { } ================================================ FILE: tests/mockito/junit4/src/main/java/samples/powermockito/junit4/bugs/github806/CustomException.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package samples.powermockito.junit4.bugs.github806; public class CustomException extends Exception { } ================================================ FILE: tests/mockito/junit4/src/main/java/samples/powermockito/junit4/bugs/github806/DoThrowTMockClass.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package samples.powermockito.junit4.bugs.github806; public class DoThrowTMockClass { public void doSomething() { } public void throwExceptionForInput(String foo) throws CustomException { if ("123".equals(foo)) { throw new CustomException(); } } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/FinalEqualsClass.java ================================================ package samples.powermockito.junit4; /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Just a testclass with a final-equals method. */ public class FinalEqualsClass { @Override public final boolean equals(Object obj) { return super.equals(obj); } public final String foo() { return "foo"; } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/FinalEqualsClassTest.java ================================================ package samples.powermockito.junit4; import static org.junit.Assert.*; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor; import org.powermock.modules.junit4.PowerMockRunner; /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @RunWith(value = PowerMockRunner.class) @PrepareForTest({FinalEqualsClass.class}) @SuppressStaticInitializationFor({"samples.powermockito.junit4.FinalClass"}) public class FinalEqualsClassTest { @Test public void callingEqualsDoesntCauseStackOverflow() throws Exception { FinalEqualsClass fc = new FinalEqualsClass(); fc.foo(); FinalEqualsClass mock = PowerMockito.mock(FinalEqualsClass.class); FinalEqualsClass mock2 = PowerMockito.mock(FinalEqualsClass.class); PowerMockito.when(mock.foo()).thenReturn("bar"); fc = PowerMockito.spy(fc); PowerMockito.when(fc.foo()).thenReturn("bar"); fc.equals(mock); assertEquals("bar", mock.foo()); assertEquals("bar", fc.foo()); assertEquals(mock, mock); assertFalse(mock.equals(mock2)); } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/abstractmocking/AbstractMethodMockingTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.abstractmocking; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.abstractmocking.AbstractMethodMocking; import static org.junit.Assert.*; import static org.powermock.api.mockito.PowerMockito.*; @RunWith(PowerMockRunner.class) @PrepareForTest( { AbstractMethodMocking.class }) public class AbstractMethodMockingTest { @Test public void mocksAbstractClasses() throws Exception { assertNotNull(mock(AbstractMethodMocking.class)); } @Test public void canSpyOnAnonymousClasses() throws Exception { AbstractMethodMocking tested = new AbstractMethodMocking() { @Override protected String getIt() { return null; } }; assertNull(tested.getValue()); AbstractMethodMocking spy = spy(tested); when(spy.getValue()).thenReturn("something"); assertEquals("something", spy.getValue()); } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/annotationbased/CaptorAnnotationTest.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.annotationbased; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.finalmocking.FinalDemo; import samples.privateandfinal.PrivateFinal; import samples.privateandfinal.PrivateFinalOverload; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.verify; import static org.powermock.api.mockito.PowerMockito.*; /** * Asserts that {@link Captor} with PowerMock. */ @RunWith(PowerMockRunner.class) @PrepareForTest({FinalDemo.class, PrivateFinal.class, PrivateFinalOverload.class}) public class CaptorAnnotationTest { @Captor private ArgumentCaptor captor; @Test public void captorAnnotationWorks() throws Exception { final String expected = "testing"; FinalDemo demo = mock(FinalDemo.class); demo.say(expected); verify(demo).say(captor.capture()); assertEquals(expected, captor.getValue()); } @Test public void captorAnnotationWorksOnPrivateMethods() throws Exception { final String expected = "testing"; PrivateFinal demo = spy(new PrivateFinal()); demo.say(expected); verifyPrivate(demo).invoke("sayIt", captor.capture()); assertEquals(expected, captor.getValue()); } @Test public void captorAnnotationWorksOnPrivateOverriddenMethods() throws Exception { final String expected = "testing"; PrivateFinalOverload demo = spy(new PrivateFinalOverload()); demo.say(expected); verifyPrivate(demo).invoke(method(PrivateFinalOverload.class, "say", String.class, String.class)).withArguments(anyString(), captor.capture()); assertEquals(expected, captor.getValue()); } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/annotationbased/ChunkingAndStaticInitializerRemovalTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.annotationbased; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.reflect.Whitebox; import samples.staticinitializer.SimpleStaticInitializerExample; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.mockito.Mockito.verify; /** * Test class to demonstrate non-static final mocking with Mockito and PowerMock * annotations. */ @RunWith(PowerMockRunner.class) @PrepareForTest(SimpleStaticInitializerExample.class) public class ChunkingAndStaticInitializerRemovalTest { @Mock private SimpleStaticInitializerExample tested; @Test public void testMockingWithNoChunking() throws Exception { final String argument = "hello"; final String string = tested.getString(); assertEquals(Whitebox.getInternalState(SimpleStaticInitializerExample.class, String.class), string); assertNull(tested.getConcatenatedString(argument)); verify(tested).getConcatenatedString(argument); } @SuppressStaticInitializationFor("samples.staticinitializer.SimpleStaticInitializerExample") @Test public void testMockingWithChunking() throws Exception { final String argument = "hello"; assertNull(tested.getString()); assertNull(tested.getConcatenatedString(argument)); verify(tested).getConcatenatedString(argument); } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/annotationbased/InjectMocksAnnotationTest.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.annotationbased; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.finalmocking.FinalDemo; import samples.injectmocks.DependencyHolder; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * Asserts that {@link @InjectMocks} with PowerMock. */ @RunWith(PowerMockRunner.class) @PrepareForTest(FinalDemo.class) public class InjectMocksAnnotationTest { @SuppressWarnings("unused") @Mock private FinalDemo finalDemo; @InjectMocks private DependencyHolder dependencyHolder = new DependencyHolder(); @Test public void injectMocksWorks() { assertNotNull(dependencyHolder.getFinalDemo()); } @Test public void testSay() throws Exception { FinalDemo tested = dependencyHolder.getFinalDemo(); String expected = "Hello altered World"; when(tested.say("hello")).thenReturn("Hello altered World"); String actual = tested.say("hello"); assertEquals("Expected and actual did not match", expected, actual); // Should still be mocked by now. try { verify(tested).say("world"); fail("Should throw AssertionError!"); } catch (AssertionError e) { assertThat(e.getMessage(), is(containsString("Argument(s) are different! Wanted"))); } } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/annotationbased/MockFinalUsingAnnotationsTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.annotationbased; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.finalmocking.FinalDemo; import static org.junit.Assert.assertNull; import static org.mockito.Mockito.verify; /** * Test class to demonstrate non-static final mocking with Mockito and PowerMock * annotations. */ @RunWith(PowerMockRunner.class) @PrepareForTest(FinalDemo.class) public class MockFinalUsingAnnotationsTest { @Mock private FinalDemo usingMockitoMockAnnotation; @SuppressWarnings("deprecation") @org.mockito.Mock private FinalDemo usingDeprecatedMockitoMockAnnotation; @Test public void assertMockFinalWithMockitoMockAnnotationWorks() throws Exception { final String argument = "hello"; assertNull(usingMockitoMockAnnotation.say(argument)); verify(usingMockitoMockAnnotation).say(argument); } @Test public void assertMockFinalWithDeprecatedMockitoMockAnnotationWorks() throws Exception { final String argument = "hello"; assertNull(usingDeprecatedMockitoMockAnnotation.say(argument)); verify(usingDeprecatedMockitoMockAnnotation).say(argument); } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/annotationbased/MockFinalUsingAnnotationsWithAnswersTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.annotationbased; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Answers; import org.mockito.Mock; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.finalmocking.FinalDemo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.powermock.api.mockito.PowerMockito.when; /** * Test class to demonstrate non-static final mocking with Mockito and PowerMock * annotations using answers. */ @RunWith(PowerMockRunner.class) @PrepareForTest(FinalDemo.class) public class MockFinalUsingAnnotationsWithAnswersTest { @Mock(answer = Answers.RETURNS_DEEP_STUBS) private FinalDemo tested1; @Mock(answer = Answers.RETURNS_MOCKS) private FinalDemo tested2; @Mock(answer = Answers.RETURNS_MOCKS, name = "myTested3") private FinalDemo tested3; @Test public void assert_mock_final_with_mockito_mock_annotation_with_deep_stubs_works() { when(tested1.simpleReturnExample().mySimpleMethod()).thenReturn(42); assertEquals(42, tested1.simpleReturnExample().mySimpleMethod()); } @Test public void assert_mock_final_with_mockito_mock_annotation_with_returns_mocks_works() { assertNotNull(tested2.simpleReturnExample()); } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/annotationbased/SpyAnnotationTest.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.annotationbased; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Spy; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.partialmocking.PrivatePartialMockingExample; import static org.junit.Assert.assertEquals; import static org.powermock.api.mockito.PowerMockito.verifyPrivate; import static org.powermock.api.mockito.PowerMockito.when; /** * Asserts that spying on private methods work with PowerMock when using * {@link Spy} annotation. */ @RunWith(PowerMockRunner.class) @PrepareForTest(PrivatePartialMockingExample.class) public class SpyAnnotationTest { @Spy private PrivatePartialMockingExample underTest = new PrivatePartialMockingExample(); @Test public void spyingOnPrivateMethodsWorksWithSpyAnnotation() throws Exception { final String expected = "TEST VALUE"; final String nameOfMethodToMock = "methodToMock"; final String input = "input"; when(underTest, nameOfMethodToMock, input).thenReturn(expected); assertEquals(expected, underTest.methodToTest()); verifyPrivate(underTest).invoke(nameOfMethodToMock, input); } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/argumentmatcher/ArgumentMatcherTest.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.argumentmatcher; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.modules.junit4.PowerMockRunner; import samples.argumentmatcher.ArgumentMatcherDemo; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.ArgumentMatchers.eq; import static org.powermock.api.mockito.PowerMockito.doReturn; import static org.powermock.api.mockito.PowerMockito.mock; @RunWith(PowerMockRunner.class) public class ArgumentMatcherTest { @Test public void worksWithArgumentMatchers() throws Exception { final ArrayList strings = new ArrayList(); final ArgumentMatcherDemo tested = mock(ArgumentMatcherDemo.class); doReturn(strings).when(tested, "findByNamedQuery", eq("AbstractPTVTicket.ticketSeatIds"), anyList()); final List stringList = tested.findByNamedQuery("something", strings); assertTrue(stringList.isEmpty()); } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/ClassLoaderBugTest.java ================================================ /* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.bugs; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.io.IOException; import java.net.URL; import java.util.Enumeration; import static org.junit.Assert.assertEquals; @RunWith(PowerMockRunner.class) @PrepareForTest(TestClass.class) public class ClassLoaderBugTest { /** * See issue 426 for more details. */ @Test(timeout = 2000) public void resourcesAreNotLoadedTwice() throws IOException { String resourceName = getClass().getCanonicalName().replace(".", "/") + ".class"; Enumeration enumeration = getClass().getClassLoader().getResources(resourceName); int count = 0; while (enumeration.hasMoreElements()) { System.out.println(enumeration.nextElement().toString()); count++; } assertEquals(1, count); } } class TestClass { } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github510/package-info.java ================================================ /** * https://github.com/jayway/powermock/issues/510 */ package samples.powermockito.junit4.bugs.github510; ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github583/ChildClass.java ================================================ package samples.powermockito.junit4.bugs.github583; /** * */ public class ChildClass extends ParenClass { private int b; public ChildClass() { super(); } public int getB() { return b; } public void setB(int b) { this.b = b; } public void test(){ } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github583/ClassWithInheritanceTest.java ================================================ package samples.powermockito.junit4.bugs.github583; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Spy; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; /** * */ @RunWith(PowerMockRunner.class) @PrepareForTest(value = {ChildClass.class}) public class ClassWithInheritanceTest { @Spy ChildClass b = new ChildClass(); @Test public void test_test(){ b.test(); } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github583/ParenClass.java ================================================ package samples.powermockito.junit4.bugs.github583; /** * */ public class ParenClass { private int a; public int getA() { return a; } public void setA(int a) { this.a = a; } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github583/package-info.java ================================================ /** * https://github.com/jayway/powermock/issues/583 */ package samples.powermockito.junit4.bugs.github583; ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github668/GitHub668Test.java ================================================ package samples.powermockito.junit4.bugs.github668; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import javax.security.auth.Subject; import java.util.HashSet; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.powermock.api.mockito.PowerMockito.mock; import static org.powermock.api.mockito.PowerMockito.when; @RunWith(PowerMockRunner.class) @PrepareForTest(Subject.class) public class GitHub668Test { @Test public void shouldMockJavaxSystemFinalClasses() { Subject subject = mock(Subject.class); final HashSet value = new HashSet(); when(subject.getPrivateCredentials()).thenReturn(value); assertThat(subject.getPrivateCredentials()).isSameAs(value); } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github668/package-info.java ================================================ /** * https://github.com/jayway/powermock/issues/688 */ package samples.powermockito.junit4.bugs.github668; ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github701/GitHub701Test.java ================================================ package samples.powermockito.junit4.bugs.github701; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.powermock.api.mockito.PowerMockito.doReturn; import static org.powermock.api.mockito.PowerMockito.mock; @RunWith(PowerMockRunner.class) @PrepareForTest({MapWrapper.class}) public class GitHub701Test { private MapWrapper mocked; @Before public void setUp() throws Exception { mocked = mock(MapWrapper.class); } @Test public void shouldMockObjectAndReturnRequiredResult() throws Exception { doReturn("1234").when(mocked).get("numbers"); assertThat(mocked.get("numbers")).isEqualTo("1234"); } @Test public void shouldMockEqualsMethod() { assertThat(mocked.equals(mocked)).isEqualTo(true); } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github701/MapWrapper.java ================================================ package samples.powermockito.junit4.bugs.github701; import java.io.Serializable; import java.util.Collections; import java.util.Map; public final class MapWrapper extends OverridesEquals { private final Map data; public MapWrapper() { this(Collections.emptyMap()); } MapWrapper(final Map data) { this.data = Collections.unmodifiableMap(data); } public Object get(final String key) { if (key == null || key.isEmpty()) { return null; } return data.get(key); } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github701/OverridesEquals.java ================================================ package samples.powermockito.junit4.bugs.github701; abstract class OverridesEquals { @Override public boolean equals (final Object other) { return this == other; } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github701/package-info.java ================================================ /** * StackOverflowError mocking final class extending non-public abstract class * overriding equals method * https://github.com/jayway/powermock/issues/701 */ package samples.powermockito.junit4.bugs.github701; ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github704/PrepareForTestSignedTest.java ================================================ package samples.powermockito.junit4.bugs.github704; import org.eclipse.core.runtime.FileLocator; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.powermock.api.mockito.PowerMockito.mock; import static org.powermock.api.mockito.PowerMockito.mockStatic; import static org.powermock.api.mockito.PowerMockito.when; @RunWith(PowerMockRunner.class) @PrepareForTest({SomeClassUseSignedClasses.class, FileLocator.class}) public class PrepareForTestSignedTest { @Test public void shouldBeAbleMockSignedClasses(){ FileLocator fileLocator = mock(FileLocator.class); mockStatic(SomeClassUseSignedClasses.class); when(SomeClassUseSignedClasses.getFileLocator()).thenReturn(fileLocator); assertThat(SomeClassUseSignedClasses.getFileLocator()).isNotNull(); } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github704/SomeClassUseSignedClasses.java ================================================ package samples.powermockito.junit4.bugs.github704; import org.eclipse.core.runtime.FileLocator; public class SomeClassUseSignedClasses { public static FileLocator getFileLocator(){ return null; } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github704/package-info.java ================================================ /** * PowerMockito 1.6.5 throws java.lang.SecurityException signer information mismatch if in the PrepareForTest annotation affects also classes which have signatures * https://github.com/jayway/powermock/issues/704 */ package samples.powermockito.junit4.bugs.github704; ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github716/A.java ================================================ package samples.powermockito.junit4.bugs.github716; public class A { } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github716/B.java ================================================ package samples.powermockito.junit4.bugs.github716; public class B { } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github716/C.java ================================================ package samples.powermockito.junit4.bugs.github716; public class C { A a; B b; public C(A a, B b) { this.a = a; this.b = b; } public int multiply() { return 42; } public A getA() { return a; } public B getB() { return b; } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github716/MyService.java ================================================ package samples.powermockito.junit4.bugs.github716; public class MyService { public int doSomething(A a, B b) { C c = new C(a, b); return c.multiply(); } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github716/WhenNewWithAnyArgumentsTest.java ================================================ package samples.powermockito.junit4.bugs.github716; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; import static org.powermock.api.mockito.PowerMockito.when; import static org.powermock.api.mockito.PowerMockito.whenNew; @PrepareForTest({MyService.class}) @RunWith(PowerMockRunner.class) public class WhenNewWithAnyArgumentsTest { @Mock private C c; @InjectMocks private MyService cut; @Test public void shouldStubNewConstructorCallIfOneOfActualParameterIsNull() throws Exception { A a = new A(); whenNew(C.class).withAnyArguments().thenReturn(c); when(c.multiply()).thenReturn(42); int result = cut.doSomething(a, null); assertThat(result, is(42)); } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github716/package-info.java ================================================ /** * Powermockito: withAnyArguments * when moving from version 1.6.5 to 1.6.6 all tests fail which are using the withAnyArguments inside * of "whenNew". Proxy objects aren't created any more and stay null which results in NullPointerException * https://github.com/jayway/powermock/issues/716 */ package samples.powermockito.junit4.bugs.github716; ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github731/MockingInterfacesTest.java ================================================ package samples.powermockito.junit4.bugs.github731; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.modules.junit4.PowerMockRunner; import java.util.concurrent.ExecutionException; import static org.powermock.api.mockito.PowerMockito.mock; import static org.powermock.api.mockito.PowerMockito.when; @RunWith(PowerMockRunner.class) public class MockingInterfacesTest { @Test public void should_stub_future_get_method() throws ExecutionException, InterruptedException { SomeInterface> mockFuture = mock(SomeInterface.class); OptionalInterface mockTypeOpt = mock(OptionalInterface.class); when(mockFuture.get()).thenReturn(mockTypeOpt); } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github731/SomeException.java ================================================ package samples.powermockito.junit4.bugs.github731; public class SomeException extends Exception{ } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github781/EqualsStatic.java ================================================ package samples.powermockito.junit4.bugs.github781; public class EqualsStatic { public static boolean equals() { return false; } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github781/GitHub781Test.java ================================================ package samples.powermockito.junit4.bugs.github781; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.mockito.Mockito.spy; @RunWith(PowerMockRunner.class) @PrepareForTest(EqualsStatic.class) public class GitHub781Test { private SpyObject partialMock = null; private final boolean result = true; @Test public void testCallMockStaticEquals() { PowerMockito.mockStatic(EqualsStatic.class); PowerMockito.when(EqualsStatic.equals()).thenReturn(result); partialMock = spy(new SpyObject()); assertThat(partialMock.callEquals()).isEqualTo(result); } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github781/SpyObject.java ================================================ package samples.powermockito.junit4.bugs.github781; public class SpyObject { public boolean callEquals() { return EqualsStatic.equals(); } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github801/GlobalPowerMockIgnoreTest.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package samples.powermockito.junit4.bugs.github801; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.modules.junit4.PowerMockRunner; import static org.assertj.core.api.Java6Assertions.assertThat; @RunWith(PowerMockRunner.class) public class GlobalPowerMockIgnoreTest { @Test public void should_load_class_from_global_ignore_with_system_class_loader() { GlobalPowerMockIgnore globalPowerMockIgnore = new GlobalPowerMockIgnore(); assertThat(globalPowerMockIgnore.getClass().getClassLoader()) .as("Class is loaded by System Classloader") .isSameAs(ClassLoader.getSystemClassLoader()); } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github806/DoThrowTest.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package samples.powermockito.junit4.bugs.github806; import org.junit.Test; import org.mockito.Mockito; import static org.mockito.Mockito.doThrow; public class DoThrowTest { @Test(expected = RuntimeException.class) public void should_throw_expected_exception() { final DoThrowTMockClass mock = Mockito.mock(DoThrowTMockClass.class); doThrow(RuntimeException.class).when(mock).doSomething(); mock.doSomething(); } @Test(expected = CustomException.class) public void should_throw_custom_exception() throws CustomException { new DoThrowTMockClass().throwExceptionForInput("123"); } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github806/package-info.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * Exception verification in junit tests #806 *

* * @Test(expected = NotFoundException.class) * public void a() { * doThrow(NotFoundException.class).when(b).doSomething(); * b.doSomething(); * } * * Test failure, throws RuntimeExceptionProxy instead of NotFoundException *

* https://github.com/powermock/powermock/issues/806 */ package samples.powermockito.junit4.bugs.github806; ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/constructor/InnerConstructorsAreFoundTest.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.constructor; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import static org.powermock.api.mockito.PowerMockito.whenNew; /** * Asserts that issue 267 * is resolved. */ @PrepareForTest({ InnerConstructorsAreFoundTest.WorkingObjectUnderTesting.class, InnerConstructorsAreFoundTest.BuggyObjectUnderTesting.class, InnerConstructorsAreFoundTest.StillBuggyObjectUnderTesting.class }) @RunWith(PowerMockRunner.class) public class InnerConstructorsAreFoundTest { interface AnyInterface { }; class AnyImplementation implements AnyInterface { @Override public boolean equals(Object obj) { return true; } } class SomeOtherImplementationOfSomethingElse { @Override public boolean equals(Object obj) { return true; } }; // class WorkingObjectUnderTesting { void methodToTest() { new WorkingObjectToMock(new AnyImplementation()); } } class BuggyObjectUnderTesting { void methodToTest() { new BuggyObjectToMock(new SomeOtherImplementationOfSomethingElse(), new AnyImplementation()); } } class StillBuggyObjectUnderTesting { void methodToTest() { new StillBuggyObjectToMock(new SomeOtherImplementationOfSomethingElse(), new AnyInterface[] { new AnyImplementation() }); } } // // class WorkingObjectToMock { public WorkingObjectToMock(AnyInterface... anys) { } } class BuggyObjectToMock { @SuppressWarnings("unused") private final AnyInterface[] anys; public BuggyObjectToMock(SomeOtherImplementationOfSomethingElse other, AnyInterface... anys) { this.anys = anys; } } class StillBuggyObjectToMock { @SuppressWarnings("unused") private final AnyInterface[] anys; public StillBuggyObjectToMock(SomeOtherImplementationOfSomethingElse other, AnyInterface[] anys) { this.anys = anys; } } @Mock WorkingObjectToMock mockedWorkingObject; @Mock BuggyObjectToMock mockedBuggyObject; @Mock StillBuggyObjectToMock mockedStillBuggyObject; @Test public void shouldFindMemberVarArgsCtorWhenPassingArrayToWithArguments() throws Exception { whenNew(BuggyObjectToMock.class).withArguments(new SomeOtherImplementationOfSomethingElse(), (Object[]) new AnyInterface[] { new AnyImplementation() }).thenReturn(mockedBuggyObject); new BuggyObjectUnderTesting().methodToTest(); } @Test public void shouldFindMemberArrayCtorWhenPassingArrayToWithArguments() throws Exception { whenNew(StillBuggyObjectToMock.class).withArguments(new SomeOtherImplementationOfSomethingElse(), (Object) new AnyInterface[] { new AnyImplementation() }).thenReturn(mockedStillBuggyObject); new StillBuggyObjectUnderTesting().methodToTest(); } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/doreturn/DoReturnTest.java ================================================ package samples.powermockito.junit4.doreturn; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.powermock.modules.junit4.PowerMockRunner; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsEqual.equalTo; import static org.powermock.api.mockito.PowerMockito.doReturn; /** * Created by gauee on 12/11/15. * Test that demonstrates that issue 599 * is resolved. */ @RunWith(PowerMockRunner.class) public class DoReturnTest { private static final String TEMP_DAY_FIRST = "41F"; private static final String TEMP_DAY_SECOND = "44F"; @Mock private Weather weather; interface Weather { String getTemperature(); } @Before public void init() { doReturn(TEMP_DAY_FIRST, TEMP_DAY_SECOND).when(weather).getTemperature(); } @Test public void returnsDifferentTemperatureForEachInvocation(){ assertThat(weather.getTemperature(), is(equalTo(TEMP_DAY_FIRST))); assertThat(weather.getTemperature(), is(equalTo(TEMP_DAY_SECOND))); } @Test public void returnsFirstTemperatureWhenPassedArrayIsEmpty() { doReturn(TEMP_DAY_FIRST, new Object[0]).when(weather).getTemperature(); assertThat(weather.getTemperature(), is(equalTo(TEMP_DAY_FIRST))); assertThat(weather.getTemperature(), is(equalTo(TEMP_DAY_FIRST))); } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/enums/EnumWithConstructorTest.java ================================================ package samples.powermockito.junit4.enums; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.enummocking.EnumWithConstructor; import samples.enummocking.SomeObjectInterfaceImpl; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.sameInstance; import static org.junit.Assert.assertThat; import static org.powermock.api.mockito.PowerMockito.whenNew; /** * */ @RunWith(PowerMockRunner.class) @PrepareForTest(value = {EnumWithConstructor.class, SomeObjectInterfaceImpl.class}, fullyQualifiedNames = "samples.enummocking.EnumWithConstructor$1") public class EnumWithConstructorTest { @Mock(name = "expectedSomeObjectInterfaceImpl") private SomeObjectInterfaceImpl someImplMock; @Test public void testCallMethodWithConstructor() throws Exception { whenNew(SomeObjectInterfaceImpl.class).withNoArguments().thenReturn(someImplMock); SomeObjectInterfaceImpl actual = (SomeObjectInterfaceImpl) EnumWithConstructor.SOME_ENUM_VALUE.create(); assertThat(actual, is(sameInstance(someImplMock))); } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/equalsmocking/EqualsMockingTest.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.equalsmocking; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import javax.naming.InitialContext; import static org.junit.Assert.assertTrue; import static org.powermock.api.mockito.PowerMockito.mock; import static org.powermock.api.mockito.PowerMockito.when; import static org.powermock.api.support.membermodification.MemberMatcher.method; import static org.powermock.api.support.membermodification.MemberModifier.stub; @RunWith(PowerMockRunner.class) @PrepareForTest(InitialContext.class) public class EqualsMockingTest { @Test public void shouldStubEquals() throws Exception { stub(method(InitialContext.class, "equals")).toReturn(true); final InitialContext context = new InitialContext(); assertTrue(context.equals(new Object())); } @Test public void shouldMockEquals() throws Exception { Object object = new Object(); final InitialContext context = mock(InitialContext.class); when(context.equals(object)).thenReturn(true); assertTrue(context.equals(object)); } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/finalmocking/MockFinalMethodsCases.java ================================================ package samples.powermockito.junit4.finalmocking; import org.junit.Test; import samples.finalmocking.FinalDemo; import samples.privateandfinal.PrivateFinal; import java.lang.reflect.Method; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.powermock.api.mockito.PowerMockito.doThrow; import static org.powermock.api.mockito.PowerMockito.mock; import static org.powermock.api.mockito.PowerMockito.spy; import static org.powermock.api.mockito.PowerMockito.verifyPrivate; import static org.powermock.api.mockito.PowerMockito.when; import static org.powermock.api.support.membermodification.MemberMatcher.method; /** * Cases to check mocking final non-static methods and final class */ public class MockFinalMethodsCases { @Test public void shouldMockFinalMethodWithNoExpectations() throws Exception { final String argument = "hello"; FinalDemo tested = mock(FinalDemo.class); assertThat(tested.say(argument)).isNull(); verify(tested).say(argument); } @Test public void shouldMockFinalMethodWithExpectations() throws Exception { final String argument = "hello"; final String expected = "Hello altered World"; FinalDemo tested = mock(FinalDemo.class); when(tested.say(argument)).thenReturn(expected); final String actual = tested.say(argument); verify(tested).say(argument); assertThat(actual).isEqualTo(expected); } @Test public void shouldMockFinalNativeMethodWithExpectations() throws Exception { final String expected = "Hello altered World"; final String argument = "hello"; FinalDemo tested = mock(FinalDemo.class); when(tested.sayFinalNative(argument)).thenReturn("Hello altered World"); String actual = tested.sayFinalNative(argument); verify(tested).sayFinalNative(argument); assertThat(actual).isEqualTo(expected); } @Test public void shouldSpyingOnFinalInstanceMethod() throws Exception { FinalDemo tested = new FinalDemo(); FinalDemo spy = spy(tested); final String argument = "PowerMock"; final String expected = "something"; assertThat(spy.say(argument)).isEqualTo("Hello " + argument); when(spy.say(argument)).thenReturn(expected); assertThat(spy.say(argument)).isEqualTo(expected); } @Test(expected = ArrayStoreException.class) public void shouldSpyingOnFinalVoidInstanceMethod() throws Exception { FinalDemo tested = new FinalDemo(); FinalDemo spy = spy(tested); doThrow(new ArrayStoreException()).when(spy).finalVoidCallee(); spy.finalVoidCaller(); } @Test public void shouldSpyingOnPrivateFinalInstanceMethod() throws Exception { PrivateFinal spy = spy(new PrivateFinal()); final String expected = "test"; assertThat(spy.say(expected)).isEqualTo("Hello " + expected); when(spy, "sayIt", isA(String.class)).thenReturn(expected); assertThat(spy.say(expected)).isEqualTo(expected); verifyPrivate(spy, times(2)).invoke("sayIt", expected); } @Test public void shouldSpyingOnPrivateFinalInstanceMethodWhenUsingJavaLangReflectMethod() throws Exception { PrivateFinal spy = spy(new PrivateFinal()); final String expected = "test"; assertThat(spy.say(expected)).isEqualTo("Hello " + expected); final Method methodToExpect = method(PrivateFinal.class, "sayIt"); when(spy, methodToExpect).withArguments(isA(String.class)).thenReturn(expected); assertThat(spy.say(expected)).isEqualTo(expected); verifyPrivate(spy, times(2)).invoke(methodToExpect).withArguments(expected); } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/finalmocking/MockFinalNonStaticMethodsTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.finalmocking; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.finalmocking.FinalDemo; import samples.privateandfinal.PrivateFinal; /** * Test class to demonstrate non-static final mocking with Mockito. */ @RunWith(PowerMockRunner.class) @PrepareForTest({FinalDemo.class, PrivateFinal.class}) public class MockFinalNonStaticMethodsTest extends MockFinalMethodsCases { } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/getannotation/GetAnnotationTest.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.getannotation; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.MockGateway; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.annotationbased.AnnotatedClassDemo; import samples.annotationbased.testannotations.RuntimeAnnotation; import static org.junit.Assert.*; import static org.powermock.api.mockito.PowerMockito.*; /** * Assert that "isAnnotationPresent" and "getAnnotation" works correctly when mockStatic is used * @see Issue 676 */ @RunWith(PowerMockRunner.class) @PrepareForTest(AnnotatedClassDemo.class) public class GetAnnotationTest { @Before public void setUp() { mockStatic(AnnotatedClassDemo.class); when(AnnotatedClassDemo.staticMethod()).thenReturn(true); } @Test public void getClassAnnotationsReturnActualAnnotationsByDefault() throws Exception { assertTrue(AnnotatedClassDemo.class.isAnnotationPresent(RuntimeAnnotation.class)); assertNotNull(AnnotatedClassDemo.class.getAnnotation(RuntimeAnnotation.class)); assertTrue(AnnotatedClassDemo.staticMethod()); } @Test public void nonExistingAnnotationsAreNotReturnedByDefault() throws Exception { assertFalse(AnnotatedClassDemo.class.isAnnotationPresent(Deprecated.class)); assertNull(AnnotatedClassDemo.class.getAnnotation(Deprecated.class)); assertTrue(AnnotatedClassDemo.staticMethod()); } // behavior before the fix: @Test public void isAnnotationPresentReturnsFalseWhenMethodsAreMocked() throws Exception { MockGateway.MOCK_ANNOTATION_METHODS = true; try { assertFalse(AnnotatedClassDemo.class.isAnnotationPresent(RuntimeAnnotation.class)); assertTrue(AnnotatedClassDemo.staticMethod()); } finally { MockGateway.MOCK_ANNOTATION_METHODS = false; } } @Test public void getAnnotationReturnsNullWhenMethodsAreMocked() throws Exception { MockGateway.MOCK_ANNOTATION_METHODS = true; try { assertNull(AnnotatedClassDemo.class.getAnnotation(RuntimeAnnotation.class)); assertTrue(AnnotatedClassDemo.staticMethod()); } finally { MockGateway.MOCK_ANNOTATION_METHODS = false; } } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/getclass/GetClassTest.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.getclass; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.MockGateway; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.expectnew.ExpectNewDemo; import static org.junit.Assert.*; import static org.powermock.api.mockito.PowerMockito.mock; /** * Assert that "getClass" on an object works correctly on objects */ @RunWith(PowerMockRunner.class) @PrepareForTest(ExpectNewDemo.class) public class GetClassTest { @Test public void getClassReturnsTheCorrectClassForNewInstancesOfClassesPrepareForTest() throws Exception { ExpectNewDemo instance = new ExpectNewDemo(); assertEquals(ExpectNewDemo.class, instance.getClass()); } @Test public void getClassReturnsTheCorrectClassForMocksPrepareForTest() throws Exception { ExpectNewDemo instance = mock(ExpectNewDemo.class); assertNotNull(instance.getClass()); } @Test public void getClassReturnsNullForMocksPreparedForTestWhenMockingOfGetClassAllowed() throws Exception { MockGateway.MOCK_GET_CLASS_METHOD = true; ExpectNewDemo instance = mock(ExpectNewDemo.class); try { assertNull(instance.getClass()); } finally { // Make sure we reset to the default for subsequent tests. MockGateway.MOCK_GET_CLASS_METHOD = false; } } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/hashcode/HashCodeTest.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.hashcode; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import javax.naming.InitialContext; import static org.junit.Assert.assertEquals; import static org.powermock.api.mockito.PowerMockito.mock; import static org.powermock.api.mockito.PowerMockito.when; import static org.powermock.api.support.membermodification.MemberMatcher.method; import static org.powermock.api.support.membermodification.MemberModifier.stub; @RunWith(PowerMockRunner.class) @PrepareForTest(InitialContext.class) public class HashCodeTest { private final static int EXPECTED_HASH = 12316; @Test public void shouldStubHashCode() throws Exception { stub(method(InitialContext.class, "hashCode")).toReturn(EXPECTED_HASH); final InitialContext context = new InitialContext(); assertEquals(EXPECTED_HASH, context.hashCode()); } @Test public void shouldMockHashCode() throws Exception { InitialContext context = mock(InitialContext.class); when(context.hashCode()).thenReturn(EXPECTED_HASH); assertEquals(EXPECTED_HASH, context.hashCode()); } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/hashcode/InnerClassHashCodeTest.java ================================================ /* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.hashcode; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.util.HashMap; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; import static org.powermock.api.mockito.PowerMockito.mock; import static org.powermock.api.mockito.PowerMockito.when; import static org.powermock.api.support.membermodification.MemberMatcher.method; import static org.powermock.api.support.membermodification.MemberModifier.stub; @RunWith(PowerMockRunner.class) @PrepareForTest({InnerClassHashCodeTest.SubHashMap.class}) public class InnerClassHashCodeTest { private static final int EXPECTED_HASH = 123456; @Test @Ignore("This should work but it's a bug") public void can_mock_inner_hash_code_method() { SubHashMap actor = mock(SubHashMap.class); when(actor.hashCode()).thenReturn(EXPECTED_HASH); int hashCode = actor.hashCode(); assertThat(hashCode, equalTo(EXPECTED_HASH)); } @Test public void can_stub_inner_hash_code_method() { stub(method(SubHashMap.class, "hashCode")).toReturn(EXPECTED_HASH); SubHashMap actor = new SubHashMap(); int hashCode = actor.hashCode(); assertThat(hashCode, equalTo(123456)); } public class SubHashMap extends HashMap { @Override public int hashCode() { return super.hashCode(); } @Override public boolean equals(Object o) { return super.equals(o); } } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/jacoco/InstanceMethods.java ================================================ package samples.powermockito.junit4.jacoco; import java.util.Random; public final class InstanceMethods { private static final Random random = new Random(); public int calculateSomething(int in){ int r = in; for (int i = 0; i < max(); i++) { r += in * i % getSomeFactor(); } return r; } private int getSomeFactor() { return random.nextInt(2); } private int max() { return random.nextInt(100); } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/jacoco/JacocoCoverageTest.java ================================================ package samples.powermockito.junit4.jacoco; import org.jacoco.core.analysis.Analyzer; import org.jacoco.core.analysis.CoverageBuilder; import org.jacoco.core.analysis.IClassCoverage; import org.jacoco.core.analysis.IMethodCoverage; import org.jacoco.core.data.ExecutionDataStore; import org.jacoco.core.data.SessionInfoStore; import org.jacoco.core.instr.Instrumenter; import org.jacoco.core.runtime.IRuntime; import org.jacoco.core.runtime.LoggerRuntime; import org.jacoco.core.runtime.RuntimeData; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.JUnitCore; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URISyntaxException; import java.net.URL; import static org.assertj.core.api.Java6Assertions.assertThat; public class JacocoCoverageTest { public static final String[] TARGET = new String[]{ TargetTest.class.getName(), StaticMethods.class.getName(), InstanceMethods.class.getName() }; @Test public void jacocoOfflineInstShouldCalculateCoverageAfterPowerMockTransformation() throws Exception { final RuntimeData data = new RuntimeData(); runTargetTest(data); final CoverageBuilder coverageBuilder = collectCoverage(getExecutionDataStore(data)); assertCodeCoverage(coverageBuilder); } private void runTargetTest(RuntimeData data) throws Exception {IRuntime runtime = new LoggerRuntime(); instrumentClasses(runtime); runtime.startup(data); JUnitCore.runClasses(TargetTest.class); runtime.shutdown(); restoreOriginalClasses(); } private void assertCodeCoverage(CoverageBuilder coverageBuilder) { for (IClassCoverage classCoverage : coverageBuilder.getClasses()) { for (IMethodCoverage methodCoverage : classCoverage.getMethods()) { if (methodCoverage.getName().equals("calculateSomething")) { assertThat(methodCoverage.getLineCounter().getCoveredRatio()).isEqualTo(1.0); assertThat(methodCoverage.getLineCounter().getCoveredCount()).isEqualTo(4); } } } } private CoverageBuilder collectCoverage(ExecutionDataStore executionData) throws IOException { final CoverageBuilder coverageBuilder = new CoverageBuilder(); final Analyzer analyzer = new Analyzer(executionData, coverageBuilder); for (String className : TARGET) { analyzer.analyzeClass(getClass().getResourceAsStream(classNameToFileName(className)), className); } return coverageBuilder; } private ExecutionDataStore getExecutionDataStore(RuntimeData data) { final ExecutionDataStore executionData = new ExecutionDataStore(); final SessionInfoStore sessionInfos = new SessionInfoStore(); data.collect(executionData, sessionInfos, false); return executionData; } private void restoreOriginalClasses() throws URISyntaxException, IOException { for (String className : TARGET) { final String classResource = classNameToFileName(className); URL classResourceURL = getClass().getResource(classResource); File originalFile = new File(classResourceURL.toURI()); restoreOriginalFile(originalFile); } } private void instrumentClasses(IRuntime runtime) throws URISyntaxException, IOException { Instrumenter instr = new Instrumenter(runtime); for (String className : TARGET) { instrumentClass(instr, className); } } private static void copyFileUsingStream(File source, File dest) throws IOException { InputStream is = null; OutputStream os = null; try { is = new FileInputStream(source); os = new FileOutputStream(dest, false); byte[] buffer = new byte[1024]; int length; while ((length = is.read(buffer)) > 0) { os.write(buffer, 0, length); } } finally { if (is != null) { is.close(); } if (os != null) { os.close(); } } } private void restoreOriginalFile(File originalFile) throws IOException { File backup = new File(originalFile.getAbsolutePath() + ".bak"); if (originalFile.exists()) { originalFile.delete(); } copyFileUsingStream(backup, originalFile); } private void instrumentClass(Instrumenter instr, String className) throws URISyntaxException, IOException { URL classResourceURL = getClass().getResource(classNameToFileName(className)); File originalFile = new File(classResourceURL.toURI()); copyOriginalFile(originalFile); final byte[] instrumented = instr.instrument(classResourceURL.openStream(), className); writeInstrumentedFile(originalFile, instrumented); } private void copyOriginalFile(File originalFile) throws IOException, URISyntaxException { File backup = new File(originalFile.getAbsolutePath() + ".bak"); if (backup.exists()) { backup.delete(); } copyFileUsingStream(originalFile, backup); } private void writeInstrumentedFile(File originalFile, byte[] instrumented) throws IOException { FileOutputStream fooStream = null; try { fooStream = new FileOutputStream(originalFile, false); fooStream.write(instrumented); } finally { if (fooStream != null) { fooStream.close(); } } } private String classNameToFileName(String name) {return '/' + name.replace('.', '/') + ".class";} } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/jacoco/StaticMethods.java ================================================ package samples.powermockito.junit4.jacoco; import java.util.Random; public class StaticMethods { private static final Random RANDOM = new Random(); public static int calculateSomething(int in){ int r = in; for (int i = 0; i < max(); i++) { r += in * i % getSomeFactor(); } return r; } private static int getSomeFactor() { return RANDOM.nextInt(2); } private static int max() { return RANDOM.nextInt(100); } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/jacoco/TargetTest.java ================================================ package samples.powermockito.junit4.jacoco; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.powermock.api.mockito.PowerMockito.doReturn; import static org.powermock.api.mockito.PowerMockito.mock; import static org.powermock.api.mockito.PowerMockito.mockStatic; import static org.powermock.api.mockito.PowerMockito.when; @RunWith(PowerMockRunner.class) @PrepareForTest({StaticMethods.class, InstanceMethods.class}) public class TargetTest { @Test public void shouldCalculateSomethingStatic() throws Exception { mockStatic(StaticMethods.class); doReturn(1).when(StaticMethods.class, "getSomeFactor"); doReturn(1).when(StaticMethods.class, "max"); when(StaticMethods.calculateSomething(10)).thenCallRealMethod(); assertThat(StaticMethods.calculateSomething(10)).isEqualTo(10); } @Test public void shouldCalculateSomething() throws Exception { InstanceMethods instanceMethods = mock(InstanceMethods.class); doReturn(1).when(instanceMethods, "getSomeFactor"); doReturn(1).when(instanceMethods, "max"); when(instanceMethods.calculateSomething(10)).thenCallRealMethod(); assertThat(instanceMethods.calculateSomething(10)).isEqualTo(10); } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/largemethod/LargeMethodTest.java ================================================ package samples.powermockito.junit4.largemethod; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.largemethod.MethodExceedingJvmLimit; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertNull; import static junit.framework.Assert.assertSame; import static junit.framework.Assert.assertTrue; import static junit.framework.Assert.fail; import static org.mockito.Mockito.when; import static org.powermock.api.mockito.PowerMockito.mockStatic; import static org.powermock.api.mockito.PowerMockito.verifyStatic; import static org.powermock.api.support.membermodification.MemberModifier.suppress; @RunWith(PowerMockRunner.class) @PrepareForTest(MethodExceedingJvmLimit.class) public class LargeMethodTest { @Test public void largeMethodShouldBeOverridden() { try { MethodExceedingJvmLimit.init(); fail("Method should be overridden and exception should be thrown"); } catch (Exception e) { assertSame(IllegalAccessException.class, e.getClass()); assertTrue(e.getMessage().contains("Method was too large and after instrumentation exceeded JVM limit")); } } @Test public void largeMethodShouldBeAbleToBeSuppressed() { suppress(PowerMockito.method(MethodExceedingJvmLimit.class, "init")); assertNull("Suppressed method should return: null", MethodExceedingJvmLimit.init()); } @Test public void largeMethodShouldBeAbleToBeMocked() { mockStatic(MethodExceedingJvmLimit.class); when(MethodExceedingJvmLimit.init()).thenReturn("ok"); assertEquals("Mocked method should return: ok", "ok", MethodExceedingJvmLimit.init()); verifyStatic(MethodExceedingJvmLimit.class); MethodExceedingJvmLimit.init(); } @Test(expected = IllegalStateException.class) public void largeMethodShouldBeAbleToBeMockedAndThrowException() { mockStatic(MethodExceedingJvmLimit.class); when(MethodExceedingJvmLimit.init()).thenThrow(new IllegalStateException()); MethodExceedingJvmLimit.init(); verifyStatic(MethodExceedingJvmLimit.class); MethodExceedingJvmLimit.init(); } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/membermodification/MemberModificationExampleTest.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.membermodification; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.staticandinstance.StaticAndInstanceDemo; import samples.suppressconstructor.SuppressConstructorHierarchy; import samples.suppresseverything.SuppressEverything; import samples.suppressfield.SuppressField; import samples.suppressmethod.SuppressMethod; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.*; import static org.powermock.api.support.membermodification.MemberMatcher.constructor; import static org.powermock.api.support.membermodification.MemberMatcher.constructorsDeclaredIn; import static org.powermock.api.support.membermodification.MemberMatcher.everythingDeclaredIn; import static org.powermock.api.support.membermodification.MemberMatcher.field; import static org.powermock.api.support.membermodification.MemberMatcher.method; import static org.powermock.api.support.membermodification.MemberMatcher.methods; import static org.powermock.api.support.membermodification.MemberMatcher.methodsDeclaredIn; import static org.powermock.api.support.membermodification.MemberModifier.*; /** * Demonstrates PowerMock's ability to modify member structures. */ @RunWith(PowerMockRunner.class) @PrepareForTest( { SuppressMethod.class, SuppressField.class, SuppressEverything.class }) public class MemberModificationExampleTest { @Test public void suppressSingleMethodExample() throws Exception { suppress(method(SuppressMethod.class, "getObject")); assertNull(new SuppressMethod().getObject()); } @Test public void suppressMultipleMethodsExample1() throws Exception { suppress(methods(SuppressMethod.class, "getObject", "getInt")); assertNull(new SuppressMethod().getObject()); assertEquals(0, new SuppressMethod().getInt()); } @Test public void suppressMultipleMethodsExample2() throws Exception { suppress(methods(method(SuppressMethod.class, "getObject"), method(SuppressMethod.class, "getInt"))); assertNull(new SuppressMethod().getObject()); assertEquals(0, new SuppressMethod().getInt()); } @Test public void suppressAllMethodsExample() throws Exception { suppress(methodsDeclaredIn(SuppressMethod.class)); final SuppressMethod tested = new SuppressMethod(); assertNull(tested.getObject()); assertNull(SuppressMethod.getObjectStatic()); assertEquals(0, tested.getByte()); } @Test public void suppressSingleFieldExample() throws Exception { suppress(field(SuppressField.class, "domainObject")); SuppressField tested = new SuppressField(); assertNull(tested.getDomainObject()); } @Test public void suppressConstructorExample() throws Exception { suppress(constructor(SuppressConstructorHierarchy.class)); SuppressConstructorHierarchy tested = new SuppressConstructorHierarchy("message"); assertEquals(42, tested.getNumber()); assertNull(tested.getMessage()); } @Test public void stubSingleMethodExample() throws Exception { final String expectedReturnValue = "new"; stub(method(SuppressMethod.class, "getObject")).toReturn(expectedReturnValue); final SuppressMethod tested = new SuppressMethod(); assertEquals(expectedReturnValue, tested.getObject()); assertEquals(expectedReturnValue, tested.getObject()); } @Test public void duckTypeStaticMethodExample() throws Exception { replace(method(SuppressMethod.class, "getObjectStatic")).with( method(StaticAndInstanceDemo.class, "getStaticMessage")); assertEquals(SuppressMethod.getObjectStatic(), StaticAndInstanceDemo.getStaticMessage()); } @Test public void whenReplacingMethodWithAMethodOfIncorrectReturnTypeThenAnIAEIsThrown() throws Exception { try { replace(method(SuppressMethod.class, "getObjectStatic")).with( method(StaticAndInstanceDemo.class, "aVoidMethod")); fail("Should thow IAE"); } catch (Exception e) { assertEquals("The replacing method (public static void samples.staticandinstance.StaticAndInstanceDemo.aVoidMethod()) needs to return java.lang.Object and not void.", e.getMessage()); } } @Test public void whenReplacingMethodWithAMethodOfWithIncorrectParametersThenAnIAEIsThrown() throws Exception { try { replace(method(SuppressMethod.class, "getObjectStatic")).with( method(StaticAndInstanceDemo.class, "aMethod2")); fail("Should thow IAE"); } catch (Exception e) { 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()); } } @Test public void changingReturnValueExample() throws Exception { replace(method(SuppressMethod.class, "getObjectWithArgument")).with(new ReturnValueChangingInvocationHandler()); final SuppressMethod tested = new SuppressMethod(); assertThat(tested.getObjectWithArgument("don't do anything"), is(instanceOf(Object.class))); assertEquals("hello world", tested.getObjectWithArgument("make it a string")); } @Test public void suppressAllConstructors() throws Exception { suppress(constructorsDeclaredIn(SuppressEverything.class)); SuppressEverything suppressEverything = new SuppressEverything(); new SuppressEverything("test"); try { suppressEverything.something(); fail("Should throw ISE"); } catch (IllegalStateException e) { assertEquals("error", e.getMessage()); } } @Test public void suppressEverythingExample() throws Exception { suppress(everythingDeclaredIn(SuppressEverything.class)); SuppressEverything suppressEverything = new SuppressEverything(); new SuppressEverything("test"); suppressEverything.something(); suppressEverything.somethingElse(); } private final class ReturnValueChangingInvocationHandler implements InvocationHandler { @Override public Object invoke(Object object, Method method, Object[] arguments) throws Throwable { if (arguments[0].equals("make it a string")) { return "hello world"; } else { return method.invoke(object, arguments); } } } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/nested/NestedClassDefinedInsideTestCaseTest.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.nested; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import static org.junit.Assert.assertEquals; import static org.powermock.api.mockito.PowerMockito.mock; import static org.powermock.api.mockito.PowerMockito.when; @RunWith(PowerMockRunner.class) @PrepareForTest( { NestedClassDefinedInsideTestCaseTest.class }) public class NestedClassDefinedInsideTestCaseTest { @Test public void mocksNestedPrivateClassDefinedInsideTestCase() throws Exception { NestedPrivateClassDefinedInsideTestCase tested = mock(NestedPrivateClassDefinedInsideTestCase.class); when(tested.getValue()).thenReturn("something"); assertEquals("something", tested.getValue()); } @Test @Ignore("See issue 95") public void mocksNestedPrivateFinalClassDefinedInsideTestCase() throws Exception { NestedPrivateFinalClassDefinedInsideTestCase tested = mock(NestedPrivateFinalClassDefinedInsideTestCase.class); when(tested.getValue()).thenReturn("something"); assertEquals("something", tested.getValue()); } private class NestedPrivateClassDefinedInsideTestCase { public String getValue() { return "value"; } } private final class NestedPrivateFinalClassDefinedInsideTestCase { public String getValue() { return "value"; } } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/partialmocking/PartialMockingExampleTest.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.partialmocking; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.partialmocking.PartialMockingExample; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.powermock.api.mockito.PowerMockito.doReturn; import static org.powermock.api.mockito.PowerMockito.spy; /** * Asserts that partial mocking (spying) with PowerMockito works for non-final * methods. */ @RunWith(PowerMockRunner.class) @PrepareForTest(PartialMockingExample.class) public class PartialMockingExampleTest { @Test public void validatingSpiedObjectGivesCorrectNumberOfExpectedInvocations() throws Exception { final String expected = "TEST VALUE"; PartialMockingExample underTest = spy(new PartialMockingExample()); doReturn(expected).when(underTest).methodToMock(); assertEquals(expected, underTest.methodToTest()); verify(underTest).methodToTest(); verify(underTest).methodToMock(); } @Test public void validatingSpiedObjectGivesCorrectNumberOfExpectedInvocationsForMockito() throws Exception { final String expected = "TEST VALUE"; PartialMockingExample underTest = Mockito.spy(new PartialMockingExample()); doReturn(expected).when(underTest).methodToMock(); assertEquals(expected, underTest.methodToTest()); verify(underTest).methodToTest(); verify(underTest).methodToMock(); } @Test public void should_verify_spied_object_used_in_other_threads() { final String expected = "TEST VALUE"; final PartialMockingExample underTest = spy(new PartialMockingExample()); doReturn(expected).when(underTest).methodToMock(); final int threadCounts = 10; final CountDownLatch startLatch = new CountDownLatch(1); final CountDownLatch endLatch = new CountDownLatch(threadCounts); final List values = new CopyOnWriteArrayList(); for (int i = 0; i < threadCounts; i++) { createAndStartThread(i, underTest, startLatch, endLatch, values); } startLatch.countDown(); awaitThreads(endLatch); assertThat(values) .as("All threads have called method and get expected result") .hasSize(threadCounts) .containsOnly(expected); verify(underTest, times(threadCounts)).methodToTest(); verify(underTest, times(threadCounts)).methodToMock(); } private void awaitThreads(final CountDownLatch endLatch) { try { endLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); } } private void createAndStartThread(final int index, final PartialMockingExample underTest, final CountDownLatch startLatch, final CountDownLatch endLatch, final List values) { Runnable runnable = new Runnable() { @Override public void run() { try { startLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); } values.add(underTest.methodToTest()); endLatch.countDown(); } }; Thread thread = new Thread(runnable, "mock-use-" + index); thread.start(); } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/partialmocking/PartialMockingRetainsStateTest.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.partialmocking; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.mockito.PowerMockito; import org.powermock.modules.junit4.PowerMockRunner; import samples.partialmocking.MockSelfDemo; import samples.partialmocking.MockWithStaticStateDemo; import static junit.framework.Assert.assertEquals; /** * Demonstrates that PowerMockito retains state when spying. This was previously * a bug (issue 263). */ @RunWith(PowerMockRunner.class) public class PartialMockingRetainsStateTest { @Test public void spyingOnAnObjectRetainsState() { MockSelfDemo demo = new MockSelfDemo(4); MockSelfDemo spy = PowerMockito.spy(demo); assertEquals(4, spy.getConstructorValue()); } @Test public void spyingOnAClassRetainsState() { PowerMockito.spy(MockWithStaticStateDemo.class); assertEquals(5, MockWithStaticStateDemo.getState()); } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/partialmocking/PrivatePartialMockingExampleTest.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.partialmocking; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.partialmocking.PrivatePartialMockingExample; import java.lang.reflect.Method; import static org.junit.Assert.assertEquals; import static org.powermock.api.mockito.PowerMockito.*; import static org.powermock.api.support.membermodification.MemberMatcher.method; /** * Asserts that partial mocking (spying) with PowerMockito works for non-final * private methods. */ @RunWith(PowerMockRunner.class) @PrepareForTest(PrivatePartialMockingExample.class) public class PrivatePartialMockingExampleTest { @Test public void spyingOnPrivateMethodsWorks() throws Exception { final String expected = "TEST VALUE"; PrivatePartialMockingExample underTest = spy(new PrivatePartialMockingExample()); final String nameOfMethodToMock = "methodToMock"; final String input = "input"; when(underTest, nameOfMethodToMock, input).thenReturn(expected); assertEquals(expected, underTest.methodToTest()); verifyPrivate(underTest).invoke(nameOfMethodToMock, input); } @Test public void partialMockingOfPrivateMethodsWorks() throws Exception { final String expected = "TEST VALUE"; PrivatePartialMockingExample underTest = spy(new PrivatePartialMockingExample()); final String nameOfMethodToMock = "methodToMock"; final String input = "input"; doReturn(expected).when(underTest, nameOfMethodToMock, input); assertEquals(expected, underTest.methodToTest()); verifyPrivate(underTest).invoke(nameOfMethodToMock, input); } @Test public void spyingOnPrivateMethodsWorksWithoutSpecifyingMethodName() throws Exception { final String expected = "TEST VALUE"; PrivatePartialMockingExample underTest = spy(new PrivatePartialMockingExample()); final String input = "input"; final Method methodToMock = method(PrivatePartialMockingExample.class, String.class); when(underTest, methodToMock).withArguments(input).thenReturn(expected); assertEquals(expected, underTest.methodToTest()); verifyPrivate(underTest).invoke(methodToMock).withArguments(input); } @Test public void partialMockingOfPrivateMethodsWorksWithoutSpecifyingMethodName() throws Exception { final String expected = "TEST VALUE"; PrivatePartialMockingExample underTest = spy(new PrivatePartialMockingExample()); final String input = "input"; final Method methodToMock = method(PrivatePartialMockingExample.class, String.class); doReturn(expected).when(underTest, methodToMock).withArguments(input); assertEquals(expected, underTest.methodToTest()); verifyPrivate(underTest).invoke(methodToMock).withArguments(input); } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/partialmocking/StaticPartialMockingTest.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.partialmocking; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.partialmocking.MockSelfDemo; import samples.singleton.StaticExample; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.times; import static org.powermock.api.mockito.PowerMockito.*; import static org.powermock.api.support.membermodification.MemberMatcher.method; @RunWith(PowerMockRunner.class) @PrepareForTest({StaticExample.class, MockSelfDemo.class}) public class StaticPartialMockingTest { @Test public void spyingOnStaticMethodReturningObjectWorks() throws Exception { spy(StaticExample.class); assertTrue(Object.class.equals(StaticExample.objectMethod().getClass())); when(StaticExample.class, "privateObjectMethod").thenReturn("Hello static"); assertEquals("Hello static", StaticExample.objectMethod()); /* * privateObjectMethod should be invoked twice, once at "assertTrue" and * once above. */ verifyPrivate(StaticExample.class, times(2)).invoke("privateObjectMethod"); } @Test public void partialMockingOfStaticMethodReturningObjectWorks() throws Exception { spy(StaticExample.class); assertTrue(Object.class.equals(StaticExample.objectMethod().getClass())); doReturn("Hello static").when(StaticExample.class, "privateObjectMethod"); assertEquals("Hello static", StaticExample.objectMethod()); /* * privateObjectMethod should be invoked twice, once at "assertTrue" and * once above. */ verifyPrivate(StaticExample.class, times(2)).invoke("privateObjectMethod"); } @Test public void partialPrivateMockingWithAnswerOfStaticMethodReturningObjectWorks() throws Exception { spy(StaticExample.class); assertTrue(Object.class.equals(StaticExample.objectMethod().getClass())); doAnswer(new Answer() { @Override public String answer(InvocationOnMock invocation) throws Throwable { return "Hello static"; } }).when(StaticExample.class, "privateObjectMethod"); assertEquals("Hello static", StaticExample.objectMethod()); /* * privateObjectMethod should be invoked twice, once at "assertTrue" and * once above. */ verifyPrivate(StaticExample.class, times(2)).invoke("privateObjectMethod"); } @Test public void spyingOnStaticFinalMethodReturningObjectWorks() throws Exception { spy(StaticExample.class); assertTrue(Object.class.equals(StaticExample.objectFinalMethod().getClass())); when(StaticExample.class, "privateObjectFinalMethod").thenReturn("Hello static"); assertEquals("Hello static", StaticExample.objectFinalMethod()); verifyPrivate(StaticExample.class, times(2)).invoke("privateObjectFinalMethod"); } @Test public void partialMockingOfStaticFinalMethodReturningObjectWorks() throws Exception { spy(StaticExample.class); assertTrue(Object.class.equals(StaticExample.objectFinalMethod().getClass())); doReturn("Hello static").when(StaticExample.class, "privateObjectFinalMethod"); assertEquals("Hello static", StaticExample.objectFinalMethod()); verifyPrivate(StaticExample.class, times(2)).invoke("privateObjectFinalMethod"); } @Test(expected = ArrayStoreException.class) public void spyingOnStaticVoidMethodReturningObjectWorks() throws Exception { spy(StaticExample.class); StaticExample.voidMethod(); when(StaticExample.class, "privateVoidMethod").thenThrow(new ArrayStoreException()); StaticExample.voidMethod(); } @Test(expected = ArrayStoreException.class) public void partialMockingOfStaticVoidMethodReturningObjectWorks() throws Exception { spy(StaticExample.class); StaticExample.voidMethod(); doThrow(new ArrayStoreException()).when(StaticExample.class, "privateVoidMethod"); StaticExample.voidMethod(); } @Test(expected = ArrayStoreException.class) public void spyingOnStaticFinalVoidMethodReturningObjectWorks() throws Exception { spy(StaticExample.class); StaticExample.voidFinalMethod(); when(StaticExample.class, "privateVoidFinalMethod").thenThrow(new ArrayStoreException()); StaticExample.voidFinalMethod(); } @Test(expected = ArrayStoreException.class) public void partialMockingOfStaticFinalVoidMethodReturningObjectWorks() throws Exception { spy(StaticExample.class); StaticExample.voidFinalMethod(); doThrow(new ArrayStoreException()).when(StaticExample.class, "privateVoidFinalMethod"); StaticExample.voidFinalMethod(); } @Test public void partialMockingOfPublicStaticVoidWorks() throws Exception { spy(StaticExample.class); // Given doNothing().when(StaticExample.class); StaticExample.staticVoidMethod(); // When StaticExample.staticVoidMethod(); // Then verifyStatic(StaticExample.class, times(1)); StaticExample.staticVoidMethod(); } @Test public void partialMockingOfPublicStaticFinalVoidWorks() throws Exception { spy(StaticExample.class); doNothing().when(StaticExample.class); StaticExample.staticFinalVoidMethod(); StaticExample.staticFinalVoidMethod(); } @Test public void partialMockingOfNonVoidPublicStaticMethodsWorks() throws Exception { spy(StaticExample.class); doReturn("something").when(StaticExample.class); StaticExample.staticMethodReturningString(); assertEquals("something", StaticExample.staticMethodReturningString()); } @Test public void partialMockingWithAnswerOfNonVoidPublicStaticMethodsWorks() throws Exception { spy(StaticExample.class); doAnswer(new Answer() { @Override public String answer(InvocationOnMock invocation) throws Throwable { return "something"; } }).when(StaticExample.class); StaticExample.staticMethodReturningString(); assertEquals("something", StaticExample.staticMethodReturningString()); } @Test public void partialMockingOfPublicStaticMethodsWorks() throws Exception { spy(MockSelfDemo.class); when(MockSelfDemo.class, method(MockSelfDemo.class, "methodToBeStubbed")).withNoArguments().thenReturn(2); int result = MockSelfDemo.getSomething(); assertEquals(4, result); } @Test public void partialMockingOfPublicStaticMethodsWorksWhenUsingDoReturn() throws Exception { spy(MockSelfDemo.class); doReturn(2).when(MockSelfDemo.class); MockSelfDemo.methodToBeStubbed(); int result = MockSelfDemo.getSomething(); assertEquals(4, result); } @Test public void partialMockingOfPublicStaticMethodsWorksWhenUsingDoReturnAndMethodNameAsString() throws Exception { spy(MockSelfDemo.class); doReturn(3).when(MockSelfDemo.class, "methodToBeStubbed"); int result = MockSelfDemo.getSomething(); assertEquals(6, result); } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/privatemocking/PrivateInstanceMockingCases.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package samples.powermockito.junit4.privatemocking; import org.junit.Test; import org.mockito.Mockito; import org.mockito.exceptions.base.MockitoAssertionError; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.powermock.reflect.Whitebox; import samples.privateandfinal.PrivateFinal; import samples.privatemocking.PrivateMethodDemo; import java.io.File; import java.io.StringReader; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.never; import static org.powermock.api.mockito.PowerMockito.doReturn; import static org.powermock.api.mockito.PowerMockito.mock; import static org.powermock.api.mockito.PowerMockito.spy; import static org.powermock.api.mockito.PowerMockito.verifyPrivate; import static org.powermock.api.mockito.PowerMockito.when; import static org.powermock.api.support.membermodification.MemberMatcher.method; public class PrivateInstanceMockingCases { @Test public void should_call_method_that_best_match_the_given_parameters_during_verification() throws Exception { final String stubbedValue = "another"; final PrivateMethodDemo tested = mock(PrivateMethodDemo.class); when(tested.sayYear(anyString(), anyInt())).thenCallRealMethod(); when(tested, "doSayYear", 12, "test").thenReturn(stubbedValue); assertThat(tested.sayYear("test", 12)) .as("Private method is called") .isEqualTo(stubbedValue); verifyPrivate(tested).invoke(12, "test"); } @Test public void expectationsWorkWhenSpyingOnPrivateMethods() throws Exception { PrivateMethodDemo tested = spy(new PrivateMethodDemo()); assertEquals("Hello Temp, you are 50 old.", tested.sayYear("Temp", 50)); when(tested, "doSayYear", 12, "test").thenReturn("another"); assertEquals("Hello Johan, you are 29 old.", tested.sayYear("Johan", 29)); assertEquals("another", tested.sayYear("test", 12)); verifyPrivate(tested).invoke("doSayYear", 12, "test"); } @Test public void expectationsWorkWithArgumentMatchersWhenSpyingOnPrivateMethods() throws Exception { PrivateMethodDemo tested = spy(new PrivateMethodDemo()); assertEquals("Hello Temp, you are 50 old.", tested.sayYear("Temp", 50)); when(tested, "doSayYear", Mockito.anyInt(), Mockito.anyString()).thenReturn("another"); assertEquals("another", tested.sayYear("Johan", 29)); assertEquals("another", tested.sayYear("test", 12)); verifyPrivate(tested).invoke("doSayYear", 29, "Johan"); verifyPrivate(tested).invoke("doSayYear", 12, "test"); verifyPrivate(tested).invoke("doSayYear", 50, "Temp"); } @Test public void answersWorkWhenSpyingOnPrivateVoidMethods() throws Exception { PrivateMethodDemo tested = spy(new PrivateMethodDemo()); tested.doObjectStuff(new Object()); when(tested, "doObjectInternal", isA(String.class)).thenAnswer(new Answer() { private static final long serialVersionUID = 20645008237481667L; @Override public Void answer(InvocationOnMock invocation) throws Throwable { assertEquals("Testing", invocation.getArguments()[0]); return null; } }); tested.doObjectStuff(new Object()); tested.doObjectStuff("Testing"); } @Test public void spyingOnPrivateFinalMethodsWorksWhenClassIsNotFinal() throws Exception { PrivateFinal tested = spy(new PrivateFinal()); final String name = "test"; tested.say(name); assertEquals("Hello " + name, tested.say(name)); when(tested, "sayIt", name).thenReturn("First", "Second"); assertEquals("First", tested.say(name)); assertEquals("Second", tested.say(name)); } @Test public void errorousVerificationOnPrivateMethodGivesFilteredErrorMessage() throws Exception { PrivateMethodDemo tested = spy(new PrivateMethodDemo()); assertEquals("Hello Temp, you are 50 old.", tested.sayYear("Temp", 50)); when(tested, "doSayYear", Mockito.anyInt(), Mockito.anyString()).thenReturn("another"); assertEquals("another", tested.sayYear("Johan", 29)); assertEquals("another", tested.sayYear("test", 12)); try { verifyPrivate(tested, never()).invoke("doSayYear", 50, "Temp"); fail("Should throw assertion error"); } catch (MockitoAssertionError e) { assertThat(e.getMessage()) .as("Never wanted but invoked") .contains("Never wanted but invoked"); } } @Test public void expectationsWorkWhenSpyingOnPrivateMethodsUsingDoReturn() throws Exception { PrivateMethodDemo tested = spy(new PrivateMethodDemo()); assertEquals("Hello Temp, you are 50 old.", tested.sayYear("Temp", 50)); doReturn("another").when(tested, "doSayYear", 12, "test"); assertEquals("Hello Johan, you are 29 old.", tested.sayYear("Johan", 29)); assertEquals("another", tested.sayYear("test", 12)); verifyPrivate(tested).invoke("doSayYear", 12, "test"); } @Test public void expectationsWorkWhenSpyingOnPrivateMethodsUsingDoReturnWhenMethodDoesntHaveAnyArguments() throws Exception { PrivateMethodDemo tested = spy(new PrivateMethodDemo()); doReturn("another").when(tested, "sayIt"); assertEquals("another", Whitebox.invokeMethod(tested, "sayIt")); verifyPrivate(tested).invoke("sayIt"); } @Test public void verifyPrivateMethodWhenNoExpectationForTheMethodHasBeenMade() throws Exception { PrivateMethodDemo tested = spy(new PrivateMethodDemo()); assertEquals("Hello Johan, you are 29 old.", tested.sayYear("Johan", 29)); verifyPrivate(tested).invoke("doSayYear", 29, "Johan"); } @Test(expected = ArrayStoreException.class) public void expectationsWorkWhenSpyingOnPrivateVoidMethods() throws Exception { PrivateMethodDemo tested = spy(new PrivateMethodDemo()); tested.doObjectStuff(new Object()); when(tested, "doObjectInternal", isA(Object.class)).thenThrow(new ArrayStoreException()); tested.doObjectStuff(new Object()); } @Test public void usingMultipleArgumentsOnPrivateMethodWorks() throws Exception { File file = mock(File.class); StringReader expected = new StringReader("Some string"); PrivateMethodDemo tested = mock(PrivateMethodDemo.class); doReturn(expected).when(tested, method(PrivateMethodDemo.class, "createReader", File.class)).withArguments(file); StringReader actual = Whitebox.invokeMethod(tested, "createReader", file); assertSame(expected, actual); } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/privatemocking/PrivateInstanceMockingTest.java ================================================ package samples.powermockito.junit4.privatemocking; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.privatemocking.PrivateMethodDemo; @RunWith(PowerMockRunner.class) @PrepareForTest({PrivateMethodDemo.class}) public class PrivateInstanceMockingTest extends PrivateInstanceMockingCases { } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/proxymethod/ProxyMethodTest.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.proxymethod; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.suppressmethod.SuppressMethod; import samples.suppressmethod.SuppressMethodExample; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import static org.mockito.Mockito.verify; import static org.powermock.api.mockito.PowerMockito.mock; import static org.powermock.api.mockito.PowerMockito.when; import static org.powermock.api.support.membermodification.MemberMatcher.method; import static org.powermock.api.support.membermodification.MemberModifier.replace; @RunWith(PowerMockRunner.class) @PrepareForTest(SuppressMethod.class) public class ProxyMethodTest { @Test(expected = ArrayStoreException.class) public void expectionThrowingMethodProxyWorksForJavaLangReflectMethods() throws Exception { replace(method(SuppressMethod.class, "getObject")).with(new ThrowingInvocationHandler()); new SuppressMethod().getObject(); } @Test(expected = ArrayStoreException.class) public void expectionThrowingMethodProxyWorksForMethodNames() throws Exception { replace(method(SuppressMethod.class, "getObject")).with(new ThrowingInvocationHandler()); new SuppressMethod().getObject(); } @Test public void returnValueChangingMethodProxyWorksForMethodNames() throws Exception { replace(method(SuppressMethod.class, "getObject")).with(new ReturnValueChangingInvocationHandler()); assertEquals("hello world", new SuppressMethod().getObject()); } @Test public void delegatingMethodProxyWorksForMethodNames() throws Exception { replace(method(SuppressMethod.class, "getObject")).with(new DelegatingInvocationHandler()); assertSame(SuppressMethod.OBJECT, new SuppressMethod().getObject()); } @Test public void mockingAndMethodProxyAtTheSameTimeWorks() throws Exception { replace(method(SuppressMethod.class, "getObjectStatic")).with(new DelegatingInvocationHandler()); SuppressMethod tested = mock(SuppressMethod.class); when(tested.getObject()).thenReturn("Hello world"); assertSame(SuppressMethod.OBJECT, SuppressMethod.getObjectStatic()); assertEquals("Hello world", tested.getObject()); verify(tested).getObject(); } @Test @Ignore("Doesn't work atm") public void replaceInstanceMethodsWork() throws Exception { replace(method(SuppressMethod.class, "getObject")).with(method(SuppressMethodExample.class, "getStringObject")); SuppressMethod tested = new SuppressMethod(); assertEquals("test", tested.getObject()); } @Test(expected = IllegalArgumentException.class) public void replaceInstanceMethodToStaticMethodDoesntWork() throws Exception { replace(method(SuppressMethod.class, "getObject")).with(method(SuppressMethodExample.class, "getStringObjectStatic")); } @Test(expected = IllegalArgumentException.class) public void replaceStaticMethodToInstaceMethodDoesntWork() throws Exception { replace(method(SuppressMethod.class, "getObjectStatic")).with(method(SuppressMethodExample.class, "getStringObject")); } @Test public void replaceStaticMethodsWork() throws Exception { replace(method(SuppressMethod.class, "getObjectStatic")).with(method(SuppressMethodExample.class, "getStringObjectStatic")); assertEquals("test", SuppressMethod.getObjectStatic()); } private final class ThrowingInvocationHandler implements InvocationHandler { @Override public Object invoke(Object object, Method method, Object[] arguments) throws Throwable { throw new ArrayStoreException(); } } private final class ReturnValueChangingInvocationHandler implements InvocationHandler { @Override public Object invoke(Object object, Method method, Object[] arguments) throws Throwable { return "hello world"; } } private final class DelegatingInvocationHandler implements InvocationHandler { @Override public Object invoke(Object object, Method method, Object[] arguments) throws Throwable { return method.invoke(object, arguments); } } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/simplemix/SimpleMixTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.simplemix; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PowerMockListener; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.core.testlisteners.FieldDefaulter; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.reflect.Whitebox; import samples.simplemix.SimpleMix; import samples.simplemix.SimpleMixCollaborator; import samples.simplemix.SimpleMixConstruction; import samples.simplemix.SimpleMixUtilities; import static org.junit.Assert.assertEquals; import static org.powermock.api.mockito.PowerMockito.*; import static org.powermock.api.support.membermodification.MemberMatcher.method; /** * Demonstrates PowerMockito features such as static mocking, final mocking, * partial mocking and setting internal state. It also demonstrates * test-chunking and final system class mocking. */ @RunWith(PowerMockRunner.class) @PowerMockListener(FieldDefaulter.class) public class SimpleMixTest { @PrepareForTest( { SimpleMixUtilities.class, SimpleMixCollaborator.class, SimpleMix.class }) @Test public void staticPartialFinalMocking() throws Exception { SimpleMix tested = spy(new SimpleMix()); when(tested, "getValue").thenReturn(0); SimpleMixCollaborator simpleMixCollaboratorMock = mock(SimpleMixCollaborator.class); mockStatic(SimpleMixUtilities.class); SimpleMixConstruction simpleMixConstructionMock = mock(SimpleMixConstruction.class); Whitebox.setInternalState(tested, simpleMixCollaboratorMock); when(SimpleMixUtilities.getRandomInteger()).thenReturn(10); when(simpleMixCollaboratorMock.getRandomInteger()).thenReturn(6); whenNew(SimpleMixConstruction.class).withNoArguments().thenReturn(simpleMixConstructionMock); when(simpleMixConstructionMock.getMyValue()).thenReturn(1); assertEquals(4, tested.calculate()); verifyStatic(SimpleMixUtilities.class); SimpleMixUtilities.getRandomInteger(); verifyNew(SimpleMixConstruction.class).withNoArguments(); verifyPrivate(tested) .invoke(method(SimpleMix.class, "getValue")) .withNoArguments(); } @PrepareForTest( { SimpleMix.class }) @Test public void finalSystemClassMocking() throws Exception { SimpleMix tested = new SimpleMix(); mockStatic(System.class); when(System.currentTimeMillis()).thenReturn(2000L); assertEquals(2, Whitebox.invokeMethod(tested, "getValue")); } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/spy/SpyTest.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.spy; import org.assertj.core.api.Assertions; import org.assertj.core.api.Java6Assertions; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.spy.SpyObject; import samples.suppressmethod.SuppressMethod; import samples.suppressmethod.SuppressMethodParent; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.powermock.api.mockito.PowerMockito.doNothing; import static org.powermock.api.mockito.PowerMockito.spy; import static org.powermock.api.mockito.PowerMockito.when; import static org.powermock.api.support.membermodification.MemberMatcher.method; import static org.powermock.api.support.membermodification.MemberModifier.suppress; @RunWith(PowerMockRunner.class) @PrepareForTest({SpyObject.class, SuppressMethod.class, SuppressMethodParent.class}) public class SpyTest { private SpyObject partialMock = null; @Before public void setup() throws Exception { partialMock = spy(new SpyObject()); } @Test public void should_stub_spying_on_private_method_works() throws Exception { when(partialMock, "getMyString").thenReturn("ikk2"); assertThat(partialMock.getMyString(), equalTo("ikk2")); assertThat(partialMock.getStringTwo(), equalTo("two")); } @Test public void should_call_real_method_when_spy_method_is_not_stubbed() { Java6Assertions.assertThat(partialMock.getMyString()) .as("Real method is called") .isEqualTo(new SpyObject().getMyString()); } @Test public void testSuppressMethodWhenObjectIsSpy() throws Exception { suppress(method(SuppressMethod.class, "myMethod")); SuppressMethod tested = spy(new SuppressMethod()); assertEquals(0, tested.myMethod()); } @Test public void testSuppressMethodInParentOnlyWhenObjectIsSpy() throws Exception { suppress(method(SuppressMethodParent.class, "myMethod")); SuppressMethod tested = spy(new SuppressMethod()); assertEquals(20, tested.myMethod()); } @Test public void testDoNothingForSpy() { doNothing().when(partialMock).throwException(); partialMock.throwException(); } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/stacktracecleaner/LocationFromStackTraceTest.java ================================================ package samples.powermockito.junit4.stacktracecleaner; import java.util.ArrayList; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.internal.stubbing.InvocationContainerImpl; import org.mockito.internal.util.MockUtil; import org.mockito.invocation.Location; import org.mockito.invocation.MockHandler; import org.mockito.junit.MockitoJUnitRunner; import org.mockito.stubbing.Stubbing; import org.powermock.api.mockito.invocation.MockHandlerAdaptor; import org.powermock.api.mockito.invocation.MockitoMethodInvocationControl; import org.powermock.core.MockRepository; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunnerDelegate; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.powermock.api.mockito.PowerMockito.doNothing; import static org.powermock.api.mockito.PowerMockito.mockStatic; import static org.powermock.api.mockito.PowerMockito.when; /** * Ensures Location.toString returns the location where a mock is declared. The filtering of the stack trace used * to determine the location is performed by the StackTraceCleaner in StackTraceCleanerProvider. */ @RunWith(value = PowerMockRunner.class) @PowerMockRunnerDelegate(MockitoJUnitRunner.StrictStubs.class) @PrepareForTest({SomethingWithStaticMethod.class}) public class LocationFromStackTraceTest { @Test public void should_filter_extra_elements_in_stack_when_mocking_static_method() throws Exception { mockStatic(SomethingWithStaticMethod.class); when(SomethingWithStaticMethod.doStaticOne()).thenReturn("Something else 1"); when(SomethingWithStaticMethod.doStaticTwo()).thenReturn("Something else 2"); doNothing().when(SomethingWithStaticMethod.class, "doStaticVoid"); MockitoMethodInvocationControl invocationControl = (MockitoMethodInvocationControl) MockRepository.getStaticMethodInvocationControl(SomethingWithStaticMethod.class); MockHandlerAdaptor mockHandlerAdaptor = invocationControl.getMockHandlerAdaptor(); Object mock = mockHandlerAdaptor.getMock(); MockHandler mockHandler = MockUtil.getMockHandler(mock); InvocationContainerImpl invocationContainer = (InvocationContainerImpl)mockHandler.getInvocationContainer(); List stubbings = new ArrayList(invocationContainer.getStubbingsAscending()); assertThat(stubbings.size(), is(3)); Location static1Location = stubbings.get(0).getInvocation().getLocation(); assertThat(static1Location.toString(), is("-> at samples.powermockito.junit4.stacktracecleaner." + "LocationFromStackTraceTest.should_filter_extra_elements_in_stack_when_mocking_static_method(" + "LocationFromStackTraceTest.java:37)")); Location static2Location = stubbings.get(1).getInvocation().getLocation(); assertThat(static2Location.toString(), is("-> at samples.powermockito.junit4.stacktracecleaner." + "LocationFromStackTraceTest.should_filter_extra_elements_in_stack_when_mocking_static_method(" + "LocationFromStackTraceTest.java:38)")); Location staticVoidLocation = stubbings.get(2).getInvocation().getLocation(); assertThat(staticVoidLocation.toString(), is("-> at samples.powermockito.junit4.stacktracecleaner." + "LocationFromStackTraceTest.should_filter_extra_elements_in_stack_when_mocking_static_method(" + "LocationFromStackTraceTest.java:39)")); // Removing these calls and the three Location assertions above will cause the test to fail due to the // strict stubs. Without the alterations to StackTraceCleanerProvider, the failure messages will contain // an item in the stack trace inside the powermock libraries. assertThat(SomethingWithStaticMethod.doStaticOne(), is("Something else 1")); assertThat(SomethingWithStaticMethod.doStaticTwo(), is("Something else 2")); SomethingWithStaticMethod.doStaticVoid(); } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/stacktracecleaner/SomethingWithStaticMethod.java ================================================ package samples.powermockito.junit4.stacktracecleaner; public class SomethingWithStaticMethod { public static String doStaticOne() { return "I am static 1"; } public static String doStaticTwo() { return "I am static 2"; } public static void doStaticVoid() { } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/staticandinstance/StaticAndInstanceDemoTest.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.staticandinstance; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.staticandinstance.StaticAndInstanceDemo; import static org.junit.Assert.assertEquals; import static org.powermock.api.mockito.PowerMockito.*; @RunWith(PowerMockRunner.class) @PrepareForTest(StaticAndInstanceDemo.class) public class StaticAndInstanceDemoTest { @Test public void partialMockingOfStaticAndInstanceMethod() throws Exception { spy(StaticAndInstanceDemo.class); StaticAndInstanceDemo tested = spy(new StaticAndInstanceDemo()); final String staticExpected = "a static message"; when(StaticAndInstanceDemo.getStaticMessage()).thenReturn(staticExpected); final String privateExpected = "A private message "; when(tested, "getPrivateMessage").thenReturn(privateExpected); String actual = tested.getMessage(); assertEquals(privateExpected + staticExpected, actual); verifyStatic(StaticAndInstanceDemo.class); StaticAndInstanceDemo.getStaticMessage(); verifyPrivate(tested).invoke("getPrivateMessage"); } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/staticmocking/MockStaticCases.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package samples.powermockito.junit4.staticmocking; import org.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.exceptions.base.MockitoAssertionError; import org.mockito.exceptions.verification.TooFewActualInvocations; import org.mockito.exceptions.verification.junit.ArgumentsAreDifferent; import samples.singleton.SimpleStaticService; import samples.singleton.StaticService; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.assertj.core.api.Java6Assertions.assertThatThrownBy; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.times; import static org.mockito.Mockito.when; import static org.powermock.api.mockito.PowerMockito.doCallRealMethod; import static org.powermock.api.mockito.PowerMockito.doNothing; import static org.powermock.api.mockito.PowerMockito.doThrow; import static org.powermock.api.mockito.PowerMockito.mockStatic; import static org.powermock.api.mockito.PowerMockito.spy; import static org.powermock.api.mockito.PowerMockito.verifyStatic; public class MockStaticCases { @Test public void should_call_reall_static_void_method() { mockStatic(StaticService.class); StaticService.throwException(); doCallRealMethod().when(StaticService.class); StaticService.throwException(); assertThatThrownBy(new ThrowingCallable() { @Override public void call() throws Throwable { StaticService.throwException(); } }).as("Real method is called") .isInstanceOf(RuntimeException.class); } @Test public void mockStatic_uses_var_args_to_create_multiple_static_mocks() throws Exception { mockStatic(StaticService.class, SimpleStaticService.class); when(SimpleStaticService.say("Something")).thenReturn("other"); StaticService.sayHello(); final String said = SimpleStaticService.say("Something"); verifyStatic(StaticService.class); StaticService.sayHello(); verifyStatic(SimpleStaticService.class); SimpleStaticService.say("Something"); assertEquals(said, "other"); } @Test public void should_verify_behaviour_of_specified_in_verify_static_class() { mockStatic(StaticService.class); StaticService.sayHello(); verifyStatic(StaticService.class); StaticService.sayHello(); } @Test public void should_not_verify_behaviour_of_another_mock_class_not_specified_in_verify_static_class() { mockStatic(StaticService.class); mockStatic(SimpleStaticService.class); StaticService.sayHello(); verifyStatic(StaticService.class); SimpleStaticService.say("Something"); StaticService.sayHello(); } @Test public void testMockStaticNoExpectations() throws Exception { mockStatic(StaticService.class); assertNull(StaticService.say("hello")); // Verification is done in two steps using static methods. verifyStatic(StaticService.class); StaticService.say("hello"); } @Test public void testMockStaticWithExpectations() throws Exception { final String expected = "Hello world"; final String argument = "hello"; mockStatic(StaticService.class); when(StaticService.say(argument)).thenReturn(expected); assertEquals(expected, StaticService.say(argument)); // Verification is done in two steps using static methods. verifyStatic(StaticService.class); StaticService.say(argument); } @Test public void errorousVerificationOfStaticMethodsGivesANonMockitoStandardMessage() throws Exception { final String expected = "Hello world"; final String argument = "hello"; mockStatic(StaticService.class); when(StaticService.say(argument)).thenReturn(expected); assertEquals(expected, StaticService.say(argument)); // Verification is done in two steps using static methods. verifyStatic(StaticService.class, times(2)); try { StaticService.say(argument); fail("Should throw assertion error"); } catch (MockitoAssertionError e) { assertEquals("\nsamples.singleton.StaticService.say(\"hello\");\nWanted 2 times but was 1 time.", e.getMessage()); } } @Test(expected = IllegalStateException.class) public void testMockStaticThatThrowsException() throws Exception { final String argument = "hello"; mockStatic(StaticService.class); when(StaticService.say(argument)).thenThrow(new IllegalStateException()); StaticService.say(argument); } @Test(expected = ArgumentsAreDifferent.class) public void testMockStaticVerificationFails() throws Exception { mockStatic(StaticService.class); assertNull(StaticService.say("hello")); // Verification is done in two steps using static methods. verifyStatic(StaticService.class); StaticService.say("Hello"); } @Test public void testMockStaticAtLeastOnce() throws Exception { mockStatic(StaticService.class); assertNull(StaticService.say("hello")); assertNull(StaticService.say("hello")); // Verification is done in two steps using static methods. verifyStatic(StaticService.class, atLeastOnce()); StaticService.say("hello"); } @Test public void testMockStaticCorrectTimes() throws Exception { mockStatic(StaticService.class); assertNull(StaticService.say("hello")); assertNull(StaticService.say("hello")); // Verification is done in two steps using static methods. verifyStatic(StaticService.class, times(2)); StaticService.say("hello"); } @Test(expected = TooFewActualInvocations.class) public void testMockStaticIncorrectTimes() throws Exception { mockStatic(StaticService.class); assertNull(StaticService.say("hello")); assertNull(StaticService.say("hello")); // Verification is done in two steps using static methods. verifyStatic(StaticService.class, times(3)); StaticService.say("hello"); } @Test public void testMockStaticVoidWithNoExpectations() throws Exception { mockStatic(StaticService.class); StaticService.sayHello(); verifyStatic(StaticService.class); StaticService.sayHello(); } @Test(expected = ArrayStoreException.class) public void testMockStaticVoidWhenThrowingException() throws Exception { mockStatic(StaticService.class); // Expectations doThrow(new ArrayStoreException("Mock error")).when(StaticService.class); StaticService.sayHello(); // Test StaticService.sayHello(); } @Test public void testSpyOnStaticMethods() throws Exception { spy(StaticService.class); String expectedMockValue = "expected"; when(StaticService.say("world")).thenReturn(expectedMockValue); assertEquals(expectedMockValue, StaticService.say("world")); assertEquals("Hello world2", StaticService.say("world2")); } @Test public void spyingUsingArgumentCaptor() throws Exception { // Given mockStatic(StaticService.class); final ArgumentCaptor captor = ArgumentCaptor.forClass(String.class); StaticService.say("something"); verifyStatic(StaticService.class); StaticService.say(captor.capture()); assertEquals("something", captor.getValue()); } @Test public void testMockStaticWithExpectations_withDo() throws Exception { final String argument = "hello"; mockStatic(StaticService.class); doNothing().when(StaticService.class, "sayHello", any(String.class)); StaticService.sayHello(argument); assertThat(StaticService.messageStorage).isNull(); } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/staticmocking/MockStaticTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.staticmocking; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.singleton.SimpleStaticService; import samples.singleton.StaticService; /** * Test class to demonstrate static mocking with PowerMockito. */ @RunWith(PowerMockRunner.class) @PrepareForTest({StaticService.class, SimpleStaticService.class}) public class MockStaticTest extends MockStaticCases { } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/stress/PowerMockStressTest.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.stress; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.stress.ClassWithStatic; import samples.stress.StressSample; import static org.mockito.Mockito.when; /** * Test that asserts that issue 308 is resolved. * The problem was that finalize methods could be called before an expected method because the GC kicked in too soon * since now object held a reference to the mock. */ @RunWith(PowerMockRunner.class) @PrepareForTest({ClassWithStatic.class}) public class PowerMockStressTest { private StressSample underTest = new StressSample(); @Before public void setUp(){ PowerMockito.mockStatic(ClassWithStatic.class); for (int i = 0; i < 1000; i++) { // 100*8executions createWhen(); } } public void createWhen(){ when(ClassWithStatic.a()).thenReturn("A"); when(ClassWithStatic.b()).thenReturn("B"); when(ClassWithStatic.c()).thenReturn("C"); when(ClassWithStatic.d()).thenReturn("D"); when(ClassWithStatic.e()).thenReturn("E"); when(ClassWithStatic.f()).thenReturn("F"); when(ClassWithStatic.g()).thenReturn("G"); when(ClassWithStatic.h()).thenReturn("H"); } @Test public void test1(){ underTest.a1(); } @Test public void test2(){ underTest.b1(); } @Test public void test3(){ underTest.c1(); } @Test public void test4(){ underTest.d1(); } @Test public void test5(){ underTest.e1(); } @Test public void test6(){ underTest.f1(); } @Test public void test7(){ underTest.g1(); } @Test public void test8(){ underTest.h1(); } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/system/ServiceLoaderTest.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.system; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.util.ServiceLoader; import static org.powermock.api.mockito.PowerMockito.doThrow; import static org.powermock.api.mockito.PowerMockito.mock; @RunWith(PowerMockRunner.class) @PrepareForTest(ServiceLoader.class) public class ServiceLoaderTest { @Test(expected = IllegalArgumentException.class) public void supportsMockingServiceLoader() throws Exception { final ServiceLoader mock = mock(ServiceLoader.class); doThrow(new IllegalArgumentException("something")) .when(mock) .reload(); mock.reload(); } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/system/SystemClassUserTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.system; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.system.SystemClassUser; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.UUID; import static org.junit.Assert.*; import static org.mockito.BDDMockito.given; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.times; import static org.powermock.api.mockito.PowerMockito.*; /** * Demonstrates PowerMockito's ability to mock non-final and final system * classes. To mock a system class you need to prepare the calling class for * testing. I.e. let's say you're testing class A which interacts with * URLEncoder then you would do: *

*

 *
 * @PrepareForTest({A.class})
 *
 * 
*/ @RunWith(PowerMockRunner.class) @PrepareForTest({SystemClassUser.class}) public class SystemClassUserTest { @Test public void assertThatMockingOfNonFinalSystemClassesWorks() throws Exception { mockStatic(URLEncoder.class); when(URLEncoder.encode("string", "enc")).thenReturn("something"); assertEquals("something", new SystemClassUser().performEncode()); } @Test public void assertThatMockingOfTheRuntimeSystemClassWorks() throws Exception { mockStatic(Runtime.class); Runtime runtimeMock = mock(Runtime.class); Process processMock = mock(Process.class); when(Runtime.getRuntime()).thenReturn(runtimeMock); when(runtimeMock.exec("command")).thenReturn(processMock); assertSame(processMock, new SystemClassUser().executeCommand()); } @Test public void assertThatMockingOfFinalSystemClassesWorks() throws Exception { mockStatic(System.class); when(System.getProperty("property")).thenReturn("my property"); assertEquals("my property", new SystemClassUser().getSystemProperty()); } @Test public void assertThatPartialMockingOfFinalSystemClassesWorks() throws Exception { spy(System.class); doReturn(2L).when(System.class); System.nanoTime(); new SystemClassUser().doMoreComplicatedStuff(); assertEquals("2", System.getProperty("nanoTime")); } @Test public void assertThatMockingOfCollectionsWork() throws Exception { List list = new LinkedList(); mockStatic(Collections.class); Collections.shuffle(list); new SystemClassUser().shuffleCollection(list); verifyStatic(Collections.class, times(2)); Collections.shuffle(list); } @Test public void assertThatPartialMockingOfFinalSystemClassesWorksForNonVoidMethods() throws Exception { spy(System.class); doReturn("my property").when(System.class); System.getProperty("property"); final SystemClassUser systemClassUser = new SystemClassUser(); systemClassUser.copyProperty("to", "property"); assertEquals("my property", System.getProperty("to")); } @Test public void assertThatMockingStringWorks() throws Exception { mockStatic(String.class); final String string = "string"; final String args = "args"; final String returnValue = "returnValue"; when(String.format(string, args)).thenReturn(returnValue); final SystemClassUser systemClassUser = new SystemClassUser(); assertEquals(systemClassUser.format(string, args), returnValue); } @Test public void mockingStaticVoidMethodWorks() throws Exception { mockStatic(Thread.class); doNothing().when(Thread.class); Thread.sleep(anyLong()); long startTime = System.currentTimeMillis(); final SystemClassUser systemClassUser = new SystemClassUser(); systemClassUser.threadSleep(); long endTime = System.currentTimeMillis(); assertTrue(endTime - startTime < 5000); } @Test public void mockingURLWorks() throws Exception { URL url = mock(URL.class); URLConnection urlConnectionMock = mock(URLConnection.class); when(url.openConnection()).thenReturn(urlConnectionMock); URLConnection openConnection = url.openConnection(); assertSame(openConnection, urlConnectionMock); } @Test public void mockingUUIDWorks() throws Exception { // given final UUID mock = mock(UUID.class); mockStatic(UUID.class); given(UUID.randomUUID()).willReturn(mock); given(mock.toString()).willCallRealMethod(); // when String actual = new SystemClassUser().generatePerishableToken(); // then assertEquals("00000000000000000000000000000000", actual); } @Test public void mockingNewURLWorks() throws Exception { // Given final URL url = mock(URL.class); whenNew(URL.class).withArguments("some_url").thenReturn(url); // When final URL actual = new SystemClassUser().newURL("some_url"); // Then assertSame(url, actual); } @Test public void mockingStringBuilder() throws Exception { // Given final StringBuilder mock = mock(StringBuilder.class); whenNew(StringBuilder.class).withNoArguments().thenReturn(mock); when(mock.toString()).thenReturn("My toString"); // When final StringBuilder actualStringBuilder = new SystemClassUser().newStringBuilder(); final String actualToString = actualStringBuilder.toString(); // Then assertSame(mock, actualStringBuilder); assertEquals("My toString", actualToString); } @Test(expected = IllegalStateException.class) public void triggerMockedCallFromInterfaceTypeInsteadOfConcreteType() throws Exception { StringBuilder builder = mock(StringBuilder.class); when(builder.length()).then(new Answer() { public StringBuilder answer(InvocationOnMock invocation) throws Throwable { throw new IllegalStateException("Can't really happen"); } }); new SystemClassUser().lengthOf(builder); } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/tostring/ToStringTest.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.tostring; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import javax.crypto.Cipher; import static org.junit.Assert.assertNotNull; /** * Test that demonstrates that issue 239 * is resolved. */ @RunWith(PowerMockRunner.class) @PrepareForTest(ToStringTest.class) public class ToStringTest { private Cipher cipher; @Test public void toStringInvocationWorksInMockito() throws Exception { cipher = PowerMockito.mock(Cipher.class); assertNotNull(cipher.toString()); } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/verify/VerifyNoMoreInteractionsTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.verify; import org.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.mockito.exceptions.base.MockitoAssertionError; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.expectnew.ExpectNewDemo; import samples.newmocking.MyClass; import samples.singleton.StaticHelper; import samples.singleton.StaticService; import static org.assertj.core.api.Java6Assertions.assertThatThrownBy; import static org.junit.Assert.assertNull; import static org.mockito.Mockito.times; import static org.powermock.api.mockito.PowerMockito.mock; import static org.powermock.api.mockito.PowerMockito.mockStatic; import static org.powermock.api.mockito.PowerMockito.verifyNew; import static org.powermock.api.mockito.PowerMockito.verifyNoMoreInteractions; import static org.powermock.api.mockito.PowerMockito.verifyStatic; import static org.powermock.api.mockito.PowerMockito.whenNew; import static org.powermock.api.support.membermodification.MemberMatcher.constructor; /** * Test class to demonstrate static mocking with PowerMockito. */ @RunWith(PowerMockRunner.class) @PrepareForTest( { StaticService.class, StaticHelper.class, ExpectNewDemo.class }) public class VerifyNoMoreInteractionsTest { @Test public void verifyNoMoreInteractionsForStaticMethodsReturnsSilentlyWhenNoMoreInteractionsTookPlace() throws Exception { mockStatic(StaticService.class); assertNull(StaticService.say("hello")); verifyStatic(StaticService.class); StaticService.say("hello"); verifyNoMoreInteractions(StaticService.class); } @Test public void verifyNoMoreInteractionsOnMethodThrowsAssertionErrorWhenMoreInteractionsTookPlace() throws Exception { mockStatic(StaticService.class); assertNull(StaticService.say("hello")); assertThatThrownBy(new ThrowingCallable() { @Override public void call() throws Throwable { verifyNoMoreInteractions(StaticService.class); } }).hasMessageStartingWith( "\nNo interactions wanted here:\n-> at samples.powermockito.junit4.verify.VerifyNoMoreInteractionsTest$1.call"); } @Test public void verifyNoMoreInteractionsOnNewInstancesThrowsAssertionErrorWhenMoreInteractionsTookPlace() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock = mock(MyClass.class); whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock); tested.simpleMultipleNew(); assertThatThrownBy(new ThrowingCallable() { @Override public void call() throws Throwable { verifyNoMoreInteractions(MyClass.class); } }).hasMessageStartingWith( "\nNo interactions wanted here:\n-> at samples.powermockito.junit4.verify.VerifyNoMoreInteractionsTest$2.call"); } @Test public void verifyNoMoreInteractionsOnNewInstancesWorks() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock = mock(MyClass.class); whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock); tested.simpleMultipleNew(); verifyNew(MyClass.class, times(3)).withNoArguments(); verifyNoMoreInteractions(MyClass.class); } @Test public void verifyNoMoreInteractionsOnNewInstancesWorksWhenUsingConstructorToExpect() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock = mock(MyClass.class); whenNew(constructor(MyClass.class)).withNoArguments().thenReturn(myClassMock); tested.simpleMultipleNew(); verifyNew(MyClass.class, times(3)).withNoArguments(); verifyNoMoreInteractions(MyClass.class); } @Test public void verifyNoMoreInteractionsDelegatesToPlainMockitoWhenMockIsNotAPowerMockitoMock() throws Exception { final MyClass myClassMock = Mockito.mock(MyClass.class); myClassMock.getMessage(); final String expectedTextThatProvesDelegation = "But found this interaction"; assertThatThrownBy(new ThrowingCallable() { @Override public void call() throws Throwable { verifyNoMoreInteractions(myClassMock); } }).hasMessageContaining(expectedTextThatProvesDelegation); } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/verify/VerifyZeroInteractionsTest.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package samples.powermockito.junit4.verify; import org.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.exceptions.verification.NoInteractionsWanted; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.Service; import samples.singleton.StaticExample; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.assertj.core.api.Java6Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.catchThrowable; import static org.powermock.api.mockito.PowerMockito.mock; import static org.powermock.api.mockito.PowerMockito.mockStatic; import static org.powermock.api.mockito.PowerMockito.verifyZeroInteractions; @RunWith(PowerMockRunner.class) @PrepareForTest(StaticExample.class) public class VerifyZeroInteractionsTest { @Test public void should_throw_verification_exception_in_case_if_static_method_is_called() { mockStatic(StaticExample.class); StaticExample.staticMethodReturningString(); assertThatThrownBy(new ThrowingCallable() { @Override public void call() throws Throwable { verifyZeroInteractions(StaticExample.class); } }).as("Verify Exception is thrown.") .isInstanceOf(NoInteractionsWanted.class) .hasMessageContaining("No interactions"); } @Test public void should_throw_verification_exception_in_case_if_instance_method_called() { final Service mock = mock(Service.class); mock.getServiceMessage(); assertThatThrownBy(new ThrowingCallable() { @Override public void call() throws Throwable { verifyZeroInteractions(mock); } }).as("Verify Exception is thrown.") .isInstanceOf(NoInteractionsWanted.class) .hasMessageContaining("No interactions"); } @Test public void should_not_throw_verification_exception_in_case_if_no_methods_are_called_for_static_mock() { mockStatic(StaticExample.class); final Throwable throwable = catchThrowable(new ThrowingCallable() { @Override public void call() throws Throwable { verifyZeroInteractions(StaticExample.class); } }); assertThat(throwable) .as("Verify Exception is not thrown.") .isNull(); } @Test public void should_not_throw_verification_exception_in_case_if_no_methods_are_called_for_instance_mock() { final Service mock = mock(Service.class); final Throwable throwable = catchThrowable(new ThrowingCallable() { @Override public void call() throws Throwable { verifyZeroInteractions(mock); } }); assertThat(throwable) .as("Verify Exception is not thrown.") .isNull(); } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/whennew/DoesntSupportCreatingMocksInFieldsWhenNewDefect.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.whennew; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.newmocking.NewDemo; import samples.newmocking.SomeDependency; import static org.powermock.api.mockito.PowerMockito.mock; import static org.powermock.api.mockito.PowerMockito.whenNew; @RunWith(PowerMockRunner.class) @PrepareForTest( { NewDemo.class }) /* Issue http://code.google.com/p/powermock/issues/detail?id=298 */ public class DoesntSupportCreatingMocksInFieldsWhenNewDefect { final 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) @Test public void methodUnderTestShouldWorkWithClassLevelMock() throws Exception { whenNew(SomeDependency.class).withNoArguments().thenReturn(somethingUsedByMethodUnderTest); NewDemo objectUnderTest = new NewDemo(); objectUnderTest.methodUnderTest(); } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/whennew/NewFileExampleTest.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.whennew; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.expectnew.NewFileExample; import java.io.File; import static org.junit.Assert.assertTrue; import static org.powermock.api.mockito.PowerMockito.*; @RunWith(PowerMockRunner.class) @PrepareForTest(NewFileExample.class) public class NewFileExampleTest { @Test public void assertThatMockingFileWorks() throws Exception { final String directoryPath = "mocked path"; File directoryMock = mock(File.class); whenNew(File.class).withArguments(directoryPath).thenReturn(directoryMock); when(directoryMock.exists()).thenReturn(false); when(directoryMock.mkdirs()).thenReturn(true); assertTrue(new NewFileExample().createDirectoryStructure(directoryPath)); verifyNew(File.class).withArguments(directoryPath); } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/whennew/VerifyNewMultipleTimesTest.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.whennew; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.expectnew.NewFileExample; import java.io.File; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.powermock.api.mockito.PowerMockito.*; @RunWith(PowerMockRunner.class) @PrepareForTest(NewFileExample.class) public class VerifyNewMultipleTimesTest { private final static String DIRECTORY_PATH = "mocked path"; @Mock private File directoryMock; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); whenNew(File.class).withArguments(DIRECTORY_PATH).thenReturn(directoryMock); when(directoryMock.exists()).thenReturn(false); when(directoryMock.mkdirs()).thenReturn(true); } @Test(expected=AssertionError.class) public void verifyNewTooManyTimesCausesAssertionError() throws Exception { assertTrue(new NewFileExample().createDirectoryStructure((DIRECTORY_PATH))); verify(directoryMock).mkdirs(); // Correct usage verifyNew(File.class, times(1)).withArguments(DIRECTORY_PATH); // Should throw verifyNew(File.class, times(100000)).withArguments(DIRECTORY_PATH); } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/whennew/VerifyNewWithoutWhenNewTest.java ================================================ package samples.powermockito.junit4.whennew; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.expectnew.ExpectNewDemo; import samples.newmocking.MyClass; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.powermock.api.mockito.PowerMockito.verifyNew; @PrepareForTest(ExpectNewDemo.class) @RunWith(PowerMockRunner.class) public class VerifyNewWithoutWhenNewTest { @Test public void verifyingNewWithoutExpectationWhenNoArgumentsThrowsISE() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); assertEquals("Hello world", tested.getMessage()); try { verifyNew(MyClass.class).withNoArguments(); fail("IllegalStateException expected"); } catch (IllegalArgumentException e) { assertEquals("No instantiation of class samples.newmocking.MyClass was recorded " + "during the test. Note that only expected object creations " + "(e.g. those using whenNew(..)) can be verified.", e.getMessage()); } } @Test public void verifyingNewWithoutExpectationButWithArgumentsThrowsISE() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); assertEquals("Hello world", tested.getMessage()); try { verifyNew(MyClass.class, Mockito.atLeastOnce()).withNoArguments(); fail("IllegalStateException expected"); } catch (IllegalArgumentException e) { assertEquals("No instantiation of class samples.newmocking.MyClass was recorded " + "during the test. Note that only expected object creations " + "(e.g. those using whenNew(..)) can be verified.", e.getMessage()); } } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/whennew/WhenNewCases.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.whennew; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.reflect.Whitebox; import org.powermock.reflect.exceptions.ConstructorNotFoundException; import samples.Service; import samples.classwithinnermembers.ClassWithInnerMembers; import samples.classwithinnermembers.ClassWithInnerMembers.*; import samples.expectnew.CreationException; import samples.expectnew.ExpectNewDemo; import samples.expectnew.ExpectNewServiceUser; import samples.expectnew.ExpectNewWithMultipleCtorDemo; import samples.expectnew.ITarget; import samples.expectnew.MultiConstructor; import samples.expectnew.SimpleVarArgsConstructorDemo; import samples.expectnew.Target; import samples.expectnew.VarArgsConstructorDemo; import samples.newmocking.MyClass; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.powermock.api.mockito.PowerMockito.*; import static org.powermock.api.support.membermodification.MemberMatcher.constructor; /** * Test class to demonstrate new instance mocking using whenConstructionOf(..). */ @PrepareForTest({MyClass.class, ExpectNewDemo.class, ClassWithInnerMembers.class, DataInputStream.class, WhenNewCases.class, Target.class, MultiConstructor.class}) public class WhenNewCases { public static final String TARGET_NAME = "MyTarget"; public static final int TARGET_ID = 1; public static final String UNKNOWN_TARGET_NAME = "Unknown2"; public static final int UNKNOWN_TARGET_ID = -11; @Rule public ExpectedException expectedException = ExpectedException.none(); @Test public void testStaticMemberClassMockingWorksWithNoConstructorArguments() throws Exception { Class innerClassType = Whitebox.getInnerClassType(ClassWithInnerMembers.class, "MyInnerClass"); Object mockMyInnerClass = mock(innerClassType); whenNew(innerClassType).withNoArguments().thenReturn(mockMyInnerClass); doReturn("something else").when(mockMyInnerClass, "doStuff"); assertEquals("something else", new ClassWithInnerMembers().getValue()); } @Test public void testStaticMemberClassMockingWorksWithConstructorArguments() throws Exception { Class innerClassType = Whitebox.getInnerClassType( ClassWithInnerMembers.class, "StaticInnerClassWithConstructorArgument"); Object mockMyInnerClass = mock(innerClassType); whenNew(innerClassType).withArguments("value").thenReturn(mockMyInnerClass); doReturn("something else").when(mockMyInnerClass, "doStuff"); assertEquals( "something else", new ClassWithInnerMembers().getValueForStaticInnerClassWithConstructorArgument()); } @Test public void testLocalClassMockingWorksWithNoConstructorArguments() throws Exception { Class innerClassType = Whitebox.getLocalClassType(ClassWithInnerMembers.class, 1, "MyLocalClass"); Object mockMyInnerClass = mock(innerClassType); whenNew(innerClassType).withNoArguments().thenReturn(mockMyInnerClass); doReturn("something else").when(mockMyInnerClass, "doStuff"); assertEquals("something else", new ClassWithInnerMembers().getLocalClassValue()); } @Test public void testLocalClassMockingWorksWithConstructorArguments() throws Exception { Class innerClassType = Whitebox.getLocalClassType(ClassWithInnerMembers.class, 2, "MyLocalClass"); Object mockMyInnerClass = mock(innerClassType); whenNew(innerClassType).withArguments("my value").thenReturn(mockMyInnerClass); doReturn("something else").when(mockMyInnerClass, "doStuff"); assertEquals("something else", new ClassWithInnerMembers().getLocalClassValueWithArgument()); } @Test public void testNonStaticMemberClassMockingWorksWithArguments() throws Exception { Class innerClassType = Whitebox.getInnerClassType( ClassWithInnerMembers.class, "MyInnerClassWithConstructorArgument"); Object mockMyInnerClass = mock(innerClassType); whenNew(innerClassType).withArguments("value").thenReturn(mockMyInnerClass); doReturn("something else").when(mockMyInnerClass, "doStuff"); assertEquals("something else", new ClassWithInnerMembers().getValueForInnerClassWithConstructorArgument()); } @Test public void testNewInnerWithDiffParams() throws Exception { ClassWithInnerMembers outerClass = new ClassWithInnerMembers(); MyInnerClassWithPrivateConstructorWithDiffMultArgs mockMyInnerClassWithPrivateConstructorWithDiffMultArgs = mock(MyInnerClassWithPrivateConstructorWithDiffMultArgs.class); whenNew(MyInnerClassWithPrivateConstructorWithDiffMultArgs.class) .withArguments(null, 2, "3").thenReturn(mockMyInnerClassWithPrivateConstructorWithDiffMultArgs); assertEquals("Expected and actual did not match", mockMyInnerClassWithPrivateConstructorWithDiffMultArgs, outerClass.makeMyInnerClassWithPrivateConstructorWithDiffMultArgs(null, 2, "3")); } @Test public void testNewInnerWithNoNullParams() throws Exception { ClassWithInnerMembers outerClass = new ClassWithInnerMembers(); MyInnerClassWithPublicConstructorWithMultArgs mockMyInnerClassWithPublicConstructorWithMultArgs = mock(MyInnerClassWithPublicConstructorWithMultArgs.class); MyInnerClassWithProtectedConstructorWithMultArgs mockMyInnerClassWithProtectedConstructorWithMultArgs = mock(MyInnerClassWithProtectedConstructorWithMultArgs.class); MyInnerClassWithPackageConstructorWithMultArgs mockMyInnerClassWithPackageConstructorWithMultArgs = mock(MyInnerClassWithPackageConstructorWithMultArgs.class); MyInnerClassWithPrivateConstructorWithMultArgs mockMyInnerClassWithPrivateConstructorWithMultArgs = mock(MyInnerClassWithPrivateConstructorWithMultArgs.class); whenNew(MyInnerClassWithPublicConstructorWithMultArgs.class) .withArguments("1", "2", "3").thenReturn(mockMyInnerClassWithPublicConstructorWithMultArgs); whenNew(MyInnerClassWithProtectedConstructorWithMultArgs.class) .withArguments("1", "2", "3").thenReturn(mockMyInnerClassWithProtectedConstructorWithMultArgs); whenNew(MyInnerClassWithPackageConstructorWithMultArgs.class) .withArguments("1", "2", "3").thenReturn(mockMyInnerClassWithPackageConstructorWithMultArgs); whenNew(MyInnerClassWithPrivateConstructorWithMultArgs.class) .withArguments("1", "2", "3").thenReturn(mockMyInnerClassWithPrivateConstructorWithMultArgs); assertEquals("Expected and actual did not match", mockMyInnerClassWithPublicConstructorWithMultArgs, outerClass.makeMyInnerClassWithPublicConstructorWithMultArgs("1", "2", "3")); assertEquals("Expected and actual did not match", mockMyInnerClassWithProtectedConstructorWithMultArgs, outerClass.makeMyInnerClassWithProtectedConstructorWithMultArgs("1", "2", "3")); assertEquals("Expected and actual did not match", mockMyInnerClassWithPackageConstructorWithMultArgs, outerClass.makeMyInnerClassWithPackageConstructorWithMultArgs("1", "2", "3")); assertEquals("Expected and actual did not match", mockMyInnerClassWithPrivateConstructorWithMultArgs, outerClass.makeMyInnerClassWithPrivateConstructorWithMultArgs("1", "2", "3")); } @Test public void testNewInnerWithMiddleParamNull() throws Exception { ClassWithInnerMembers outerClass = new ClassWithInnerMembers(); MyInnerClassWithPublicConstructorWithMultArgs mockMyInnerClassWithPublicConstructorWithMultArgs = mock(MyInnerClassWithPublicConstructorWithMultArgs.class); MyInnerClassWithProtectedConstructorWithMultArgs mockMyInnerClassWithProtectedConstructorWithMultArgs = mock(MyInnerClassWithProtectedConstructorWithMultArgs.class); MyInnerClassWithPackageConstructorWithMultArgs mockMyInnerClassWithPackageConstructorWithMultArgs = mock(MyInnerClassWithPackageConstructorWithMultArgs.class); MyInnerClassWithPrivateConstructorWithMultArgs mockMyInnerClassWithPrivateConstructorWithMultArgs = mock(MyInnerClassWithPrivateConstructorWithMultArgs.class); whenNew(MyInnerClassWithPublicConstructorWithMultArgs.class) .withArguments("1", null, "3").thenReturn(mockMyInnerClassWithPublicConstructorWithMultArgs); whenNew(MyInnerClassWithProtectedConstructorWithMultArgs.class) .withArguments("1", null, "3").thenReturn(mockMyInnerClassWithProtectedConstructorWithMultArgs); whenNew(MyInnerClassWithPackageConstructorWithMultArgs.class) .withArguments("1", null, "3").thenReturn(mockMyInnerClassWithPackageConstructorWithMultArgs); whenNew(MyInnerClassWithPrivateConstructorWithMultArgs.class) .withArguments("1", null, "3").thenReturn(mockMyInnerClassWithPrivateConstructorWithMultArgs); assertEquals("Expected and actual did not match", mockMyInnerClassWithPublicConstructorWithMultArgs, outerClass.makeMyInnerClassWithPublicConstructorWithMultArgs("1", null, "3")); assertEquals("Expected and actual did not match", mockMyInnerClassWithProtectedConstructorWithMultArgs, outerClass.makeMyInnerClassWithProtectedConstructorWithMultArgs("1", null, "3")); assertEquals("Expected and actual did not match", mockMyInnerClassWithPackageConstructorWithMultArgs, outerClass.makeMyInnerClassWithPackageConstructorWithMultArgs("1", null, "3")); assertEquals("Expected and actual did not match", mockMyInnerClassWithPrivateConstructorWithMultArgs, outerClass.makeMyInnerClassWithPrivateConstructorWithMultArgs("1", null, "3")); } @Test public void testNewInnerWithFirstParamNull() throws Exception { ClassWithInnerMembers outerClass = new ClassWithInnerMembers(); MyInnerClassWithPublicConstructorWithMultArgs mockMyInnerClassWithPublicConstructorWithMultArgs = mock(MyInnerClassWithPublicConstructorWithMultArgs.class); MyInnerClassWithProtectedConstructorWithMultArgs mockMyInnerClassWithProtectedConstructorWithMultArgs = mock(MyInnerClassWithProtectedConstructorWithMultArgs.class); MyInnerClassWithPackageConstructorWithMultArgs mockMyInnerClassWithPackageConstructorWithMultArgs = mock(MyInnerClassWithPackageConstructorWithMultArgs.class); MyInnerClassWithPrivateConstructorWithMultArgs mockMyInnerClassWithPrivateConstructorWithMultArgs = mock(MyInnerClassWithPrivateConstructorWithMultArgs.class); whenNew(MyInnerClassWithPublicConstructorWithMultArgs.class) .withArguments(null, "2", "3").thenReturn(mockMyInnerClassWithPublicConstructorWithMultArgs); whenNew(MyInnerClassWithProtectedConstructorWithMultArgs.class) .withArguments(null, "2", "3").thenReturn(mockMyInnerClassWithProtectedConstructorWithMultArgs); whenNew(MyInnerClassWithPackageConstructorWithMultArgs.class) .withArguments(null, "2", "3").thenReturn(mockMyInnerClassWithPackageConstructorWithMultArgs); whenNew(MyInnerClassWithPrivateConstructorWithMultArgs.class) .withArguments(null, "2", "3").thenReturn(mockMyInnerClassWithPrivateConstructorWithMultArgs); assertEquals("Expected and actual did not match", mockMyInnerClassWithPublicConstructorWithMultArgs, outerClass.makeMyInnerClassWithPublicConstructorWithMultArgs(null, "2", "3")); assertEquals("Expected and actual did not match", mockMyInnerClassWithProtectedConstructorWithMultArgs, outerClass.makeMyInnerClassWithProtectedConstructorWithMultArgs(null, "2", "3")); assertEquals("Expected and actual did not match", mockMyInnerClassWithPackageConstructorWithMultArgs, outerClass.makeMyInnerClassWithPackageConstructorWithMultArgs(null, "2", "3")); assertEquals("Expected and actual did not match", mockMyInnerClassWithPrivateConstructorWithMultArgs, outerClass.makeMyInnerClassWithPrivateConstructorWithMultArgs(null, "2", "3")); } @Test public void testNewInnerWithLastParamNull() throws Exception { ClassWithInnerMembers outerClass = new ClassWithInnerMembers(); MyInnerClassWithPublicConstructorWithMultArgs mockMyInnerClassWithPublicConstructorWithMultArgs = mock(MyInnerClassWithPublicConstructorWithMultArgs.class); MyInnerClassWithProtectedConstructorWithMultArgs mockMyInnerClassWithProtectedConstructorWithMultArgs = mock(MyInnerClassWithProtectedConstructorWithMultArgs.class); MyInnerClassWithPackageConstructorWithMultArgs mockMyInnerClassWithPackageConstructorWithMultArgs = mock(MyInnerClassWithPackageConstructorWithMultArgs.class); MyInnerClassWithPrivateConstructorWithMultArgs mockMyInnerClassWithPrivateConstructorWithMultArgs = mock(MyInnerClassWithPrivateConstructorWithMultArgs.class); whenNew(MyInnerClassWithPublicConstructorWithMultArgs.class) .withArguments("1", "2", null).thenReturn(mockMyInnerClassWithPublicConstructorWithMultArgs); whenNew(MyInnerClassWithProtectedConstructorWithMultArgs.class) .withArguments("1", "2", null).thenReturn(mockMyInnerClassWithProtectedConstructorWithMultArgs); whenNew(MyInnerClassWithPackageConstructorWithMultArgs.class) .withArguments("1", "2", null).thenReturn(mockMyInnerClassWithPackageConstructorWithMultArgs); whenNew(MyInnerClassWithPrivateConstructorWithMultArgs.class) .withArguments("1", "2", null).thenReturn(mockMyInnerClassWithPrivateConstructorWithMultArgs); assertEquals("Expected and actual did not match", mockMyInnerClassWithPublicConstructorWithMultArgs, outerClass.makeMyInnerClassWithPublicConstructorWithMultArgs("1", "2", null)); assertEquals("Expected and actual did not match", mockMyInnerClassWithProtectedConstructorWithMultArgs, outerClass.makeMyInnerClassWithProtectedConstructorWithMultArgs("1", "2", null)); assertEquals("Expected and actual did not match", mockMyInnerClassWithPackageConstructorWithMultArgs, outerClass.makeMyInnerClassWithPackageConstructorWithMultArgs("1", "2", null)); assertEquals("Expected and actual did not match", mockMyInnerClassWithPrivateConstructorWithMultArgs, outerClass.makeMyInnerClassWithPrivateConstructorWithMultArgs("1", "2", null)); } @Test public void testNewWithCheckedException() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); final String expectedFailMessage = "testing checked exception"; whenNew(MyClass.class).withNoArguments().thenThrow(new IOException(expectedFailMessage)); try { tested.throwExceptionAndWrapInRunTimeWhenInvoction(); fail("Should throw a checked Exception!"); } catch (RuntimeException e) { assertTrue(e.getCause() instanceof IOException); assertEquals(expectedFailMessage, e.getMessage()); } verifyNew(MyClass.class).withNoArguments(); } @Test public void testGetMessage() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock = mock(MyClass.class); whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock); String expected = "Hello altered World"; when(myClassMock.getMessage()).thenReturn("Hello altered World"); String actual = tested.getMessage(); verify(myClassMock).getMessage(); verifyNew(MyClass.class).withNoArguments(); assertEquals("Expected and actual did not match", expected, actual); } @Test public void testGetMessageWithArgument() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock = mock(MyClass.class); whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock); String expected = "Hello altered World"; when(myClassMock.getMessage("test")).thenReturn("Hello altered World"); String actual = tested.getMessageWithArgument(); verify(myClassMock).getMessage("test"); verifyNew(MyClass.class).withNoArguments(); assertEquals("Expected and actual did not match", expected, actual); } @Test public void testInvokeVoidMethod() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock = mock(MyClass.class); whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock); doNothing().when(myClassMock).voidMethod(); tested.invokeVoidMethod(); verify(myClassMock).voidMethod(); verifyNew(MyClass.class).withNoArguments(); } @Test public void testNewWithRuntimeException() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); final String expectedFailMessage = "testing"; whenNew(MyClass.class).withNoArguments().thenThrow(new RuntimeException(expectedFailMessage)); try { tested.throwExceptionWhenInvoction(); fail("Should throw RuntimeException!"); } catch (RuntimeException e) { assertEquals(expectedFailMessage, e.getMessage()); } verifyNew(MyClass.class).withNoArguments(); } @Test public void testMultipleNew() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock = mock(MyClass.class); whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock); when(myClassMock.getMessage()).thenReturn("Hello"); final String actual = tested.multipleNew(); verify(myClassMock, times(2)).getMessage(); verifyNew(MyClass.class, times(2)).withNoArguments(); assertEquals("HelloHello", actual); } @Test public void testSimpleMultipleNew() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock = mock(MyClass.class); whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock); tested.simpleMultipleNew(); verifyNew(MyClass.class, times(3)).withNoArguments(); } @Test public void testSimpleMultipleNew_tooManyTimesExpected() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock = mock(MyClass.class); whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock); tested.simpleMultipleNew(); try { verifyNew(MyClass.class, times(4)).withNoArguments(); fail("Should throw AssertionError."); } catch (AssertionError e) { assertEquals("samples.newmocking.MyClass();\nWanted 4 times but was 3 times.", e.getMessage()); } } @Test public void testSimpleMultipleNew_tooFewTimesExpected() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock1 = mock(MyClass.class); whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock1); tested.simpleMultipleNew(); try { verifyNew(MyClass.class, times(1)).withNoArguments(); fail("Should throw AssertionError."); } catch (AssertionError e) { assertEquals("samples.newmocking.MyClass();\nWanted 1 time but was 3 times.", e.getMessage()); } } /** * Verifies that the issue * http://code.google.com/p/powermock/issues/detail?id=10 is solved. */ @Test public void testSimpleMultipleNewPrivate_tooFewTimesExpected() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock1 = mock(MyClass.class); whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock1); Whitebox.invokeMethod(tested, "simpleMultipleNewPrivate"); try { verifyNew(MyClass.class, times(2)).withNoArguments(); fail("Should throw AssertionError."); } catch (AssertionError e) { assertEquals("samples.newmocking.MyClass();\nWanted 2 times but was 3 times.", e.getMessage()); } } @Test public void testSimpleMultipleNewPrivate_ok() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock1 = mock(MyClass.class); whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock1); Whitebox.invokeMethod(tested, "simpleMultipleNewPrivate"); verifyNew(MyClass.class, times(3)).withNoArguments(); } @Test public void testSimpleSingleNew_withOnce() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock1 = mock(MyClass.class); whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock1); tested.simpleSingleNew(); verifyNew(MyClass.class).withNoArguments(); } @Test public void testSimpleSingleNew_withAtLeastOnce() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock1 = mock(MyClass.class); whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock1); tested.simpleSingleNew(); verifyNew(MyClass.class, atLeastOnce()).withNoArguments(); } @Test public void testSimpleMultipleNew_withAtLeastOnce() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock1 = mock(MyClass.class); whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock1); tested.simpleMultipleNew(); verifyNew(MyClass.class, atLeastOnce()).withNoArguments(); } // @Test public void testAlternativeFlow() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); whenNew(DataInputStream.class).withArguments(null).thenThrow(new RuntimeException("error")); InputStream stream = tested.alternativePath(); verifyNew(DataInputStream.class).withArguments(null); assertNotNull("The returned inputstream should not be null.", stream); assertTrue("The returned inputstream should be an instance of ByteArrayInputStream.", stream instanceof ByteArrayInputStream); } @Test public void testSimpleMultipleNewPrivate_tooManyTimesExpected() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock1 = mock(MyClass.class); whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock1); Whitebox.invokeMethod(tested, "simpleMultipleNewPrivate"); try { verifyNew(MyClass.class, times(4)).withNoArguments(); fail("Should throw an exception!."); } catch (AssertionError e) { assertEquals("samples.newmocking.MyClass();\nWanted 4 times but was 3 times.", e.getMessage()); } } @Test public void testNewWithArguments() throws Exception { final int numberOfTimes = 2; final String expected = "used"; ExpectNewDemo tested = new ExpectNewDemo(); ExpectNewServiceUser expectNewServiceImplMock = mock(ExpectNewServiceUser.class); Service serviceMock = mock(Service.class); whenNew(ExpectNewServiceUser.class).withArguments(serviceMock, numberOfTimes).thenReturn( expectNewServiceImplMock); when(expectNewServiceImplMock.useService()).thenReturn(expected); assertEquals(expected, tested.newWithArguments(serviceMock, numberOfTimes)); verifyNew(ExpectNewServiceUser.class).withArguments(serviceMock, numberOfTimes); } @Test public void testNewWithParameterTypesAndArguments() throws Exception { final int numberOfTimes = 2; final String expected = "used"; ExpectNewDemo tested = new ExpectNewDemo(); ExpectNewServiceUser expectNewServiceImplMock = mock(ExpectNewServiceUser.class); Service serviceMock = mock(Service.class); whenNew(ExpectNewServiceUser.class).withParameterTypes(Service.class, int.class) .withArguments(serviceMock, numberOfTimes) .thenReturn(expectNewServiceImplMock); when(expectNewServiceImplMock.useService()).thenReturn(expected); assertEquals(expected, tested.newWithArguments(serviceMock, numberOfTimes)); verifyNew(ExpectNewServiceUser.class).withArguments(serviceMock, numberOfTimes); } @Test public void testNewWithConstructorUsingParameterTypesAndArguments() throws Exception { final int numberOfTimes = 2; final String expected = "used"; ExpectNewDemo tested = new ExpectNewDemo(); ExpectNewServiceUser expectNewServiceImplMock = mock(ExpectNewServiceUser.class); Service serviceMock = mock(Service.class); whenNew(constructor(ExpectNewServiceUser.class, Service.class, int.class)).withArguments(serviceMock, numberOfTimes) .thenReturn(expectNewServiceImplMock); when(expectNewServiceImplMock.useService()).thenReturn(expected); assertEquals(expected, tested.newWithArguments(serviceMock, numberOfTimes)); verifyNew(ExpectNewServiceUser.class).withArguments(serviceMock, numberOfTimes); } @Test public void testNewUsingConstructorWithArguments() throws Exception { final int numberOfTimes = 2; final String expected = "used"; ExpectNewDemo tested = new ExpectNewDemo(); ExpectNewServiceUser expectNewServiceImplMock = mock(ExpectNewServiceUser.class); Service serviceMock = mock(Service.class); whenNew(constructor(ExpectNewServiceUser.class)).withArguments(serviceMock, numberOfTimes).thenReturn( expectNewServiceImplMock); when(expectNewServiceImplMock.useService()).thenReturn(expected); assertEquals(expected, tested.newWithArguments(serviceMock, numberOfTimes)); verifyNew(ExpectNewServiceUser.class).withArguments(serviceMock, numberOfTimes); } @Test public void testNewWithVarArgs() throws Exception { final String firstString = "hello"; final String secondString = "world"; ExpectNewDemo tested = new ExpectNewDemo(); VarArgsConstructorDemo varArgsConstructorDemoMock = mock(VarArgsConstructorDemo.class); whenNew(VarArgsConstructorDemo.class).withArguments(firstString, secondString).thenReturn( varArgsConstructorDemoMock); when(varArgsConstructorDemoMock.getAllMessages()).thenReturn(new String[]{firstString, secondString}); String[] varArgs = tested.newVarArgs(firstString, secondString); assertEquals(2, varArgs.length); assertEquals(firstString, varArgs[0]); assertEquals(secondString, varArgs[1]); verifyNew(VarArgsConstructorDemo.class).withArguments(firstString, secondString); } @Test public void testNewWhenTheExpectedConstructorIsNotFound() throws Exception { final Object object = new Object(); try { whenNew(VarArgsConstructorDemo.class).withArguments(object); fail("Should throw ConstructorNotFoundException!"); } catch (ConstructorNotFoundException e) { assertEquals("No constructor found in class '" + VarArgsConstructorDemo.class.getName() + "' with parameter types: [ " + object.getClass().getName() + " ].", e.getMessage()); } } @Test public void testNewWithVarArgsConstructorWhenOneArgumentIsOfASubType() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); Service serviceMock = mock(Service.class); VarArgsConstructorDemo varArgsConstructorDemoMock = mock(VarArgsConstructorDemo.class); final Service serviceSubTypeInstance = new Service() { public String getServiceMessage() { return "message"; } }; whenNew(VarArgsConstructorDemo.class).withArguments(serviceSubTypeInstance, serviceMock).thenReturn( varArgsConstructorDemoMock); when(varArgsConstructorDemoMock.getAllServices()).thenReturn(new Service[]{serviceMock}); Service[] varArgs = tested.newVarArgs(serviceSubTypeInstance, serviceMock); assertEquals(1, varArgs.length); assertSame(serviceMock, varArgs[0]); verifyNew(VarArgsConstructorDemo.class).withArguments(serviceSubTypeInstance, serviceMock); } @Test public void testNewWithArrayVarArgs() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); VarArgsConstructorDemo varArgsConstructorDemoMock = mock(VarArgsConstructorDemo.class); final byte[] byteArrayOne = new byte[]{42}; final byte[] byteArrayTwo = new byte[]{17}; whenNew(VarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo).thenReturn( varArgsConstructorDemoMock); when(varArgsConstructorDemoMock.getByteArrays()).thenReturn(new byte[][]{byteArrayOne}); byte[][] varArgs = tested.newVarArgs(byteArrayOne, byteArrayTwo); assertEquals(1, varArgs.length); assertSame(byteArrayOne, varArgs[0]); verifyNew(VarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo); } @Test public void testNewWithArrayVarArgsAndMatchers() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); VarArgsConstructorDemo varArgsConstructorDemoMock = mock(VarArgsConstructorDemo.class); final byte[] byteArrayOne = new byte[]{42}; final byte[] byteArrayTwo = new byte[]{17}; whenNew(VarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo).thenReturn( varArgsConstructorDemoMock); when(varArgsConstructorDemoMock.getByteArrays()).thenReturn(new byte[][]{byteArrayOne}); byte[][] varArgs = tested.newVarArgsWithMatchers(); assertEquals(1, varArgs.length); assertSame(byteArrayOne, varArgs[0]); verifyNew(VarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo); } @Test public void testNewWithArrayVarArgsWhenFirstArgumentIsNullAndSubseqentArgumentsAreNotNull() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); VarArgsConstructorDemo varArgsConstructorDemoMock = mock(VarArgsConstructorDemo.class); final byte[] byteArrayOne = null; final byte[] byteArrayTwo = new byte[]{17}; whenNew(VarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo).thenReturn( varArgsConstructorDemoMock); when(varArgsConstructorDemoMock.getByteArrays()).thenReturn(new byte[][]{byteArrayTwo}); byte[][] varArgs = tested.newVarArgs(byteArrayOne, byteArrayTwo); assertEquals(1, varArgs.length); assertSame(byteArrayTwo, varArgs[0]); verifyNew(VarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo); } @Test public void testNewWithArrayVarArgsWhenFirstArgumentIsNotNullButSubseqentArgumentsAreNull() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); VarArgsConstructorDemo varArgsConstructorDemoMock = mock(VarArgsConstructorDemo.class); final byte[] byteArrayOne = new byte[]{42}; final byte[] byteArrayTwo = null; whenNew(VarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo).thenReturn( varArgsConstructorDemoMock); when(varArgsConstructorDemoMock.getByteArrays()).thenReturn(new byte[][]{byteArrayOne}); byte[][] varArgs = tested.newVarArgs(byteArrayOne, byteArrayTwo); assertEquals(1, varArgs.length); assertSame(byteArrayOne, varArgs[0]); verifyNew(VarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo); } @Test public void testNewWithArrayVarArgsWhenFirstArgumentIsNullSecondArgumentIsNotNullAndThirdArgumentIsNull() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); VarArgsConstructorDemo varArgsConstructorDemoMock = mock(VarArgsConstructorDemo.class); final byte[] byteArrayOne = null; final byte[] byteArrayTwo = new byte[]{42}; final byte[] byteArrayThree = null; whenNew(VarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo, byteArrayThree).thenReturn( varArgsConstructorDemoMock); when(varArgsConstructorDemoMock.getByteArrays()).thenReturn(new byte[][]{byteArrayTwo}); byte[][] varArgs = tested.newVarArgs(byteArrayOne, byteArrayTwo, byteArrayThree); assertEquals(1, varArgs.length); assertSame(byteArrayTwo, varArgs[0]); verifyNew(VarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo, byteArrayThree); } @Test public void testNewWithArrayVarArgsWhenAllArgumentsAreNullAndOverloadedVarArgsConstructors() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); VarArgsConstructorDemo varArgsConstructorDemoMock = mock(VarArgsConstructorDemo.class); final byte[] byteArrayOne = null; final byte[] byteArrayTwo = null; whenNew(VarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo).thenReturn( varArgsConstructorDemoMock); when(varArgsConstructorDemoMock.getByteArrays()).thenReturn(new byte[][]{ byteArrayTwo}); byte[][] varArgs = tested.newVarArgs(byteArrayOne, byteArrayTwo); assertEquals(1, varArgs.length); assertSame(byteArrayTwo, varArgs[0]); verifyNew(VarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo); } @Test public void testNewWithArrayVarArgsWhenAllArgumentsAreNull() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); SimpleVarArgsConstructorDemo varArgsConstructorDemoMock = mock(SimpleVarArgsConstructorDemo.class); final byte[] byteArrayOne = null; final byte[] byteArrayTwo = null; whenNew(SimpleVarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo).thenReturn( varArgsConstructorDemoMock); when(varArgsConstructorDemoMock.getByteArrays()).thenReturn(new byte[][]{byteArrayTwo}); byte[][] varArgs = tested.newSimpleVarArgs(byteArrayOne, byteArrayTwo); assertEquals(1, varArgs.length); assertSame(byteArrayTwo, varArgs[0]); verifyNew(SimpleVarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo); } @Test(expected = NullPointerException.class) public void testNewWithWrongArgument() throws Exception { final int numberOfTimes = 2; final String expected = "used"; ExpectNewDemo tested = new ExpectNewDemo(); ExpectNewServiceUser expectNewServiceImplMock = mock(ExpectNewServiceUser.class); Service serviceMock = mock(Service.class); whenNew(ExpectNewServiceUser.class).withArguments(serviceMock, numberOfTimes).thenReturn( expectNewServiceImplMock); when(expectNewServiceImplMock.useService()).thenReturn(expected); assertEquals(expected, tested.newWithWrongArguments(serviceMock, numberOfTimes)); verifyNew(ExpectNewServiceUser.class).withArguments(serviceMock, numberOfTimes); /* * Should throw NPE because the default behavior of Mockito when a * something isn't expected is to return a default value. In this case * whenConstructionOf * (ExpectNewServiceUser.class).withArguments(serviceMock, * numberOfTimes) is the wrong expectation and thus null is returned * from the substitute mock which is the correct behavior. */ fail("Should throw NPE!"); } @Test public void testExpectNewButNoNewCallWasMade() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock1 = mock(MyClass.class); whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock1); tested.makeDate(); try { verifyNew(MyClass.class).withNoArguments(); fail("Should throw AssertionError!"); } catch (AssertionError e) { assertEquals( "Wanted but not invoked samples.newmocking.MyClass();\nActually, there were zero interactions with this mock.", e.getMessage()); } } @Test public void whenNewSupportsVarArgsAsSecondParameter() throws Exception { final int one = 1; final int two = 2; final float myFloat = 3.0f; ExpectNewDemo tested = new ExpectNewDemo(); VarArgsConstructorDemo varArgsConstructorDemoMock = mock(VarArgsConstructorDemo.class); whenNew(VarArgsConstructorDemo.class).withArguments(myFloat, one, two).thenReturn(varArgsConstructorDemoMock); when(varArgsConstructorDemoMock.getInts()).thenReturn(new int[] { one, two}); int[] varArgs = tested.newVarArgs(myFloat, one, two); assertEquals(2, varArgs.length); assertEquals(one, varArgs[0]); assertEquals(two, varArgs[1]); verifyNew(VarArgsConstructorDemo.class).withArguments(myFloat, one, two); } @Test public void whenNewAnyArgumentsWorksInClassesWithSingleCtor() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock = mock(MyClass.class); whenNew(MyClass.class).withAnyArguments().thenReturn(myClassMock); when(myClassMock.getMessage()).thenReturn("Hello"); final String actual = tested.multipleNew(); verify(myClassMock, times(2)).getMessage(); verifyNew(MyClass.class, times(2)).withNoArguments(); assertEquals("HelloHello", actual); } @Test public void whenNewAnyArgumentsWorksInClassesWithMultipleCtors() throws Exception { ExpectNewWithMultipleCtorDemo expectNewWithMultipleCtorDemoMock = mock(ExpectNewWithMultipleCtorDemo.class); Service serviceMock = mock(Service.class); whenNew(ExpectNewWithMultipleCtorDemo.class).withAnyArguments().thenReturn(expectNewWithMultipleCtorDemoMock); when(expectNewWithMultipleCtorDemoMock.useService()).thenReturn("message"); // When final ExpectNewWithMultipleCtorDemo expectNewWithMultipleCtorDemo = new ExpectNewWithMultipleCtorDemo(serviceMock); final String message1 = expectNewWithMultipleCtorDemo.useService(); final ExpectNewWithMultipleCtorDemo expectNewWithMultipleCtorDemo1 = new ExpectNewWithMultipleCtorDemo(serviceMock, 5); final String message2 = expectNewWithMultipleCtorDemo1.useService(); assertEquals(message1, "message"); assertEquals(message2, "message"); } @Test public void canDefineSeveralMockResultForNew() throws Exception { final Target expectedTarget = new Target(UNKNOWN_TARGET_NAME,UNKNOWN_TARGET_ID); whenNew(Target.class).withArguments(eq(TARGET_NAME),eq(TARGET_ID)).thenThrow(new CreationException()); whenNew(Target.class).withArguments(eq("Unknown"), eq(-1)).thenReturn(expectedTarget); Target actualTarget = new ExpectNewDemo().createTarget(new ITarget() { @Override public int getId() { return TARGET_ID; } @Override public String getName() { return TARGET_NAME; } }); assertThat(actualTarget).isEqualToComparingFieldByField(expectedTarget); } @Test public void multiConstructorMatching() throws Exception { MultiConstructor expectedObject = new MultiConstructor("only"); whenNew(MultiConstructor.class).withAnyArguments().thenReturn(expectedObject); MultiConstructor actualObject = new MultiConstructor(null); assertNotNull("withAnyArguments did not match constructor(String=null)", actualObject); assertEquals("only", actualObject.getFirst()); actualObject = new MultiConstructor("first", null); assertNotNull("withAnyArguments did not match constructor(String, String=null)", actualObject); assertEquals("only", actualObject.getFirst()); actualObject = new MultiConstructor("first", null, true); assertNotNull("withAnyArguments did not match constructor(Runnable=null, boolean, Object)", actualObject); assertEquals("only", actualObject.getFirst()); } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/whennew/WhenNewCases.java.orig ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.whennew; import org.junit.Rule; import org.junit.Test; <<<<<<< HEAD:modules/module-test/mockito/junit4/src/test/java/samples/powermockito/junit4/whennew/WhenNewCases.java import org.junit.rules.ExpectedException; ======= import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner; >>>>>>> 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 import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunnerDelegate; import org.powermock.reflect.Whitebox; import org.powermock.reflect.exceptions.ConstructorNotFoundException; import samples.Service; import samples.expectnew.CreationException; import samples.expectnew.ExpectNewDemo; import samples.expectnew.ExpectNewServiceUser; import samples.expectnew.ExpectNewWithMultipleCtorDemo; import samples.expectnew.ITarget; import samples.expectnew.SimpleVarArgsConstructorDemo; import samples.expectnew.Target; import samples.expectnew.VarArgsConstructorDemo; import samples.newmocking.MyClass; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.powermock.api.mockito.PowerMockito.mock; import static org.powermock.api.mockito.PowerMockito.verifyNew; import static org.powermock.api.mockito.PowerMockito.when; import static org.powermock.api.mockito.PowerMockito.whenNew; import static org.powermock.api.support.membermodification.MemberMatcher.constructor; /** * Test class to demonstrate new instance mocking using whenConstructionOf(..). */ <<<<<<< HEAD:modules/module-test/mockito/junit4/src/test/java/samples/powermockito/junit4/whennew/WhenNewCases.java @PrepareForTest({MyClass.class, ExpectNewDemo.class, DataInputStream.class, WhenNewCases.class, Target.class}) ======= @RunWith(PowerMockRunner.class) @PowerMockRunnerDelegate(MockitoJUnitRunner.class) @PrepareForTest({MyClass.class, ExpectNewDemo.class, DataInputStream.class}) >>>>>>> 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 public class WhenNewCases { public static final String TARGET_NAME = "MyTarget"; public static final int TARGET_ID = 1; public static final String UNKNOWN_TARGET_NAME = "Unknown2"; public static final int UNKNOWN_TARGET_ID = -11; @Rule public ExpectedException expectedException = ExpectedException.none(); @Test public void testNewWithCheckedException() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); final String expectedFailMessage = "testing checked exception"; whenNew(MyClass.class).withNoArguments().thenThrow(new IOException(expectedFailMessage)); try { tested.throwExceptionAndWrapInRunTimeWhenInvoction(); fail("Should throw a checked Exception!"); } catch (RuntimeException e) { assertTrue(e.getCause() instanceof IOException); assertEquals(expectedFailMessage, e.getMessage()); } verifyNew(MyClass.class).withNoArguments(); } @Test public void testGetMessage() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock = mock(MyClass.class); whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock); String expected = "Hello altered World"; when(myClassMock.getMessage()).thenReturn("Hello altered World"); String actual = tested.getMessage(); verify(myClassMock).getMessage(); verifyNew(MyClass.class).withNoArguments(); assertEquals("Expected and actual did not match", expected, actual); } @Test public void testGetMessageWithArgument() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock = mock(MyClass.class); whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock); String expected = "Hello altered World"; when(myClassMock.getMessage("test")).thenReturn("Hello altered World"); String actual = tested.getMessageWithArgument(); verify(myClassMock).getMessage("test"); verifyNew(MyClass.class).withNoArguments(); assertEquals("Expected and actual did not match", expected, actual); } @Test public void testInvokeVoidMethod() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock = mock(MyClass.class); whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock); doNothing().when(myClassMock).voidMethod(); tested.invokeVoidMethod(); verify(myClassMock).voidMethod(); verifyNew(MyClass.class).withNoArguments(); } @Test public void testNewWithRuntimeException() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); final String expectedFailMessage = "testing"; whenNew(MyClass.class).withNoArguments().thenThrow(new RuntimeException(expectedFailMessage)); try { tested.throwExceptionWhenInvoction(); fail("Should throw RuntimeException!"); } catch (RuntimeException e) { assertEquals(expectedFailMessage, e.getMessage()); } verifyNew(MyClass.class).withNoArguments(); } @Test public void testMultipleNew() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock = mock(MyClass.class); whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock); when(myClassMock.getMessage()).thenReturn("Hello"); final String actual = tested.multipleNew(); verify(myClassMock, times(2)).getMessage(); verifyNew(MyClass.class, times(2)).withNoArguments(); assertEquals("HelloHello", actual); } @Test public void testSimpleMultipleNew() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock = mock(MyClass.class); whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock); tested.simpleMultipleNew(); verifyNew(MyClass.class, times(3)).withNoArguments(); } @Test public void testSimpleMultipleNew_tooManyTimesExpected() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock = mock(MyClass.class); whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock); tested.simpleMultipleNew(); try { verifyNew(MyClass.class, times(4)).withNoArguments(); fail("Should throw AssertionError."); } catch (AssertionError e) { assertEquals("samples.newmocking.MyClass();\nWanted 4 times but was 3 times.", e.getMessage()); } } @Test public void testSimpleMultipleNew_tooFewTimesExpected() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock1 = mock(MyClass.class); whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock1); tested.simpleMultipleNew(); try { verifyNew(MyClass.class, times(1)).withNoArguments(); fail("Should throw AssertionError."); } catch (AssertionError e) { assertEquals("samples.newmocking.MyClass();\nWanted 1 time but was 3 times.", e.getMessage()); } } /** * Verifies that the issue * http://code.google.com/p/powermock/issues/detail?id=10 is solved. */ @Test public void testSimpleMultipleNewPrivate_tooFewTimesExpected() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock1 = mock(MyClass.class); whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock1); Whitebox.invokeMethod(tested, "simpleMultipleNewPrivate"); try { verifyNew(MyClass.class, times(2)).withNoArguments(); fail("Should throw AssertionError."); } catch (AssertionError e) { assertEquals("samples.newmocking.MyClass();\nWanted 2 times but was 3 times.", e.getMessage()); } } @Test public void testSimpleMultipleNewPrivate_ok() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock1 = mock(MyClass.class); whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock1); Whitebox.invokeMethod(tested, "simpleMultipleNewPrivate"); verifyNew(MyClass.class, times(3)).withNoArguments(); } @Test public void testSimpleSingleNew_withOnce() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock1 = mock(MyClass.class); whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock1); tested.simpleSingleNew(); verifyNew(MyClass.class).withNoArguments(); } @Test public void testSimpleSingleNew_withAtLeastOnce() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock1 = mock(MyClass.class); whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock1); tested.simpleSingleNew(); verifyNew(MyClass.class, atLeastOnce()).withNoArguments(); } @Test public void testSimpleMultipleNew_withAtLeastOnce() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock1 = mock(MyClass.class); whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock1); tested.simpleMultipleNew(); verifyNew(MyClass.class, atLeastOnce()).withNoArguments(); } // @Test public void testAlternativeFlow() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); whenNew(DataInputStream.class).withArguments(null).thenThrow(new RuntimeException("error")); InputStream stream = tested.alternativePath(); verifyNew(DataInputStream.class).withArguments(null); assertNotNull("The returned inputstream should not be null.", stream); assertTrue("The returned inputstream should be an instance of ByteArrayInputStream.", stream instanceof ByteArrayInputStream); } @Test public void testSimpleMultipleNewPrivate_tooManyTimesExpected() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock1 = mock(MyClass.class); whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock1); Whitebox.invokeMethod(tested, "simpleMultipleNewPrivate"); try { verifyNew(MyClass.class, times(4)).withNoArguments(); fail("Should throw an exception!."); } catch (AssertionError e) { assertEquals("samples.newmocking.MyClass();\nWanted 4 times but was 3 times.", e.getMessage()); } } @Test public void testNewWithArguments() throws Exception { final int numberOfTimes = 2; final String expected = "used"; ExpectNewDemo tested = new ExpectNewDemo(); ExpectNewServiceUser expectNewServiceImplMock = mock(ExpectNewServiceUser.class); Service serviceMock = mock(Service.class); whenNew(ExpectNewServiceUser.class).withArguments(serviceMock, numberOfTimes).thenReturn( expectNewServiceImplMock); when(expectNewServiceImplMock.useService()).thenReturn(expected); assertEquals(expected, tested.newWithArguments(serviceMock, numberOfTimes)); verifyNew(ExpectNewServiceUser.class).withArguments(serviceMock, numberOfTimes); } @Test public void testNewWithParameterTypesAndArguments() throws Exception { final int numberOfTimes = 2; final String expected = "used"; ExpectNewDemo tested = new ExpectNewDemo(); ExpectNewServiceUser expectNewServiceImplMock = mock(ExpectNewServiceUser.class); Service serviceMock = mock(Service.class); whenNew(ExpectNewServiceUser.class).withParameterTypes(Service.class, int.class) .withArguments(serviceMock, numberOfTimes) .thenReturn(expectNewServiceImplMock); when(expectNewServiceImplMock.useService()).thenReturn(expected); assertEquals(expected, tested.newWithArguments(serviceMock, numberOfTimes)); verifyNew(ExpectNewServiceUser.class).withArguments(serviceMock, numberOfTimes); } @Test public void testNewWithConstructorUsingParameterTypesAndArguments() throws Exception { final int numberOfTimes = 2; final String expected = "used"; ExpectNewDemo tested = new ExpectNewDemo(); ExpectNewServiceUser expectNewServiceImplMock = mock(ExpectNewServiceUser.class); Service serviceMock = mock(Service.class); whenNew(constructor(ExpectNewServiceUser.class, Service.class, int.class)).withArguments(serviceMock, numberOfTimes) .thenReturn(expectNewServiceImplMock); when(expectNewServiceImplMock.useService()).thenReturn(expected); assertEquals(expected, tested.newWithArguments(serviceMock, numberOfTimes)); verifyNew(ExpectNewServiceUser.class).withArguments(serviceMock, numberOfTimes); } @Test public void testNewUsingConstructorWithArguments() throws Exception { final int numberOfTimes = 2; final String expected = "used"; ExpectNewDemo tested = new ExpectNewDemo(); ExpectNewServiceUser expectNewServiceImplMock = mock(ExpectNewServiceUser.class); Service serviceMock = mock(Service.class); whenNew(constructor(ExpectNewServiceUser.class)).withArguments(serviceMock, numberOfTimes).thenReturn( expectNewServiceImplMock); when(expectNewServiceImplMock.useService()).thenReturn(expected); assertEquals(expected, tested.newWithArguments(serviceMock, numberOfTimes)); verifyNew(ExpectNewServiceUser.class).withArguments(serviceMock, numberOfTimes); } @Test public void testNewWithVarArgs() throws Exception { final String firstString = "hello"; final String secondString = "world"; ExpectNewDemo tested = new ExpectNewDemo(); VarArgsConstructorDemo varArgsConstructorDemoMock = mock(VarArgsConstructorDemo.class); whenNew(VarArgsConstructorDemo.class).withArguments(firstString, secondString).thenReturn( varArgsConstructorDemoMock); when(varArgsConstructorDemoMock.getAllMessages()).thenReturn(new String[]{firstString, secondString}); String[] varArgs = tested.newVarArgs(firstString, secondString); assertEquals(2, varArgs.length); assertEquals(firstString, varArgs[0]); assertEquals(secondString, varArgs[1]); verifyNew(VarArgsConstructorDemo.class).withArguments(firstString, secondString); } @Test public void testNewWhenTheExpectedConstructorIsNotFound() throws Exception { final Object object = new Object(); try { whenNew(VarArgsConstructorDemo.class).withArguments(object); fail("Should throw ConstructorNotFoundException!"); } catch (ConstructorNotFoundException e) { assertEquals("No constructor found in class '" + VarArgsConstructorDemo.class.getName() + "' with parameter types: [ " + object.getClass().getName() + " ].", e.getMessage()); } } @Test public void testNewWithVarArgsConstructorWhenOneArgumentIsOfASubType() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); Service serviceMock = mock(Service.class); VarArgsConstructorDemo varArgsConstructorDemoMock = mock(VarArgsConstructorDemo.class); final Service serviceSubTypeInstance = new Service() { public String getServiceMessage() { return "message"; } }; whenNew(VarArgsConstructorDemo.class).withArguments(serviceSubTypeInstance, serviceMock).thenReturn( varArgsConstructorDemoMock); when(varArgsConstructorDemoMock.getAllServices()).thenReturn(new Service[]{serviceMock}); Service[] varArgs = tested.newVarArgs(serviceSubTypeInstance, serviceMock); assertEquals(1, varArgs.length); assertSame(serviceMock, varArgs[0]); verifyNew(VarArgsConstructorDemo.class).withArguments(serviceSubTypeInstance, serviceMock); } @Test public void testNewWithArrayVarArgs() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); VarArgsConstructorDemo varArgsConstructorDemoMock = mock(VarArgsConstructorDemo.class); final byte[] byteArrayOne = new byte[]{42}; final byte[] byteArrayTwo = new byte[]{17}; whenNew(VarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo).thenReturn( varArgsConstructorDemoMock); when(varArgsConstructorDemoMock.getByteArrays()).thenReturn(new byte[][]{byteArrayOne}); byte[][] varArgs = tested.newVarArgs(byteArrayOne, byteArrayTwo); assertEquals(1, varArgs.length); assertSame(byteArrayOne, varArgs[0]); verifyNew(VarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo); } @Test public void testNewWithArrayVarArgsAndMatchers() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); VarArgsConstructorDemo varArgsConstructorDemoMock = mock(VarArgsConstructorDemo.class); final byte[] byteArrayOne = new byte[]{42}; final byte[] byteArrayTwo = new byte[]{17}; whenNew(VarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo).thenReturn( varArgsConstructorDemoMock); when(varArgsConstructorDemoMock.getByteArrays()).thenReturn(new byte[][]{byteArrayOne}); byte[][] varArgs = tested.newVarArgsWithMatchers(); assertEquals(1, varArgs.length); assertSame(byteArrayOne, varArgs[0]); verifyNew(VarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo); } @Test public void testNewWithArrayVarArgsWhenFirstArgumentIsNullAndSubseqentArgumentsAreNotNull() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); VarArgsConstructorDemo varArgsConstructorDemoMock = mock(VarArgsConstructorDemo.class); final byte[] byteArrayOne = null; final byte[] byteArrayTwo = new byte[]{17}; whenNew(VarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo).thenReturn( varArgsConstructorDemoMock); when(varArgsConstructorDemoMock.getByteArrays()).thenReturn(new byte[][]{byteArrayTwo}); byte[][] varArgs = tested.newVarArgs(byteArrayOne, byteArrayTwo); assertEquals(1, varArgs.length); assertSame(byteArrayTwo, varArgs[0]); verifyNew(VarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo); } @Test public void testNewWithArrayVarArgsWhenFirstArgumentIsNotNullButSubseqentArgumentsAreNull() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); VarArgsConstructorDemo varArgsConstructorDemoMock = mock(VarArgsConstructorDemo.class); final byte[] byteArrayOne = new byte[]{42}; final byte[] byteArrayTwo = null; whenNew(VarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo).thenReturn( varArgsConstructorDemoMock); when(varArgsConstructorDemoMock.getByteArrays()).thenReturn(new byte[][]{byteArrayOne}); byte[][] varArgs = tested.newVarArgs(byteArrayOne, byteArrayTwo); assertEquals(1, varArgs.length); assertSame(byteArrayOne, varArgs[0]); verifyNew(VarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo); } @Test public void testNewWithArrayVarArgsWhenFirstArgumentIsNullSecondArgumentIsNotNullAndThirdArgumentIsNull() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); VarArgsConstructorDemo varArgsConstructorDemoMock = mock(VarArgsConstructorDemo.class); final byte[] byteArrayOne = null; final byte[] byteArrayTwo = new byte[]{42}; final byte[] byteArrayThree = null; whenNew(VarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo, byteArrayThree).thenReturn( varArgsConstructorDemoMock); when(varArgsConstructorDemoMock.getByteArrays()).thenReturn(new byte[][]{byteArrayTwo}); byte[][] varArgs = tested.newVarArgs(byteArrayOne, byteArrayTwo, byteArrayThree); assertEquals(1, varArgs.length); assertSame(byteArrayTwo, varArgs[0]); verifyNew(VarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo, byteArrayThree); } @Test public void testNewWithArrayVarArgsWhenAllArgumentsAreNullAndOverloadedVarArgsConstructors() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); VarArgsConstructorDemo varArgsConstructorDemoMock = mock(VarArgsConstructorDemo.class); final byte[] byteArrayOne = null; final byte[] byteArrayTwo = null; whenNew(VarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo).thenReturn( varArgsConstructorDemoMock); when(varArgsConstructorDemoMock.getByteArrays()).thenReturn(new byte[][]{ byteArrayTwo}); byte[][] varArgs = tested.newVarArgs(byteArrayOne, byteArrayTwo); assertEquals(1, varArgs.length); assertSame(byteArrayTwo, varArgs[0]); verifyNew(VarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo); } @Test public void testNewWithArrayVarArgsWhenAllArgumentsAreNull() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); SimpleVarArgsConstructorDemo varArgsConstructorDemoMock = mock(SimpleVarArgsConstructorDemo.class); final byte[] byteArrayOne = null; final byte[] byteArrayTwo = null; whenNew(SimpleVarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo).thenReturn( varArgsConstructorDemoMock); when(varArgsConstructorDemoMock.getByteArrays()).thenReturn(new byte[][]{byteArrayTwo}); byte[][] varArgs = tested.newSimpleVarArgs(byteArrayOne, byteArrayTwo); assertEquals(1, varArgs.length); assertSame(byteArrayTwo, varArgs[0]); verifyNew(SimpleVarArgsConstructorDemo.class).withArguments(byteArrayOne, byteArrayTwo); } @Test(expected = NullPointerException.class) public void testNewWithWrongArgument() throws Exception { final int numberOfTimes = 2; final String expected = "used"; ExpectNewDemo tested = new ExpectNewDemo(); ExpectNewServiceUser expectNewServiceImplMock = mock(ExpectNewServiceUser.class); Service serviceMock = mock(Service.class); whenNew(ExpectNewServiceUser.class).withArguments(serviceMock, numberOfTimes).thenReturn( expectNewServiceImplMock); when(expectNewServiceImplMock.useService()).thenReturn(expected); assertEquals(expected, tested.newWithWrongArguments(serviceMock, numberOfTimes)); verifyNew(ExpectNewServiceUser.class).withArguments(serviceMock, numberOfTimes); /* * Should throw NPE because the default behavior of Mockito when a * something isn't expected is to return a default value. In this case * whenConstructionOf * (ExpectNewServiceUser.class).withArguments(serviceMock, * numberOfTimes) is the wrong expectation and thus null is returned * from the substitute mock which is the correct behavior. */ fail("Should throw NPE!"); } @Test public void testExpectNewButNoNewCallWasMade() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock1 = mock(MyClass.class); whenNew(MyClass.class).withNoArguments().thenReturn(myClassMock1); tested.makeDate(); try { verifyNew(MyClass.class).withNoArguments(); fail("Should throw AssertionError!"); } catch (AssertionError e) { assertEquals( "Wanted but not invoked samples.newmocking.MyClass();\nActually, there were zero interactions with this mock.", e.getMessage()); } } @Test public void whenNewSupportsVarArgsAsSecondParameter() throws Exception { final int one = 1; final int two = 2; final float myFloat = 3.0f; ExpectNewDemo tested = new ExpectNewDemo(); VarArgsConstructorDemo varArgsConstructorDemoMock = mock(VarArgsConstructorDemo.class); whenNew(VarArgsConstructorDemo.class).withArguments(myFloat, one, two).thenReturn(varArgsConstructorDemoMock); when(varArgsConstructorDemoMock.getInts()).thenReturn(new int[] { one, two}); int[] varArgs = tested.newVarArgs(myFloat, one, two); assertEquals(2, varArgs.length); assertEquals(one, varArgs[0]); assertEquals(two, varArgs[1]); verifyNew(VarArgsConstructorDemo.class).withArguments(myFloat, one, two); } @Test public void whenNewAnyArgumentsWorksInClassesWithSingleCtor() throws Exception { ExpectNewDemo tested = new ExpectNewDemo(); MyClass myClassMock = mock(MyClass.class); whenNew(MyClass.class).withAnyArguments().thenReturn(myClassMock); when(myClassMock.getMessage()).thenReturn("Hello"); final String actual = tested.multipleNew(); verify(myClassMock, times(2)).getMessage(); verifyNew(MyClass.class, times(2)).withNoArguments(); assertEquals("HelloHello", actual); } @Test public void whenNewAnyArgumentsWorksInClassesWithMultipleCtors() throws Exception { ExpectNewWithMultipleCtorDemo expectNewWithMultipleCtorDemoMock = mock(ExpectNewWithMultipleCtorDemo.class); Service serviceMock = mock(Service.class); whenNew(ExpectNewWithMultipleCtorDemo.class).withAnyArguments().thenReturn(expectNewWithMultipleCtorDemoMock); when(expectNewWithMultipleCtorDemoMock.useService()).thenReturn("message"); // When final ExpectNewWithMultipleCtorDemo expectNewWithMultipleCtorDemo = new ExpectNewWithMultipleCtorDemo(serviceMock); final String message1 = expectNewWithMultipleCtorDemo.useService(); final ExpectNewWithMultipleCtorDemo expectNewWithMultipleCtorDemo1 = new ExpectNewWithMultipleCtorDemo(serviceMock, 5); final String message2 = expectNewWithMultipleCtorDemo1.useService(); assertEquals(message1, "message"); assertEquals(message2, "message"); } @Test public void canDefineSeveralMockResultForNew() throws Exception { final Target expectedTarget = new Target(UNKNOWN_TARGET_NAME,UNKNOWN_TARGET_ID); whenNew(Target.class).withArguments(eq(TARGET_NAME),eq(TARGET_ID)).thenThrow(new CreationException()); whenNew(Target.class).withArguments(eq("Unknown"), eq(-1)).thenReturn(expectedTarget); Target actualTarget = new ExpectNewDemo().createTarget(new ITarget() { @Override public int getId() { return TARGET_ID; } @Override public String getName() { return TARGET_NAME; } }); assertThat(actualTarget).isEqualToComparingFieldByField(expectedTarget); } } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/whennew/WhenNewTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.whennew; import org.junit.runner.RunWith; import org.powermock.modules.junit4.PowerMockRunner; /** * Test class to demonstrate new instance mocking using whenConstructionOf(..). * */ @RunWith(PowerMockRunner.class) public class WhenNewTest extends WhenNewCases { } ================================================ FILE: tests/mockito/junit4/src/test/java/samples/powermockito/junit4/withsettings/WithSettingsTest.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.withsettings; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.finalmocking.FinalDemo; import samples.finalmocking.HoldingFinalDemo; import samples.finalmocking.StaticHoldingFinalDemo; import static org.junit.Assert.assertNotNull; import static org.mockito.Mockito.RETURNS_MOCKS; import static org.mockito.Mockito.withSettings; import static org.powermock.api.mockito.PowerMockito.mock; import static org.powermock.api.mockito.PowerMockito.mockStatic; @RunWith(PowerMockRunner.class) @PrepareForTest( { StaticHoldingFinalDemo.class, HoldingFinalDemo.class, FinalDemo.class }) public class WithSettingsTest { @Test public void powermockitoSupportsAnswersForInstanceMethods() { HoldingFinalDemo tested = mock(HoldingFinalDemo.class, RETURNS_MOCKS); assertNotNull(tested.getFinalDemo()); } @Test public void powermockitoSupportsWithSettingsForInstanceMethods() { HoldingFinalDemo tested = mock(HoldingFinalDemo.class, withSettings().defaultAnswer(RETURNS_MOCKS)); assertNotNull(tested.getFinalDemo()); } @Test public void powermockitoSupportsAnswersForStaticMethods() { mockStatic(StaticHoldingFinalDemo.class, RETURNS_MOCKS); assertNotNull(StaticHoldingFinalDemo.getFinalDemo()); } @Test public void powermockitoSupportsWithSettingsForStaticMethods() { mockStatic(StaticHoldingFinalDemo.class, withSettings().defaultAnswer(RETURNS_MOCKS)); assertNotNull(StaticHoldingFinalDemo.getFinalDemo()); } } ================================================ FILE: tests/mockito/junit4/src/test/resources/org/powermock/extensions/configuration.properties ================================================ powermock.global-ignore=samples.powermockito.junit4.bugs.github801.GlobalPowerMockIgnore ================================================ FILE: tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/AnnotationUsageTest.java ================================================ /* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.agent; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.mockito.InjectMocks; import org.mockito.Mock; import org.powermock.modules.junit4.rule.PowerMockRule; import samples.Service; import samples.annotationbased.AnnotationDemo; import java.util.Arrays; import static org.junit.Assert.assertEquals; import static org.powermock.api.mockito.PowerMockito.when; @RunWith(Parameterized.class) public class AnnotationUsageTest { @Rule public PowerMockRule rule = new PowerMockRule(); @InjectMocks AnnotationDemo tested; @Mock Service server; final String fooId; public AnnotationUsageTest(String fooId) { this.fooId = fooId; } @Parameterized.Parameters() public static Iterable data() { return Arrays.asList(new Object[][]{ {"1"}, {"2"} }); } @Before public void setUp() throws Exception { when(server.getServiceMessage()).thenReturn(fooId); } @Test public void annotationsAreEnabledWhenUsingTheJUnitRule() throws Exception { String serviceMessage = tested.getServiceMessage(); assertEquals(fooId, serviceMessage); } } ================================================ FILE: tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/AssertPowerMockRuleDelagatesToOtherRulesTest.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.agent; import org.junit.Rule; import org.junit.Test; import org.junit.rules.MethodRule; import org.junit.rules.TestName; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.Statement; import org.powermock.core.classloader.MockClassLoader; import org.powermock.modules.junit4.rule.PowerMockRule; import java.util.LinkedList; import java.util.List; import static org.assertj.core.api.Java6Assertions.assertThat; /** * This test demonstrates that the PowerMockRule delegates to other rules. */ public class AssertPowerMockRuleDelagatesToOtherRulesTest { private static final MyObject BEFORE = new MyObject(); private final List objects = new LinkedList(); @Rule public PowerMockRule powerMockRule = new PowerMockRule(); @Rule public MyRule rule = new MyRule(); @Rule public TestName testName = new TestName(); @Test public void assertPowerMockRuleDelegatesToOtherRules() throws Exception { assertThat(this.getClass().getClassLoader()).isNotInstanceOf(MockClassLoader.class); assertThat(objects) .hasSize(1) .containsExactly(BEFORE); assertThat(testName.getMethodName()).isEqualTo("assertPowerMockRuleDelegatesToOtherRules"); } private static class MyObject { private final String state = "state"; @Override public int hashCode() { return state.hashCode(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } MyObject myObject = (MyObject) o; return state.equals(myObject.state); } } private class MyRule implements MethodRule { @Override public Statement apply(final Statement base, FrameworkMethod method, Object target) { return new Statement() { @Override public void evaluate() throws Throwable { objects.add(BEFORE); base.evaluate(); } }; } } } ================================================ FILE: tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/LargeMethodTest.java ================================================ package samples.powermockito.junit4.agent; import org.junit.Rule; import org.junit.Test; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.rule.PowerMockRule; import samples.largemethod.MethodExceedingJvmLimit; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertNull; import static junit.framework.Assert.assertSame; import static junit.framework.Assert.assertTrue; import static junit.framework.Assert.fail; import static org.mockito.Mockito.when; import static org.powermock.api.mockito.PowerMockito.mockStatic; import static org.powermock.api.mockito.PowerMockito.verifyStatic; import static org.powermock.api.support.membermodification.MemberMatcher.method; import static org.powermock.api.support.membermodification.MemberModifier.suppress; @PrepareForTest(MethodExceedingJvmLimit.class) public class LargeMethodTest { @Rule public PowerMockRule powerMockRule = new PowerMockRule(); @Test public void largeMethodShouldBeOverridden() { try { MethodExceedingJvmLimit.init(); fail("Method should be overridden and exception should be thrown"); } catch (Exception e) { assertSame(IllegalAccessException.class, e.getClass()); assertTrue(e.getMessage().contains("Method was too large and after instrumentation exceeded JVM limit")); } } @Test public void largeMethodShouldBeAbleToBeSuppressed() { suppress(method(MethodExceedingJvmLimit.class, "init")); assertNull("Suppressed method should return: null", MethodExceedingJvmLimit.init()); } @Test public void largeMethodShouldBeAbleToBeMocked() { mockStatic(MethodExceedingJvmLimit.class); when(MethodExceedingJvmLimit.init()).thenReturn("ok"); assertEquals("Mocked method should return: ok", "ok", MethodExceedingJvmLimit.init()); verifyStatic(MethodExceedingJvmLimit.class); MethodExceedingJvmLimit.init(); } @Test(expected = IllegalStateException.class) public void largeMethodShouldBeAbleToBeMockedAndThrowException() { mockStatic(MethodExceedingJvmLimit.class); when(MethodExceedingJvmLimit.init()).thenThrow(new IllegalStateException()); MethodExceedingJvmLimit.init(); verifyStatic(MethodExceedingJvmLimit.class); MethodExceedingJvmLimit.init(); } } ================================================ FILE: tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/MemberModificationExampleTest.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.agent; import org.junit.Rule; import org.junit.Test; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.rule.PowerMockRule; import samples.staticandinstance.StaticAndInstanceDemo; import samples.suppressconstructor.SuppressConstructorHierarchy; import samples.suppresseverything.SuppressEverything; import samples.suppressfield.SuppressField; import samples.suppressmethod.SuppressMethod; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import static org.powermock.api.support.membermodification.MemberMatcher.constructor; import static org.powermock.api.support.membermodification.MemberMatcher.constructorsDeclaredIn; import static org.powermock.api.support.membermodification.MemberMatcher.everythingDeclaredIn; import static org.powermock.api.support.membermodification.MemberMatcher.field; import static org.powermock.api.support.membermodification.MemberMatcher.method; import static org.powermock.api.support.membermodification.MemberMatcher.methods; import static org.powermock.api.support.membermodification.MemberMatcher.methodsDeclaredIn; import static org.powermock.api.support.membermodification.MemberModifier.replace; import static org.powermock.api.support.membermodification.MemberModifier.stub; import static org.powermock.api.support.membermodification.MemberModifier.suppress; /** * Demonstrates PowerMock's ability to modify member structures. */ @PrepareForTest( { SuppressMethod.class, SuppressField.class, SuppressEverything.class }) public class MemberModificationExampleTest { @Rule public PowerMockRule powerMockRule = new PowerMockRule(); @Test public void suppressSingleMethodExample() throws Exception { suppress(method(SuppressMethod.class, "getObject")); assertNull(new SuppressMethod().getObject()); } @Test public void suppressMultipleMethodsExample1() throws Exception { suppress(methods(SuppressMethod.class, "getObject", "getInt")); assertNull(new SuppressMethod().getObject()); assertEquals(0, new SuppressMethod().getInt()); } @Test public void suppressMultipleMethodsExample2() throws Exception { suppress(methods(method(SuppressMethod.class, "getObject"), method(SuppressMethod.class, "getInt"))); assertNull(new SuppressMethod().getObject()); assertEquals(0, new SuppressMethod().getInt()); } @Test public void suppressAllMethodsExample() throws Exception { suppress(methodsDeclaredIn(SuppressMethod.class)); final SuppressMethod tested = new SuppressMethod(); assertNull(tested.getObject()); assertNull(SuppressMethod.getObjectStatic()); assertEquals(0, tested.getByte()); } @Test public void suppressSingleFieldExample() throws Exception { suppress(field(SuppressField.class, "domainObject")); SuppressField tested = new SuppressField(); assertNull(tested.getDomainObject()); } @Test public void suppressConstructorExample() throws Exception { suppress(constructor(SuppressConstructorHierarchy.class)); SuppressConstructorHierarchy tested = new SuppressConstructorHierarchy("message"); assertEquals(42, tested.getNumber()); assertNull(tested.getMessage()); } @Test public void stubSingleMethodExample() throws Exception { final String expectedReturnValue = "new"; stub(method(SuppressMethod.class, "getObject")).toReturn(expectedReturnValue); final SuppressMethod tested = new SuppressMethod(); assertEquals(expectedReturnValue, tested.getObject()); assertEquals(expectedReturnValue, tested.getObject()); } @Test public void duckTypeStaticMethodExample() throws Exception { replace(method(SuppressMethod.class, "getObjectStatic")).with( method(StaticAndInstanceDemo.class, "getStaticMessage")); assertEquals(SuppressMethod.getObjectStatic(), StaticAndInstanceDemo.getStaticMessage()); } @Test public void whenReplacingMethodWithAMethodOfIncorrectReturnTypeThenAnIAEIsThrown() throws Exception { try { replace(method(SuppressMethod.class, "getObjectStatic")).with( method(StaticAndInstanceDemo.class, "aVoidMethod")); fail("Should thow IAE"); } catch (Exception e) { assertEquals("The replacing method (public static void samples.staticandinstance.StaticAndInstanceDemo.aVoidMethod()) needs to return java.lang.Object and not void.", e.getMessage()); } } @Test public void whenReplacingMethodWithAMethodOfWithIncorrectParametersThenAnIAEIsThrown() throws Exception { try { replace(method(SuppressMethod.class, "getObjectStatic")).with( method(StaticAndInstanceDemo.class, "aMethod2")); fail("Should thow IAE"); } catch (Exception e) { 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()); } } @Test public void changingReturnValueExample() throws Exception { replace(method(SuppressMethod.class, "getObjectWithArgument")).with(new ReturnValueChangingInvocationHandler()); final SuppressMethod tested = new SuppressMethod(); assertThat(tested.getObjectWithArgument("don't do anything"), is(instanceOf(Object.class))); assertEquals("hello world", tested.getObjectWithArgument("make it a string")); } @Test public void suppressAllConstructors() throws Exception { suppress(constructorsDeclaredIn(SuppressEverything.class)); SuppressEverything suppressEverything = new SuppressEverything(); new SuppressEverything("test"); try { suppressEverything.something(); fail("Should throw ISE"); } catch (IllegalStateException e) { assertEquals("error", e.getMessage()); } } @Test public void suppressEverythingExample() throws Exception { suppress(everythingDeclaredIn(SuppressEverything.class)); SuppressEverything suppressEverything = new SuppressEverything(); new SuppressEverything("test"); suppressEverything.something(); suppressEverything.somethingElse(); } private final class ReturnValueChangingInvocationHandler implements InvocationHandler { @Override public Object invoke(Object object, Method method, Object[] arguments) throws Throwable { if (arguments[0].equals("make it a string")) { return "hello world"; } else { return method.invoke(object, arguments); } } } } ================================================ FILE: tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/MockFinalNonStaticMethodsTest.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.agent; import org.junit.Rule; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.rule.PowerMockRule; import samples.finalmocking.FinalDemo; import samples.powermockito.junit4.finalmocking.MockFinalMethodsCases; import samples.privateandfinal.PrivateFinal; /** * Test class to demonstrate non-static final mocking with Mockito. */ @PrepareForTest( { FinalDemo.class, PrivateFinal.class }) public class MockFinalNonStaticMethodsTest extends MockFinalMethodsCases{ @Rule public PowerMockRule powerMockRule = new PowerMockRule(); } ================================================ FILE: tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/MockFinalUsingAnnotationsTest.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.agent; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.mockito.Mock; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.rule.PowerMockRule; import samples.finalmocking.FinalDemo; import static org.junit.Assert.assertNull; import static org.mockito.Mockito.verify; /** * Test class to demonstrate non-static final mocking with Mockito and PowerMock * annotations. */ @PrepareForTest(FinalDemo.class) @Ignore public class MockFinalUsingAnnotationsTest { @Rule public PowerMockRule powerMockRule = new PowerMockRule(); @Mock private FinalDemo usingMockitoMockAnnotation; @SuppressWarnings("deprecation") @org.mockito.Mock private FinalDemo usingDeprecatedMockitoMockAnnotation; @Test public void assertMockFinalWithMockitoMockAnnotationWorks() throws Exception { final String argument = "hello"; assertNull(usingMockitoMockAnnotation.say(argument)); verify(usingMockitoMockAnnotation).say(argument); } @Test public void assertMockFinalWithDeprecatedMockitoMockAnnotationWorks() throws Exception { final String argument = "hello"; assertNull(usingDeprecatedMockitoMockAnnotation.say(argument)); verify(usingDeprecatedMockitoMockAnnotation).say(argument); } } ================================================ FILE: tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/MockStaticTest.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.agent; import org.junit.Rule; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.rule.PowerMockRule; import samples.powermockito.junit4.staticmocking.MockStaticCases; import samples.singleton.SimpleStaticService; import samples.singleton.StaticService; /** * Test class to demonstrate static mocking with PowerMockito. */ @PrepareForTest({StaticService.class, SimpleStaticService.class}) public class MockStaticTest extends MockStaticCases { @Rule public PowerMockRule powerMockRule = new PowerMockRule(); } ================================================ FILE: tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/MockStaticWithPrivateCtorTest.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.agent; import org.junit.Rule; import org.junit.Test; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.rule.PowerMockRule; import samples.singleton.StaticWithPrivateCtor; import static org.junit.Assert.assertEquals; import static org.powermock.api.mockito.PowerMockito.mockStatic; import static org.powermock.api.mockito.PowerMockito.when; @PrepareForTest(StaticWithPrivateCtor.class) public class MockStaticWithPrivateCtorTest { @Rule public PowerMockRule powerMockRule = new PowerMockRule(); @Test public void canMockStaticMethodsInClassWithPrivateConstructor() throws Exception { mockStatic(StaticWithPrivateCtor.class); when(StaticWithPrivateCtor.staticMethod()).thenReturn("something else"); assertEquals("something else", StaticWithPrivateCtor.staticMethod()); } } ================================================ FILE: tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/PrivateInstanceMockingTest.java ================================================ package samples.powermockito.junit4.agent; import org.junit.Rule; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.rule.PowerMockRule; import samples.powermockito.junit4.privatemocking.PrivateInstanceMockingCases; import samples.privatemocking.PrivateMethodDemo; @PrepareForTest( { PrivateMethodDemo.class }) public class PrivateInstanceMockingTest extends PrivateInstanceMockingCases { @Rule public PowerMockRule powerMockRule = new PowerMockRule(); } ================================================ FILE: tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/StubMethodTest.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.agent; import org.junit.Rule; import org.junit.Test; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.rule.PowerMockRule; import org.powermock.reflect.exceptions.MethodNotFoundException; import org.powermock.reflect.exceptions.TooManyMethodsFoundException; import samples.suppressmethod.SuppressMethod; import static junit.framework.Assert.fail; import static org.junit.Assert.assertEquals; import static org.powermock.api.support.membermodification.MemberMatcher.method; import static org.powermock.api.support.membermodification.MemberModifier.stub; @PrepareForTest(SuppressMethod.class) public class StubMethodTest { @Rule public PowerMockRule powerMockRule = new PowerMockRule(); @Test public void whenStubbingInstanceMethodTheMethodReturnsTheStubbedValue() throws Exception { String expectedValue = "Hello"; stub(method(SuppressMethod.class, "getObject")).toReturn(expectedValue); SuppressMethod tested = new SuppressMethod(); assertEquals(expectedValue, tested.getObject()); assertEquals(expectedValue, tested.getObject()); } @Test public void whenStubbingStaticMethodTheMethodReturnsTheStubbedValue() throws Exception { String expectedValue = "Hello"; stub(method(SuppressMethod.class, "getObjectStatic")).toReturn(expectedValue); assertEquals(expectedValue, SuppressMethod.getObjectStatic()); assertEquals(expectedValue, SuppressMethod.getObjectStatic()); } @Test public void whenStubbingInstanceMethodWithPrimiteValueTheMethodReturnsTheStubbedValue() throws Exception { float expectedValue = 4; stub(method(SuppressMethod.class, "getFloat")).toReturn(expectedValue); SuppressMethod tested = new SuppressMethod(); assertEquals(expectedValue, tested.getFloat(), 0.0f); assertEquals(expectedValue, tested.getFloat(), 0.0f); } @Test(expected = TooManyMethodsFoundException.class) public void whenSeveralMethodsFoundThenTooManyMethodsFoundExceptionIsThrown() throws Exception { stub(method(SuppressMethod.class, "sameName")); } @Test(expected = MethodNotFoundException.class) public void whenNoMethodsFoundThenMethodNotFoundExceptionIsThrown() throws Exception { stub(method(SuppressMethod.class, "notFound")); } @Test public void whenStubbingInstanceMethodByPassingTheMethodTheMethodReturnsTheStubbedValue() throws Exception { String expected = "Hello"; stub(method(SuppressMethod.class, "getObject")).toReturn(expected); SuppressMethod tested = new SuppressMethod(); assertEquals(expected, tested.getObject()); assertEquals(expected, tested.getObject()); } @Test public void whenStubbingStaticMethodByPassingTheMethodTheMethodReturnsTheStubbedValue() throws Exception { String expected = "Hello"; stub(method(SuppressMethod.class, "getObjectStatic")).toReturn(expected); assertEquals(expected, SuppressMethod.getObjectStatic()); assertEquals(expected, SuppressMethod.getObjectStatic()); } @Test(expected = ClassCastException.class) public void whenStubbingInstanceMethodWithWrongReturnTypeThenClasscastExceptionIsThrown() throws Exception { String illegalReturnType = "Hello"; stub(method(SuppressMethod.class, "getFloat")).toReturn(illegalReturnType); SuppressMethod tested = new SuppressMethod(); tested.getFloat(); } @Test public void whenStubbingInstanceMethodToThrowExceptionTheMethodThrowsTheStubbedException() throws Exception { Exception expected = new Exception("message"); stub(method(SuppressMethod.class, "getObject")).toThrow(expected); SuppressMethod tested = new SuppressMethod(); try { tested.getObject(); fail(); } catch (Exception e) { assertEquals("message", e.getMessage()); } } @Test public void whenStubbingStaticMethodToThrowExceptionTheMethodThrowsTheStubbedException() throws Exception { Exception expected = new Exception("message"); stub(method(SuppressMethod.class, "getObjectStatic")).toThrow(expected); try { SuppressMethod.getObjectStatic(); fail(); } catch (Exception e) { assertEquals("message", e.getMessage()); } } } ================================================ FILE: tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/SuppressConstructorDemoTest.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.agent; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.rule.PowerMockRule; import samples.suppressconstructor.SuppressConstructorDemo; import samples.suppressconstructor.SuppressConstructorSubclassDemo; import static org.junit.Assert.assertNull; import static org.powermock.api.support.membermodification.MemberMatcher.constructor; import static org.powermock.api.support.membermodification.MemberModifier.suppress; /** * This test demonstrates how to tell PowerMock to avoid executing constructor * code for a certain class. This is crucial in certain tests where the * constructor or a subclass's constructor performs operations that are of no * concern to the unit test of the actual class or if the constructor performs * operations, such as getting services from a runtime environment that has not * been initialized. In normal situations you're forced to create an integration * or function test for the class instead (and thus the runtime environment is * available). This is not particularly good when it comes to testing method * logic. */ @PrepareForTest(SuppressConstructorDemo.class) public class SuppressConstructorDemoTest { @Rule public PowerMockRule powerMockRule = new PowerMockRule(); /** * This test makes sure that the real constructor has never been called. */ @Test public void testSuppressConstructor() throws Exception { suppress(constructor(SuppressConstructorDemo.class)); final SuppressConstructorDemo tested = new SuppressConstructorDemo("a message"); assertNull("Message should have been null since we're skipping the execution of the constructor code.", tested.getMessage()); } /** * This test makes sure that the real parent constructor has never been * called. */ @Test @Ignore("Doesn't work when using the Java agent") public void testSuppressParentConstructor() throws Exception { suppress(constructor(SuppressConstructorSubclassDemo.class)); final SuppressConstructorDemo tested = new SuppressConstructorDemo("a message"); assertNull("Message should have been null since we're skipping the execution of the constructor code.", tested.getMessage()); } } ================================================ FILE: tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/SuppressConstructorHierarchyDemoTest.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.agent; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.rule.PowerMockRule; import samples.suppressconstructor.InvokeConstructor; import samples.suppressconstructor.SuppressConstructorHierarchy; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; import static org.powermock.api.support.membermodification.MemberMatcher.constructor; import static org.powermock.api.support.membermodification.MemberModifier.suppress; @PrepareForTest(SuppressConstructorHierarchy.class) public class SuppressConstructorHierarchyDemoTest { @Rule public PowerMockRule powerMockRule = new PowerMockRule(); @Test @Ignore("Doesn't work from the java agent") public void testSuppressConstructorHierarchy() throws Exception { suppress(constructor(SuppressConstructorHierarchy.class)); final String message = new InvokeConstructor().doStuff("qwe"); assertNull("Message should have been null since we're skipping the execution of the constructor code. Message was \"" + message + "\".", message); } @Test @PrepareForTest public void testNotSuppressConstructorWithoutByteCodeManipulation() throws Exception { try { new SuppressConstructorHierarchy("message"); fail("Should throw RuntimeException since we're running this test with a new class loader!"); } catch (RuntimeException e) { assertEquals("This should be suppressed!!", e.getMessage()); } } @Test public void testNotSuppressConstructorWithByteCodeManipulation() throws Exception { try { new SuppressConstructorHierarchy("message"); fail("Should throw RuntimeException since we're running this test with a new class loader!"); } catch (RuntimeException e) { assertEquals("This should be suppressed!!", e.getMessage()); } } /** * This simple test demonstrate that it's possible to continue execution * with the default {@code PrepareForTest} settings (i.e. using a * byte-code manipulated version of the SuppressConstructorHierarchyDemo * class). */ @Test public void testSuppressConstructorHierarchyAgain() throws Exception { suppress(constructor(SuppressConstructorHierarchy.class)); SuppressConstructorHierarchy tested = new SuppressConstructorHierarchy("message"); assertEquals(42, tested.getNumber()); } } ================================================ FILE: tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/SystemClassUserTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.agent; import org.junit.Rule; import org.junit.Test; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.rule.PowerMockRule; import samples.system.SystemClassUser; import java.net.URLEncoder; import java.util.Collections; import java.util.LinkedList; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import static org.mockito.Mockito.times; import static org.powermock.api.mockito.PowerMockito.*; /** * Demonstrates PowerMockito's ability to mock non-final and final system * classes. To mock a system class you need to prepare the calling class for * testing. I.e. let's say you're testing class A which interacts with * URLEncoder then you would do: * *
 * 
 * @PrepareForTest({A.class})
 * 
 * 
*/ @SuppressWarnings("MalformedFormatString") @PrepareForTest( { SystemClassUser.class }) public class SystemClassUserTest { @Rule public PowerMockRule powerMockRule = new PowerMockRule(); @Test public void assertThatMockingOfNonFinalSystemClassesWorks() throws Exception { mockStatic(URLEncoder.class); when(URLEncoder.encode("string", "enc")).thenReturn("something"); assertEquals("something", new SystemClassUser().performEncode()); } @Test public void assertThatMockingOfTheRuntimeSystemClassWorks() throws Exception { mockStatic(Runtime.class); Runtime runtimeMock = mock(Runtime.class); Process processMock = mock(Process.class); when(Runtime.getRuntime()).thenReturn(runtimeMock); when(runtimeMock.exec("command")).thenReturn(processMock); assertSame(processMock, new SystemClassUser().executeCommand()); } @Test public void assertThatMockingOfFinalSystemClassesWorks() throws Exception { mockStatic(System.class); when(System.getProperty("property")).thenReturn("my property"); assertEquals("my property", new SystemClassUser().getSystemProperty()); } @Test public void assertThatPartialMockingOfFinalSystemClassesWorks() throws Exception { spy(System.class); doReturn(2L).when(System.class); System.nanoTime(); new SystemClassUser().doMoreComplicatedStuff(); assertEquals("2", System.getProperty("nanoTime")); } @Test public void assertThatMockingOfCollectionsWork() throws Exception { List list = new LinkedList(); mockStatic(Collections.class); Collections.shuffle(list); new SystemClassUser().shuffleCollection(list); verifyStatic(Collections.class, times(2)); Collections.shuffle(list); } @Test public void assertThatPartialMockingOfFinalSystemClassesWorksForNonVoidMethods() throws Exception { spy(System.class); doReturn("my property").when(System.class); System.getProperty("property"); final SystemClassUser systemClassUser = new SystemClassUser(); systemClassUser.copyProperty("to", "property"); assertEquals("my property", System.getProperty("to")); } @Test public void assertThatMockingStringWorks() throws Exception { mockStatic(String.class); final String string = "string"; final String args = "args"; final String returnValue = "returnValue"; when(String.format(string, args)).thenReturn(returnValue); final SystemClassUser systemClassUser = new SystemClassUser(); assertEquals(systemClassUser.format(string, args), returnValue); } } ================================================ FILE: tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/WhenNewTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.agent; import org.junit.Rule; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.rule.PowerMockRule; import samples.expectnew.ExpectNewDemo; import samples.newmocking.MyClass; import samples.powermockito.junit4.whennew.WhenNewCases; import java.io.DataInputStream; /** * Test class to demonstrate new instance mocking using whenConstructionOf(..). * */ @SuppressWarnings("PrimitiveArrayArgumentToVariableArgMethod") @PrepareForTest({ MyClass.class, ExpectNewDemo.class, DataInputStream.class }) public class WhenNewTest extends WhenNewCases { @Rule public PowerMockRule powerMockRule = new PowerMockRule(); } ================================================ FILE: tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/github512/Github512Test.java ================================================ package samples.powermockito.junit4.agent.github512; import org.junit.Rule; import org.junit.Test; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.rule.PowerMockRule; import samples.singleton.StaticService; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.powermock.api.mockito.PowerMockito.method; import static org.powermock.api.mockito.PowerMockito.suppress; @PowerMockIgnore("org.assertj.*") public class Github512Test { @Rule public PowerMockRule rule = new PowerMockRule(); @Test @PrepareForTest(StaticService.class) public void shouldSuppressMethodWithPrepareForTestOnMethod() { suppress(method(StaticService.class, "calculate")); assertThat(StaticService.calculate(1, 5)).isEqualTo(0); } } ================================================ FILE: tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/github512/package-info.java ================================================ /** * https://github.com/jayway/powermock/issues/512 */ package samples.powermockito.junit4.agent.github512; ================================================ FILE: tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/EnclosedTest.java ================================================ /* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package powermock.modules.test.mockito.junit4.delegate; import org.junit.Test; import org.junit.experimental.runners.Enclosed; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunnerDelegate; import samples.staticandinstance.StaticAndInstanceDemo; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.not; import static org.junit.Assert.assertThat; import static org.powermock.api.mockito.PowerMockito.*; /** * Demonstrates how PowerMockRunner with annotation PowerMockRunnerDelegate can * provide PowerMock features to yet-another JUnit runner. */ @RunWith(PowerMockRunner.class) @PowerMockRunnerDelegate(Enclosed.class) @PrepareForTest(StaticAndInstanceDemo.class) public class EnclosedTest { private static final String stubbedReturnValue = "Stubbed return-value from " + EnclosedTest.class; public static class NoStubbing { @Test public void noStubbing() { assertThat("Original return-value of #getStaticMessage()", StaticAndInstanceDemo.getStaticMessage(), not(equalTo(stubbedReturnValue))); } } public static class StubbedStaticReturnValue { @Test public void stubbedStaticReturnValue() { mockStatic(StaticAndInstanceDemo.class); when(StaticAndInstanceDemo.getStaticMessage()) .thenReturn(stubbedReturnValue); assertThat("Stubbed return-value of #getStaticMessag()", StaticAndInstanceDemo.getStaticMessage(), equalTo(stubbedReturnValue)); verifyStatic(StaticAndInstanceDemo.class); StaticAndInstanceDemo.getStaticMessage(); verifyNoMoreInteractions(StaticAndInstanceDemo.class); } } public static class WhenStubbingIsOver { @Test public void whenStubbingIsOver() { assertThat("Back to original return-value of #getStaticMessage()", StaticAndInstanceDemo.getStaticMessage(), not(equalTo(stubbedReturnValue))); } } public static class SubClass extends StubbedStaticReturnValue {} public static class SubClassWithExtraNonPublicConstructors extends StubbedStaticReturnValue { public SubClassWithExtraNonPublicConstructors() {} private SubClassWithExtraNonPublicConstructors(boolean arg) {} protected SubClassWithExtraNonPublicConstructors(String arg) {} } } ================================================ FILE: tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/JUnitParamsTest.java ================================================ package powermock.modules.test.mockito.junit4.delegate; import junitparams.JUnitParamsRunner; import junitparams.Parameters; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunnerDelegate; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.when; @PowerMockRunnerDelegate(JUnitParamsRunner.class) @PrepareForTest(Math.class) @RunWith(PowerMockRunner.class) public class JUnitParamsTest { @Before public void setUp() { PowerMockito.mockStatic(Math.class); when(Math.addExact(anyInt(), anyInt())).thenReturn(42); } @Test @Parameters({"11, 234", "-54, 43"}) public void testSum(int a, int b) { Assert.assertEquals(42, Math.addExact(a, b)); } } ================================================ FILE: tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/MultipleConstructorsTest.java ================================================ /* * Copyright 2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package powermock.modules.test.mockito.junit4.delegate; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunnerDelegate; /** * Verifies that an additional non-public constructor does not break the test-run. */ @RunWith(PowerMockRunner.class) @PowerMockRunnerDelegate public class MultipleConstructorsTest { public MultipleConstructorsTest() { } protected MultipleConstructorsTest(String s) { } @Test public void dummyTest() {} } ================================================ FILE: tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/SelfieTest.java ================================================ /* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package powermock.modules.test.mockito.junit4.delegate; import org.hamcrest.Matcher; import org.junit.runner.Description; import org.junit.runner.RunWith; import org.junit.runner.Runner; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunNotifier; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunnerDelegate; import samples.staticandinstance.StaticAndInstanceDemo; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.not; import static org.junit.runner.Description.createTestDescription; import static org.powermock.api.mockito.PowerMockito.*; /** * Demonstrates how PowerMockRunner with annotation PowerMockRunnerDelegate can * provide a low-level JUnit (in this case a self-contained "selfie" test) * with some PowerMock abilities. */ @RunWith(PowerMockRunner.class) @PowerMockRunnerDelegate(SelfieTest.class) @PrepareForTest(StaticAndInstanceDemo.class) public class SelfieTest extends Runner { private static final String stubbedReturnValue = "Stubbed return-value from " + SelfieTest.class; private static final Description first = createTestDescription( SelfieTest.class, "No Stubbing"); private static final Description second = createTestDescription( SelfieTest.class, "Stubbed Static Return-Value"); /** * Mandatory Runner constructor */ public SelfieTest(Class ignore) { } @Override public Description getDescription() { Description desc = Description .createSuiteDescription(SelfieTest.class); desc.addChild(first); desc.addChild(second); return desc; } @Override public void run(RunNotifier notifier) { assert_getStaticMessage(notifier, first, not(equalTo(stubbedReturnValue))); mockStatic(StaticAndInstanceDemo.class); when(StaticAndInstanceDemo.getStaticMessage()) .thenReturn(stubbedReturnValue); assert_getStaticMessage(notifier, second, equalTo(stubbedReturnValue)); } void assert_getStaticMessage(RunNotifier notifier, Description currentTest, Matcher getStaticMessageExpectation) { notifier.fireTestStarted(currentTest); try { String staticMessage = StaticAndInstanceDemo.getStaticMessage(); if (getStaticMessageExpectation.matches(staticMessage)) { notifier.fireTestFinished(currentTest); } else { notifier.fireTestFailure(new Failure(currentTest, new AssertionError( "Unexpected #getStaticMessage() return-value: " + staticMessage))); } } catch (Exception ex) { notifier.fireTestFailure(new Failure(currentTest, ex)); } } } ================================================ FILE: tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/SubclassDelegateTest.java ================================================ /* * Copyright 2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package powermock.modules.test.mockito.junit4.delegate; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunnerDelegate; /** * To verify that annotation {@link PowerMockRunnerDelegate} works OK when the * test-class has a super-class that will be loaded from the same class-loader. * (This used to make JUnit's default runner fail with * java.lang.IllegalArgumentException: Test class can only have one constructor * during initialization.) */ @RunWith(PowerMockRunner.class) @PowerMockRunnerDelegate public class SubclassDelegateTest extends SuperClass { @Test public void test() {} } ================================================ FILE: tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/SuperClass.java ================================================ /* * Copyright 2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package powermock.modules.test.mockito.junit4.delegate; class SuperClass {} ================================================ FILE: tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/SuppressedMethod.java ================================================ /* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package powermock.modules.test.mockito.junit4.delegate; import samples.suppressmethod.SuppressMethod; public enum SuppressedMethod { getObject { @Override public Object invokeOn(SuppressMethod tested) { return tested.getObject(); } }, getObjectStatic { @Override public Object invokeOn(SuppressMethod tested) { return SuppressMethod.getObjectStatic(); } }, getFloat { @Override public Object invokeOn(SuppressMethod tested) { return tested.getFloat(); } }; public abstract Object invokeOn(SuppressMethod tested); } ================================================ FILE: tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/SuppressedMethodStubbing.java ================================================ /* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package powermock.modules.test.mockito.junit4.delegate; import java.util.concurrent.Callable; import org.powermock.api.support.membermodification.strategy.MethodStubStrategy; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; public enum SuppressedMethodStubbing { Hello("Hello"), float_4(4.0F), exception(new Exception("message")) { @Override public void enforceOn(MethodStubStrategy stub) { stub.toThrow((Exception) value); } @Override public void verify(final Callable invocation) throws Exception { super.verify(new Callable() { @Override public Exception call() { try { invocation.call(); fail("Expected exception: " + value); return null; } catch (Exception actualException) { return actualException; } } }); } @Override public String toString() { return "throws Exception"; } }; final Object value; private SuppressedMethodStubbing(Object value) { this.value = value; } public void enforceOn(MethodStubStrategy stub) { stub.toReturn((T) value); } public void verify(Callable invocation) throws Exception { assertEquals(value, invocation.call()); } @Override public String toString() { return "returns " + value; } } ================================================ FILE: tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/SystemClassUserCases.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package powermock.modules.test.mockito.junit4.delegate; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import samples.system.SystemClassUser; import java.net.URLEncoder; import java.util.Collections; import java.util.LinkedList; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import static org.mockito.Mockito.times; import static org.powermock.api.mockito.PowerMockito.*; /** * Demonstrates PowerMockito's ability to mock non-final and final system * classes. To mock a system class you need to prepare the calling class for * testing. I.e. let's say you're testing class A which interacts with * URLEncoder then you would do: * *
 *
 * @PrepareForTest({A.class})
 *
 * 
*/ @RunWith(PowerMockRunner.class) @PrepareForTest({SystemClassUser.class}) public class SystemClassUserCases { @Test public void assertThatMockingOfNonFinalSystemClassesWorks() throws Exception { mockStatic(URLEncoder.class); when(URLEncoder.encode("string", "enc")).thenReturn("something"); assertEquals("something", new SystemClassUser().performEncode()); } @Test public void assertThatMockingOfTheRuntimeSystemClassWorks() throws Exception { mockStatic(Runtime.class); Runtime runtimeMock = mock(Runtime.class); Process processMock = mock(Process.class); when(Runtime.getRuntime()).thenReturn(runtimeMock); when(runtimeMock.exec("command")).thenReturn(processMock); assertSame(processMock, new SystemClassUser().executeCommand()); } @Test public void assertThatMockingOfFinalSystemClassesWorks() throws Exception { mockStatic(System.class); when(System.getProperty("property")).thenReturn("my property"); assertEquals("my property", new SystemClassUser().getSystemProperty()); } @Test public void assertThatPartialMockingOfFinalSystemClassesWorks() throws Exception { spy(System.class); doReturn(2L).when(System.class); System.nanoTime(); new SystemClassUser().doMoreComplicatedStuff(); assertEquals("2", System.getProperty("nanoTime")); } @Test public void assertThatMockingOfCollectionsWork() throws Exception { List list = new LinkedList(); mockStatic(Collections.class); Collections.shuffle(list); new SystemClassUser().shuffleCollection(list); verifyStatic(Collections.class, times(2)); Collections.shuffle(list); } @Test public void assertThatPartialMockingOfFinalSystemClassesWorksForNonVoidMethods() throws Exception { spy(System.class); doReturn("my property").when(System.class); System.getProperty("property"); final SystemClassUser systemClassUser = new SystemClassUser(); systemClassUser.copyProperty("to", "property"); assertEquals("my property", System.getProperty("to")); } @Test public void assertThatMockingStringWorks() throws Exception { mockStatic(String.class); final String string = "string"; final String args = "args"; final String returnValue = "returnValue"; when(String.format(string, args)).thenReturn(returnValue); final SystemClassUser systemClassUser = new SystemClassUser(); assertEquals(systemClassUser.format(string, args), returnValue); } } ================================================ FILE: tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/SystemClassUserMethod.java ================================================ /* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package powermock.modules.test.mockito.junit4.delegate; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import org.junit.Test; public class SystemClassUserMethod { private final Method method; public SystemClassUserMethod(Method method) { this.method = method; } public static SystemClassUserMethod[] values() { Method[] methods = SystemClassUserCases.class.getDeclaredMethods(); List values = new ArrayList(methods.length); for (Method m : methods) { if (m.isAnnotationPresent(Test.class)) { values.add(new SystemClassUserMethod(m)); } } return values.toArray(new SystemClassUserMethod[values.size()]); } @Override public String toString() { return method.getName(); } public Method getMethod() { return method; } } ================================================ FILE: tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/WhenNewCaseMethod.java ================================================ /* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package powermock.modules.test.mockito.junit4.delegate; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import org.junit.Test; import samples.powermockito.junit4.whennew.WhenNewCases; public class WhenNewCaseMethod { final Method testMethod; public WhenNewCaseMethod(Method testMethod) { this.testMethod = testMethod; } @Override public String toString() { return testMethod.getName(); } public void runTest() throws Throwable { try { testMethod.invoke(new WhenNewCases()); } catch (InvocationTargetException ex) { throw ex.getTargetException(); } } public boolean nullPointerIsExpected() { return NullPointerException.class == testMethod.getAnnotation(Test.class).expected(); } public static WhenNewCaseMethod[] values() { Method[] methods = WhenNewCases.class.getDeclaredMethods(); List values = new ArrayList(methods.length); for (Method m : methods) { if (m.isAnnotationPresent(Test.class)) { values.add(new WhenNewCaseMethod(m)); } } return values.toArray(new WhenNewCaseMethod[values.size()]); } } ================================================ FILE: tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/parameterized/FinalDemoTest.java ================================================ /* * Copyright 2011-2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package powermock.modules.test.mockito.junit4.delegate.parameterized; import java.lang.reflect.Method; import java.util.Collection; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunnerDelegate; import samples.finalmocking.FinalDemo; import samples.privateandfinal.PrivateFinal; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.powermock.api.mockito.PowerMockito.*; import static org.powermock.api.support.membermodification.MemberMatcher.method; /** * Test class to demonstrate non-static final mocking with Mockito. */ @RunWith(PowerMockRunner.class) @PowerMockRunnerDelegate(Parameterized.class) @PrepareForTest({FinalDemo.class, PrivateFinal.class}) public class FinalDemoTest { @Parameterized.Parameter(0) public String expected; @Parameterized.Parameters(name = "expected={0}") public static Collection expections() { return java.util.Arrays.asList(new Object[][]{ {"Hello altered World"}, {"something"}, {"test"} }); } @Test public void assertMockFinalWithNoExpectationsWorks() throws Exception { final String argument = "hello"; FinalDemo tested = mock(FinalDemo.class); assertNull(tested.say(argument)); verify(tested).say(argument); } @Test public void assertMockFinalWithExpectationsWorks() throws Exception { final String argument = "hello"; FinalDemo tested = mock(FinalDemo.class); when(tested.say(argument)).thenReturn(expected); final String actual = "" + tested.say(argument); verify(tested).say(argument); assertEquals("Expected and actual did not match", expected, actual); } @Test public void assertFinalNativeWithExpectationsWorks() throws Exception { final String argument = "hello"; FinalDemo tested = mock(FinalDemo.class); when(tested.sayFinalNative(argument)).thenReturn(expected); String actual = "" + tested.sayFinalNative(argument); verify(tested).sayFinalNative(argument); assertEquals("Expected and actual did not match", expected, actual); } @Test public void assertSpyingOnFinalInstanceMethodWorks() throws Exception { FinalDemo tested = new FinalDemo(); FinalDemo spy = spy(tested); final String argument = "PowerMock"; assertEquals("Hello " + argument, spy.say(argument)); when(spy.say(argument)).thenReturn(expected); assertEquals(expected, "" + spy.say(argument)); } @Test(expected = ArrayStoreException.class) public void assertSpyingOnFinalVoidInstanceMethodWorks() throws Exception { FinalDemo tested = new FinalDemo(); FinalDemo spy = spy(tested); doThrow(new ArrayStoreException()).when(spy).finalVoidCallee(); spy.finalVoidCaller(); } @Test public void assertSpyingOnPrivateFinalInstanceMethodWorks() throws Exception { PrivateFinal spy = spy(new PrivateFinal()); assertEquals("Hello " + expected, spy.say(expected)); when(spy, "sayIt", isA(String.class)).thenReturn(expected); assertEquals(expected, "" + spy.say(expected)); verifyPrivate(spy, times(2)).invoke("sayIt", expected); } @Test public void assertSpyingOnPrivateFinalInstanceMethodWorksWhenUsingJavaLangReflectMethod() throws Exception { PrivateFinal spy = spy(new PrivateFinal()); assertEquals("Hello " + expected, spy.say(expected)); final Method methodToExpect = method(PrivateFinal.class, "sayIt"); when(spy, methodToExpect).withArguments(isA(String.class)).thenReturn(expected); assertEquals(expected, "" + spy.say(expected)); verifyPrivate(spy, times(2)).invoke(methodToExpect).withArguments(expected); } } ================================================ FILE: tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/parameterized/MockFinalUsingAnnotationsTest.java ================================================ /* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package powermock.modules.test.mockito.junit4.delegate.parameterized; import java.util.ArrayList; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.mockito.Mock; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunnerDelegate; import org.powermock.reflect.Whitebox; import samples.finalmocking.FinalDemo; import static org.junit.Assert.assertNull; import static org.mockito.Mockito.verify; /** * Test class to demonstrate non-static final mocking with Mockito and PowerMock * annotations. */ @RunWith(PowerMockRunner.class) @PowerMockRunnerDelegate(Parameterized.class) @PrepareForTest(FinalDemo.class) public class MockFinalUsingAnnotationsTest { @Mock private FinalDemo usingMockitoMockAnnotation; @org.mockito.Mock private FinalDemo usingDeprecatedMockitoMockAnnotation; @Parameterized.Parameter(0) public MockField field2test; @Test public void testMockFinal() throws Exception { final String argument = "hello"; System.out.println(field2test); FinalDemo mockedFinal = field2test.inTest(this); assertNull(mockedFinal.say(argument)); verify(mockedFinal).say(argument); } @Parameterized.Parameters(name = "{0}") public static List vals() { MockField[] mockFields = MockField.values(); List vals = new ArrayList(mockFields.length); for (MockField each : mockFields) { vals.add(new Object[]{each}); } return vals; } enum MockField { usingMockitoMockAnnotation, usingDeprecatedMockitoMockAnnotation; T inTest(Object test) { try { return (T) Whitebox.getInternalState(test, name()); } catch (Exception ex) { throw new Error(ex); } } } } ================================================ FILE: tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/parameterized/StubMethodTest.java ================================================ /* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package powermock.modules.test.mockito.junit4.delegate.parameterized; import java.util.Arrays; import java.util.List; import java.util.concurrent.Callable; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunnerDelegate; import powermock.modules.test.mockito.junit4.delegate.SuppressedMethod; import powermock.modules.test.mockito.junit4.delegate.SuppressedMethodStubbing; import samples.suppressmethod.SuppressMethod; import static org.powermock.api.support.membermodification.MemberMatcher.method; import static org.powermock.api.support.membermodification.MemberModifier.stub; import static powermock.modules.test.mockito.junit4.delegate.SuppressedMethod.*; import static powermock.modules.test.mockito.junit4.delegate.SuppressedMethodStubbing.*; @RunWith(PowerMockRunner.class) @PowerMockRunnerDelegate(Parameterized.class) @PrepareForTest(SuppressMethod.class) public class StubMethodTest { @Parameterized.Parameter(0) public SuppressedMethod method; @Parameterized.Parameter(1) public SuppressedMethodStubbing stubbing; @Test public void test() throws Exception { stubbing.enforceOn(stub(method(SuppressMethod.class, method.name()))); final SuppressMethod tested = new SuppressMethod(); Callable methodInvocation = new Callable() { @Override public Object call() { return method.invokeOn(tested); } }; stubbing.verify(methodInvocation); stubbing.verify(methodInvocation); stubbing.verify(methodInvocation); } @Parameterized.Parameters(name = " {0} {1}") public static List paramValues() { return Arrays.asList(new Object[][]{ {getObject, Hello}, {getObject, float_4}, {getObject, exception}, {getObjectStatic, Hello}, {getObjectStatic, float_4}, {getObjectStatic, exception}, // {getFloat, Hello}, //Incompatible return-type {getFloat, float_4}, {getFloat, exception},}); } } ================================================ FILE: tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/parameterized/SuppressConstructorDemoTest.java ================================================ /* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package powermock.modules.test.mockito.junit4.delegate.parameterized; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunnerDelegate; import samples.suppressconstructor.SuppressConstructorDemo; import samples.suppressconstructor.SuppressConstructorSubclassDemo; import static org.junit.Assert.assertNull; import static org.powermock.api.support.membermodification.MemberMatcher.constructor; import static org.powermock.api.support.membermodification.MemberModifier.suppress; /** * This test demonstrates how to tell PowerMock to avoid executing constructor * code for a certain class. This is crucial in certain tests where the * constructor or a subclass's constructor performs operations that are of no * concern to the unit test of the actual class or if the constructor performs * operations, such as getting services from a runtime environment that has not * been initialized. In normal situations you're forced to create an integration * or function test for the class instead (and thus the runtime environment is * available). This is not particularly good when it comes to testing method * logic. */ @RunWith(PowerMockRunner.class) @PowerMockRunnerDelegate(Parameterized.class) @PrepareForTest(SuppressConstructorDemo.class) public class SuppressConstructorDemoTest { final Class constructor2suppress; public SuppressConstructorDemoTest( Class constructor2suppress) { this.constructor2suppress = constructor2suppress; } /** * This test makes sure that the real constructor has never been called. */ @Test public void testSuppressConstructor() throws Exception { suppress(constructor(constructor2suppress)); final SuppressConstructorDemo tested = new SuppressConstructorDemo("a message"); assertNull("Message should have been null since we're skipping the execution of the constructor code.", tested.getMessage()); } @Parameterized.Parameters(name = "{0}") public static List classesWithConstructor2suppress() { List constructorClasses = Arrays.asList(new Object[][]{ {SuppressConstructorSubclassDemo.class}, {SuppressConstructorDemo.class} }); Collections.shuffle(constructorClasses); return constructorClasses; } } ================================================ FILE: tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/parameterized/SuppressConstructorHierarchyDemoTest.java ================================================ /* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package powermock.modules.test.mockito.junit4.delegate.parameterized; import java.util.Arrays; import java.util.List; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunnerDelegate; import samples.suppressconstructor.InvokeConstructor; import samples.suppressconstructor.SuppressConstructorHierarchy; import static org.junit.Assert.*; import static org.powermock.api.support.membermodification.MemberMatcher.constructor; import static org.powermock.api.support.membermodification.MemberModifier.suppress; @RunWith(PowerMockRunner.class) @PowerMockRunnerDelegate(Parameterized.class) @PrepareForTest(SuppressConstructorHierarchy.class) public class SuppressConstructorHierarchyDemoTest { @Parameterized.Parameter public boolean suppress; @Parameterized.Parameters(name = "suppress={0}") public static List false_or_true() { return Arrays.asList(new Object[][]{{false}, {true}}); } @Before public void suppressOnDemand() { if (suppress) { suppress(constructor(SuppressConstructorHierarchy.class)); } } @Test public void directConstructorUsage() throws Exception { System.out.println("ClassLoader: " + getClass().getClassLoader()); try { SuppressConstructorHierarchy tested = new SuppressConstructorHierarchy("message"); if (suppress) { assertNull( "Message should have been null since we're skipping the execution of the constructor code. Message was \"message\".", tested.getMessage()); assertEquals("getNumber() value", 42, tested.getNumber()); } else { fail("Expected RuntimeException"); } } catch (RuntimeException ex) { if (suppress) { throw ex; } else { assertEquals("This should be suppressed!!", ex.getMessage()); } } } @Test public void useConstructorInvoker() throws Exception { System.out.println("ClassLoader: " + getClass().getClassLoader()); try { final String message = new InvokeConstructor().doStuff("qwe"); if (suppress) { assertNull("Message should have been null since we're skipping the execution of the constructor code. Message was \"" + message + "\".", message); } else { fail("Expected RuntimeException"); } } catch (RuntimeException ex) { if (suppress) { throw ex; } else { assertEquals("This should be suppressed!!", ex.getMessage()); } } } @Test @PrepareForTest public void suppressWithoutByteCodeManipulation() throws Exception { System.out.println("ClassLoader: " + getClass().getClassLoader()); try { new InvokeConstructor().doStuff("qwe"); fail("Should throw RuntimeException since we're running this test with a new class loader!"); } catch (RuntimeException ex) { assertEquals("This should be suppressed!!", ex.getMessage()); } } } ================================================ FILE: tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/parameterized/SupressMethodExampleTest.java ================================================ /* * Copyright 2011-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package powermock.modules.test.mockito.junit4.delegate.parameterized; import java.util.Arrays; import java.util.Collection; import org.hamcrest.Matcher; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunnerDelegate; import samples.suppressconstructor.SuppressConstructorHierarchy; import samples.suppresseverything.SuppressEverything; import samples.suppressfield.SuppressField; import samples.suppressmethod.SuppressMethod; import samples.suppressfield.DomainObject; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.*; import static org.powermock.api.support.membermodification.MemberModifier.*; /** * Demonstrates PowerMock's ability to modify member structures. */ @RunWith(PowerMockRunner.class) @PowerMockRunnerDelegate(Parameterized.class) @PrepareForTest({SuppressMethod.class, SuppressField.class, SuppressEverything.class}) public class SupressMethodExampleTest { enum GetObjectSuppression { DONT_SUPPRESS(SuppressMethod.OBJECT), SUPPRESS(null) { @Override void doIt() { suppress(method(SuppressMethod.class, "getObject")); } }; final Object expectedReturnValue; GetObjectSuppression(Object expectedReturnValue) { this.expectedReturnValue = expectedReturnValue; } void doIt() { } } enum GetIntSuppression { DONT_SUPPRESS(Integer.MAX_VALUE), SUPPRESS(0) { @Override void doIt() { suppress(method(SuppressMethod.class, "getInt")); } }; final int expectedReturnValue; GetIntSuppression(int expectedReturnValue) { this.expectedReturnValue = expectedReturnValue; } void doIt() { } } enum FieldSuppression { DONT_SUPPRESS(instanceOf(DomainObject.class)), SUPPRESS(nullValue()) { @Override void doIt() { suppress(field(SuppressField.class, "domainObject")); } }; final Matcher expectation; private FieldSuppression(Matcher expectation) { this.expectation = expectation; } void doIt() { } } final GetObjectSuppression getObjectSuppression; final GetIntSuppression getIntSuppression; final FieldSuppression fieldSuppression; final boolean suppressConstructor; @Rule public final ExpectedException expectedException = ExpectedException.none(); public SupressMethodExampleTest( GetObjectSuppression getObjectSuppression, GetIntSuppression getIntSuppression, FieldSuppression fieldSuppression, Boolean suppressConstructor) { this.getObjectSuppression = getObjectSuppression; this.getIntSuppression = getIntSuppression; this.fieldSuppression = fieldSuppression; this.suppressConstructor = suppressConstructor; } @Parameterized.Parameters(name = "getObject={0} getInt={1} field={2} suppressConstructor={3}") public static Collection suppressionParamValues() { return Arrays.asList(new Object[][]{ {GetObjectSuppression.DONT_SUPPRESS, GetIntSuppression.DONT_SUPPRESS, FieldSuppression.DONT_SUPPRESS, false}, {GetObjectSuppression.DONT_SUPPRESS, GetIntSuppression.SUPPRESS, FieldSuppression.DONT_SUPPRESS, false}, {GetObjectSuppression.SUPPRESS, GetIntSuppression.DONT_SUPPRESS, FieldSuppression.DONT_SUPPRESS, true}, {GetObjectSuppression.SUPPRESS, GetIntSuppression.SUPPRESS, FieldSuppression.DONT_SUPPRESS, true}, {GetObjectSuppression.DONT_SUPPRESS, GetIntSuppression.DONT_SUPPRESS, FieldSuppression.SUPPRESS, true}, {GetObjectSuppression.DONT_SUPPRESS, GetIntSuppression.SUPPRESS, FieldSuppression.SUPPRESS, true}, {GetObjectSuppression.SUPPRESS, GetIntSuppression.DONT_SUPPRESS, FieldSuppression.SUPPRESS, false}, {GetObjectSuppression.SUPPRESS, GetIntSuppression.SUPPRESS, FieldSuppression.SUPPRESS, false},}); } @Test public void verifySuppression() throws Exception { getObjectSuppression.doIt(); getIntSuppression.doIt(); fieldSuppression.doIt(); assertEquals("getObject return-value", getObjectSuppression.expectedReturnValue, new SuppressMethod().getObject()); assertEquals("getInt return-value", getIntSuppression.expectedReturnValue, new SuppressMethod().getInt()); assertThat("Value from field", new SuppressField().getDomainObject(), is(fieldSuppression.expectation)); if (suppressConstructor) { suppress(constructor(SuppressConstructorHierarchy.class)); } else { expectedException.expect(RuntimeException.class); } SuppressConstructorHierarchy tested = new SuppressConstructorHierarchy("message"); assertTrue("Or a runtime exception should have been thrown by now", suppressConstructor); assertEquals(42, tested.getNumber()); assertNull(tested.getMessage()); } } ================================================ FILE: tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/parameterized/SystemClassUserTest.java ================================================ /* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package powermock.modules.test.mockito.junit4.delegate.parameterized; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.model.Statement; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunnerDelegate; import powermock.modules.test.mockito.junit4.delegate.SystemClassUserCases; import powermock.modules.test.mockito.junit4.delegate.SystemClassUserMethod; import samples.system.SystemClassUser; /** * Demonstrates PowerMockito's ability to mock non-final and final system * classes. To mock a system class you need to prepare the calling class for * testing. I.e. let's say you're testing class A which interacts with * URLEncoder then you would do: * *
 *
 * @PrepareForTest({A.class})
 *
 * 
*/ @RunWith(PowerMockRunner.class) @PowerMockRunnerDelegate(Parameterized.class) @PrepareForTest({SystemClassUserCases.class, SystemClassUser.class}) public class SystemClassUserTest { final Statement test; public SystemClassUserTest(final SystemClassUserMethod testCase) { test = new Statement() { @Override public void evaluate() throws Throwable { try { testCase.getMethod().invoke(new SystemClassUserCases()); } catch (InvocationTargetException ex) { throw ex.getTargetException(); } } }; } @Parameterized.Parameters(name = "{0}") public static List paramValues() { List values = new ArrayList(); for (SystemClassUserMethod tstCase : SystemClassUserMethod.values()) { values.add(new Object[]{tstCase}); } return values; } @Test public void __() throws Throwable { test.evaluate(); } } ================================================ FILE: tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/parameterized/WhenNewTest.java ================================================ /* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package powermock.modules.test.mockito.junit4.delegate.parameterized; import org.powermock.core.classloader.annotations.PrepareForTest; import samples.classwithinnermembers.ClassWithInnerMembers; import samples.expectnew.ExpectNewDemo; import samples.newmocking.MyClass; import java.io.DataInputStream; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunnerDelegate; import powermock.modules.test.mockito.junit4.delegate.WhenNewCaseMethod; import samples.powermockito.junit4.whennew.WhenNewCases; @PrepareForTest({MyClass.class, ExpectNewDemo.class, ClassWithInnerMembers.class, DataInputStream.class, WhenNewCases.class}) @RunWith(PowerMockRunner.class) @PowerMockRunnerDelegate(Parameterized.class) public class WhenNewTest { @Rule public final ExpectedException ee = ExpectedException.none(); @Parameterized.Parameter(0) public WhenNewCaseMethod whenNewCase; @Test public void test() throws Throwable { if (whenNewCase.nullPointerIsExpected()) { ee.expect(NullPointerException.class); } whenNewCase.runTest(); } @Parameterized.Parameters(name = "{0}") public static Collection whenNewCases() { WhenNewCaseMethod[] cases = WhenNewCaseMethod.values(); List paramValues = new ArrayList(cases.length); for (WhenNewCaseMethod each : cases) { paramValues.add(new Object[]{each}); } return paramValues; } } ================================================ FILE: tests/mockito/junit4-rule-objenesis/src/test/java/samples/powermockito/junit4/rule/objenesis/Foo.java ================================================ package samples.powermockito.junit4.rule.objenesis; public class Foo { public Bar m() { return new Bar(1); } @SuppressWarnings("SameParameterValue") public static class Bar { private final int i; Bar(final int i) { this.i = i; } public int getI() { return i; } } } ================================================ FILE: tests/mockito/junit4-rule-objenesis/src/test/java/samples/powermockito/junit4/rule/objenesis/MockFinalNonStaticMethodsTest.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.rule.objenesis; import org.junit.Rule; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.rule.PowerMockRule; import samples.finalmocking.FinalDemo; import samples.powermockito.junit4.finalmocking.MockFinalMethodsCases; import samples.privateandfinal.PrivateFinal; /** * Test class to demonstrate non-static final mocking with Mockito. */ @PrepareForTest( { FinalDemo.class, PrivateFinal.class }) public class MockFinalNonStaticMethodsTest extends MockFinalMethodsCases { @Rule public PowerMockRule powerMockRule = new PowerMockRule(); } ================================================ FILE: tests/mockito/junit4-rule-objenesis/src/test/java/samples/powermockito/junit4/rule/objenesis/MockStaticTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.rule.objenesis; import org.junit.Rule; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.rule.PowerMockRule; import samples.powermockito.junit4.staticmocking.MockStaticCases; import samples.singleton.SimpleStaticService; import samples.singleton.StaticService; /** * Test class to demonstrate static mocking with PowerMockito. */ @PrepareForTest({StaticService.class, SimpleStaticService.class}) public class MockStaticTest extends MockStaticCases { @Rule public PowerMockRule rule = new PowerMockRule(); } ================================================ FILE: tests/mockito/junit4-rule-objenesis/src/test/java/samples/powermockito/junit4/rule/objenesis/PowerMockRuleTest.java ================================================ package samples.powermockito.junit4.rule.objenesis; import org.junit.Rule; import org.junit.Test; import org.powermock.core.classloader.annotations.MockPolicy; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.core.spi.PowerMockPolicy; import org.powermock.mockpolicies.MockPolicyClassLoadingSettings; import org.powermock.mockpolicies.MockPolicyInterceptionSettings; import org.powermock.modules.junit4.rule.PowerMockRule; import org.powermock.reflect.Whitebox; import samples.powermockito.junit4.rule.objenesis.Foo.Bar; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @PowerMockIgnore({"org.mockito.*","org.powermock.api.mockito.repackaged.*"}) @PrepareForTest(Foo.class) @MockPolicy(PowerMockRuleTest.CustomPolicy.class) public class PowerMockRuleTest { @Rule public final PowerMockRule rule = new PowerMockRule(); @Test public void test1() { assertEquals(999, new Foo().m().getI()); } @Test public void test2() { assertEquals(999, new Foo().m().getI()); } public static class CustomPolicy implements PowerMockPolicy { @Override public void applyClassLoadingPolicy(MockPolicyClassLoadingSettings settings) { } @Override public void applyInterceptionPolicy(MockPolicyInterceptionSettings settings) { final Bar barMock = mock(Bar.class); when(barMock.getI()).thenReturn(999); settings.stubMethod(Whitebox.getMethod(Foo.class, "m"), barMock); } } } ================================================ FILE: tests/mockito/junit4-rule-objenesis/src/test/java/samples/powermockito/junit4/rule/objenesis/PrivateInstanceMockingTest.java ================================================ package samples.powermockito.junit4.rule.objenesis; import org.junit.Rule; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.rule.PowerMockRule; import samples.powermockito.junit4.privatemocking.PrivateInstanceMockingCases; import samples.privatemocking.PrivateMethodDemo; @PrepareForTest( { PrivateMethodDemo.class }) public class PrivateInstanceMockingTest extends PrivateInstanceMockingCases { @Rule public PowerMockRule powerMockRule = new PowerMockRule(); } ================================================ FILE: tests/mockito/junit4-rule-objenesis/src/test/java/samples/powermockito/junit4/rule/objenesis/StaticInitializerExampleTest.java ================================================ package samples.powermockito.junit4.rule.objenesis; import org.junit.Rule; import org.junit.Test; import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor; import org.powermock.modules.junit4.rule.PowerMockRule; import org.powermock.reflect.Whitebox; import samples.staticinitializer.StaticInitializerExample; import java.util.HashSet; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; @SuppressStaticInitializationFor("samples.staticinitializer.StaticInitializerExample") public class StaticInitializerExampleTest { @Rule public PowerMockRule rule = new PowerMockRule(); @Test public void testSupressStaticInitializerAndSetFinalField() throws Exception { assertNull("Should be null because the static initializer should be suppressed", StaticInitializerExample.getMySet()); final HashSet hashSet = new HashSet(); Whitebox.setInternalState(StaticInitializerExample.class, "mySet", hashSet); assertSame(hashSet, Whitebox.getInternalState(StaticInitializerExample.class, "mySet")); } } ================================================ FILE: tests/mockito/junit4-rule-objenesis/src/test/java/samples/powermockito/junit4/rule/objenesis/SystemClassUserTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.rule.objenesis; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.rule.PowerMockRule; import samples.system.SystemClassUser; import java.net.URLEncoder; import java.util.Collections; import java.util.LinkedList; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import static org.mockito.Mockito.times; import static org.powermock.api.mockito.PowerMockito.mock; import static org.powermock.api.mockito.PowerMockito.mockStatic; import static org.powermock.api.mockito.PowerMockito.spy; import static org.powermock.api.mockito.PowerMockito.verifyStatic; import static org.powermock.api.mockito.PowerMockito.when; /** * Demonstrates PowerMockito's ability to mock non-final and final system * classes. To mock a system class you need to prepare the calling class for * testing. I.e. let's say you're testing class A which interacts with * URLEncoder then you would do: *

*

 *
 * @PrepareForTest({A.class})
 *
 * 
*/ @PrepareForTest({SystemClassUser.class}) @Ignore public class SystemClassUserTest { @Rule public PowerMockRule powerMockRule = new PowerMockRule(); @Test public void assertThatMockingOfNonFinalSystemClassesWorks() throws Exception { mockStatic(URLEncoder.class); when(URLEncoder.encode("string", "enc")).thenReturn("something"); assertEquals("something", new SystemClassUser().performEncode()); } @Test public void assertThatMockingOfTheRuntimeSystemClassWorks() throws Exception { mockStatic(Runtime.class); Runtime runtimeMock = mock(Runtime.class); Process processMock = mock(Process.class); when(Runtime.getRuntime()).thenReturn(runtimeMock); when(runtimeMock.exec("command")).thenReturn(processMock); assertSame(processMock, new SystemClassUser().executeCommand()); } @Test public void assertThatMockingOfFinalSystemClassesWorks() throws Exception { mockStatic(System.class); when(System.getProperty("property")).thenReturn("my property"); assertEquals("my property", new SystemClassUser().getSystemProperty()); } @Test public void assertThatPartialMockingOfFinalSystemClassesWorks() throws Exception { spy(System.class); when(System.nanoTime()).thenReturn(2L); new SystemClassUser().doMoreComplicatedStuff(); assertEquals("2", System.getProperty("nanoTime")); } @Test public void assertThatMockingOfCollectionsWork() throws Exception { List list = new LinkedList(); mockStatic(Collections.class); Collections.shuffle(list); new SystemClassUser().shuffleCollection(list); verifyStatic(Collections.class, times(2)); Collections.shuffle(list); } @Test public void assertThatPartialMockingOfFinalSystemClassesWorksForNonVoidMethods() throws Exception { spy(System.class); when(System.getProperty("property")).thenReturn("my property"); final SystemClassUser systemClassUser = new SystemClassUser(); systemClassUser.copyProperty("to", "property"); } @Test public void assertThatMockingStringWorks() throws Exception { mockStatic(String.class); final String string = "string"; final String args = "args"; final String returnValue = "returnValue"; when(String.format(string, args)).thenReturn(returnValue); final SystemClassUser systemClassUser = new SystemClassUser(); assertEquals(systemClassUser.format(string, args), returnValue); } } ================================================ FILE: tests/mockito/junit4-rule-objenesis/src/test/java/samples/powermockito/junit4/rule/objenesis/WhenNewTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.rule.objenesis; import org.junit.Ignore; import org.junit.Rule; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.rule.PowerMockRule; import samples.expectnew.ExpectNewDemo; import samples.newmocking.MyClass; import samples.powermockito.junit4.whennew.WhenNewCases; import java.io.DataInputStream; /** * Test class to demonstrate new instance mocking using whenConstructionOf(..). * */ @SuppressWarnings("PrimitiveArrayArgumentToVariableArgMethod") @Ignore("Since upgrading to JVM 1.6.0_24 lots of tests started to fail") @PrepareForTest({ MyClass.class, ExpectNewDemo.class, DataInputStream.class }) public class WhenNewTest extends WhenNewCases { @Rule public PowerMockRule powerMockRule = new PowerMockRule(); } ================================================ FILE: tests/mockito/junit4-rule-objenesis/src/test/java/samples/powermockito/junit4/rule/objenesis/bugs/github512/Github512Test.java ================================================ package samples.powermockito.junit4.rule.objenesis.bugs.github512; import org.junit.Rule; import org.junit.Test; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.rule.PowerMockRule; import samples.singleton.StaticService; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.powermock.api.mockito.PowerMockito.method; import static org.powermock.api.mockito.PowerMockito.suppress; public class Github512Test { @Rule public PowerMockRule rule = new PowerMockRule(); @Test @PrepareForTest(StaticService.class) public void shouldSuppressMethodWithPrepareForTestOnMethod() { suppress(method(StaticService.class, "calculate")); assertThat(StaticService.calculate(1, 5)).isEqualTo(0); } } ================================================ FILE: tests/mockito/junit4-rule-objenesis/src/test/java/samples/powermockito/junit4/rule/objenesis/bugs/github512/package-info.java ================================================ /** * https://github.com/jayway/powermock/issues/512 */ package samples.powermockito.junit4.rule.objenesis.bugs.github512; ================================================ FILE: tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/AssertPowerMockRuleDelagatesToOtherRulesTest.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.rule.xstream; import org.junit.Rule; import org.junit.Test; import org.junit.rules.MethodRule; import org.junit.rules.TestName; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.Statement; import org.powermock.core.classloader.MockClassLoader; import org.powermock.modules.junit4.rule.PowerMockRule; import java.util.LinkedList; import java.util.List; import static junit.framework.Assert.assertTrue; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.junit.Assert.assertEquals; /** * This test demonstrates that the PowerMockRule delegates to other rules. */ public class AssertPowerMockRuleDelagatesToOtherRulesTest { private static final MyObject BEFORE = new MyObject(); private final List objects = new LinkedList(); @Rule public PowerMockRule powerMockRule = new PowerMockRule(); @Rule public MyRule rule = new MyRule(); @Rule public TestName testName = new TestName(); @Test public void assertPowerMockRuleDelegatesToOtherRules() throws Exception { assertThat(this.getClass().getClassLoader()).isInstanceOf(MockClassLoader.class); assertThat(objects) .hasSize(1) .containsExactly(BEFORE); assertThat(testName.getMethodName()).isEqualTo("assertPowerMockRuleDelegatesToOtherRules"); } private class MyRule implements MethodRule { public Statement apply(final Statement base, FrameworkMethod method, Object target) { return new Statement() { @Override public void evaluate() throws Throwable { objects.add(BEFORE); base.evaluate(); } }; } } private static class MyObject { private final String state = "state"; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MyObject myObject = (MyObject) o; return state.equals(myObject.state); } @Override public int hashCode() { return state.hashCode(); } } } ================================================ FILE: tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/Foo.java ================================================ package samples.powermockito.junit4.rule.xstream; public class Foo { public Bar m() { return new Bar(1); } @SuppressWarnings("SameParameterValue") public static class Bar { private final int i; Bar(final int i) { this.i = i; } public int getI() { return i; } } } ================================================ FILE: tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/MockFinalNonStaticMethodsTest.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.rule.xstream; import org.junit.Rule; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.rule.PowerMockRule; import samples.finalmocking.FinalDemo; import samples.powermockito.junit4.finalmocking.MockFinalMethodsCases; import samples.privateandfinal.PrivateFinal; /** * Test class to demonstrate non-static final mocking with Mockito. */ @PrepareForTest( { FinalDemo.class, PrivateFinal.class }) public class MockFinalNonStaticMethodsTest extends MockFinalMethodsCases{ @Rule public PowerMockRule powerMockRule = new PowerMockRule(); } ================================================ FILE: tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/MockStaticTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.rule.xstream; import org.junit.Rule; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.rule.PowerMockRule; import samples.powermockito.junit4.staticmocking.MockStaticCases; import samples.singleton.SimpleStaticService; import samples.singleton.StaticService; /** * Test class to demonstrate static mocking with PowerMockito. */ @PrepareForTest({StaticService.class, SimpleStaticService.class}) public class MockStaticTest extends MockStaticCases { @Rule public PowerMockRule rule = new PowerMockRule(); } ================================================ FILE: tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/PowerMockRuleTest.java ================================================ package samples.powermockito.junit4.rule.xstream; import org.junit.Rule; import org.junit.Test; import org.powermock.core.classloader.annotations.MockPolicy; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.core.spi.PowerMockPolicy; import org.powermock.mockpolicies.MockPolicyClassLoadingSettings; import org.powermock.mockpolicies.MockPolicyInterceptionSettings; import org.powermock.modules.junit4.rule.PowerMockRule; import org.powermock.reflect.Whitebox; import samples.powermockito.junit4.rule.xstream.Foo.Bar; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @PowerMockIgnore({"org.mockito.*","org.powermock.api.mockito.repackaged.*"}) @PrepareForTest(Foo.class) @MockPolicy(PowerMockRuleTest.CustomPolicy.class) public class PowerMockRuleTest { @Rule public final PowerMockRule rule = new PowerMockRule(); @Test public void test1() { assertEquals(999, new Foo().m().getI()); } @Test public void test2() { assertEquals(999, new Foo().m().getI()); } public static class CustomPolicy implements PowerMockPolicy { @Override public void applyClassLoadingPolicy(MockPolicyClassLoadingSettings settings) { } @Override public void applyInterceptionPolicy(MockPolicyInterceptionSettings settings) { final Bar barMock = mock(Bar.class); when(barMock.getI()).thenReturn(999); settings.stubMethod(Whitebox.getMethod(Foo.class, "m"), barMock); } } } ================================================ FILE: tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/PrivateInstanceMockingTest.java ================================================ package samples.powermockito.junit4.rule.xstream; import org.junit.Rule; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.rule.PowerMockRule; import samples.powermockito.junit4.privatemocking.PrivateInstanceMockingCases; import samples.privatemocking.PrivateMethodDemo; @PrepareForTest( { PrivateMethodDemo.class }) public class PrivateInstanceMockingTest extends PrivateInstanceMockingCases { @Rule public PowerMockRule powerMockRule = new PowerMockRule(); } ================================================ FILE: tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/StaticInitializerExampleTest.java ================================================ package samples.powermockito.junit4.rule.xstream; import org.junit.Rule; import org.junit.Test; import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor; import org.powermock.modules.junit4.rule.PowerMockRule; import org.powermock.reflect.Whitebox; import samples.staticinitializer.StaticInitializerExample; import java.util.HashSet; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; @SuppressStaticInitializationFor("samples.staticinitializer.StaticInitializerExample") public class StaticInitializerExampleTest { @Rule public PowerMockRule rule = new PowerMockRule(); @Test public void testSupressStaticInitializerAndSetFinalField() throws Exception { assertNull("Should be null because the static initializer should be suppressed", StaticInitializerExample.getMySet()); final HashSet hashSet = new HashSet(); Whitebox.setInternalState(StaticInitializerExample.class, "mySet", hashSet); assertSame(hashSet, Whitebox.getInternalState(StaticInitializerExample.class, "mySet")); } } ================================================ FILE: tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/SystemClassUserTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.rule.xstream; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.rule.PowerMockRule; import samples.system.SystemClassUser; import java.net.URLEncoder; import java.util.Collections; import java.util.LinkedList; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import static org.mockito.Mockito.times; import static org.powermock.api.mockito.PowerMockito.mock; import static org.powermock.api.mockito.PowerMockito.mockStatic; import static org.powermock.api.mockito.PowerMockito.spy; import static org.powermock.api.mockito.PowerMockito.verifyStatic; import static org.powermock.api.mockito.PowerMockito.when; /** * Demonstrates PowerMockito's ability to mock non-final and final system * classes. To mock a system class you need to prepare the calling class for * testing. I.e. let's say you're testing class A which interacts with * URLEncoder then you would do: * *
 * 
 * @PrepareForTest({A.class})
 * 
 * 
*/ @PrepareForTest( { SystemClassUser.class }) @Ignore public class SystemClassUserTest { @Rule public PowerMockRule powerMockRule = new PowerMockRule(); @Test public void assertThatMockingOfNonFinalSystemClassesWorks() throws Exception { mockStatic(URLEncoder.class); when(URLEncoder.encode("string", "enc")).thenReturn("something"); assertEquals("something", new SystemClassUser().performEncode()); } @Test public void assertThatMockingOfTheRuntimeSystemClassWorks() throws Exception { mockStatic(Runtime.class); Runtime runtimeMock = mock(Runtime.class); Process processMock = mock(Process.class); when(Runtime.getRuntime()).thenReturn(runtimeMock); when(runtimeMock.exec("command")).thenReturn(processMock); assertSame(processMock, new SystemClassUser().executeCommand()); } @Test public void assertThatMockingOfFinalSystemClassesWorks() throws Exception { mockStatic(System.class); when(System.getProperty("property")).thenReturn("my property"); assertEquals("my property", new SystemClassUser().getSystemProperty()); } @Test public void assertThatPartialMockingOfFinalSystemClassesWorks() throws Exception { spy(System.class); when(System.nanoTime()).thenReturn(2L); new SystemClassUser().doMoreComplicatedStuff(); assertEquals("2", System.getProperty("nanoTime")); } @Test public void assertThatMockingOfCollectionsWork() throws Exception { List list = new LinkedList(); mockStatic(Collections.class); Collections.shuffle(list); new SystemClassUser().shuffleCollection(list); verifyStatic(Collections.class, times(2)); Collections.shuffle(list); } @Test public void assertThatPartialMockingOfFinalSystemClassesWorksForNonVoidMethods() throws Exception { spy(System.class); when(System.getProperty("property")).thenReturn("my property"); final SystemClassUser systemClassUser = new SystemClassUser(); systemClassUser.copyProperty("to", "property"); } @Test public void assertThatMockingStringWorks() throws Exception { mockStatic(String.class); final String string = "string"; final String args = "args"; final String returnValue = "returnValue"; when(String.format(string, args)).thenReturn(returnValue); final SystemClassUser systemClassUser = new SystemClassUser(); assertEquals(systemClassUser.format(string, args), returnValue); } } ================================================ FILE: tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/WhenNewTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.rule.xstream; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.powermock.modules.junit4.rule.PowerMockRule; import samples.powermockito.junit4.whennew.WhenNewCases; /** * Test class to demonstrate new instance mocking using whenConstructionOf(..). * */ @SuppressWarnings("PrimitiveArrayArgumentToVariableArgMethod") public class WhenNewTest extends WhenNewCases{ @Rule public PowerMockRule powerMockRule = new PowerMockRule(); @Ignore("Test case fails only for xstream with MockitoException: Mockito cannot mock this class: " + "class samples.classwithinnermembers.ClassWithInnerMembers$1MyLocalClass") @Test @Override public void testLocalClassMockingWorksWithNoConstructorArguments() throws Exception { super.testLocalClassMockingWorksWithNoConstructorArguments(); } @Ignore("Test case fails only for xstream with MockitoException: Mockito cannot mock this class: " + "class samples.classwithinnermembers.ClassWithInnerMembers$2MyLocalClass") @Test @Override public void testLocalClassMockingWorksWithConstructorArguments() throws Exception { super.testLocalClassMockingWorksWithConstructorArguments(); } } ================================================ FILE: tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/github512/Github512Test.java ================================================ package samples.powermockito.junit4.rule.xstream.github512; import org.junit.Rule; import org.junit.Test; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.rule.PowerMockRule; import samples.singleton.StaticService; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.powermock.api.mockito.PowerMockito.method; import static org.powermock.api.mockito.PowerMockito.suppress; public class Github512Test { @Rule public PowerMockRule rule = new PowerMockRule(); @Test @PrepareForTest(StaticService.class) public void shouldSuppressMethodWithPrepareForTestOnMethod() { suppress(method(StaticService.class, "calculate")); assertThat(StaticService.calculate(1, 5)).isEqualTo(0); } } ================================================ FILE: tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/github512/package-info.java ================================================ /** * https://github.com/jayway/powermock/issues/512 */ package samples.powermockito.junit4.rule.xstream.github512; ================================================ FILE: tests/mockito/junit49/src/test/java/samples/powermockito/junit4/rules/JUnit49RuleTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.junit4.rules; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runner.RunWith; import org.junit.runners.model.Statement; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.util.LinkedList; import java.util.List; /** * JUnit 4.9 changed the implementation/execution of Rules. * Demonstrates that issue 344 * is resolved. */ @RunWith(PowerMockRunner.class) @PrepareForTest( { JUnit49RuleTest.class }) public class JUnit49RuleTest { private static Object BEFORE = new Object(); private List objects = new LinkedList(); @Rule public MyRule rule = new MyRule(); @Rule public TestName testName = new TestName(); @Test public void assertThatJUnit47RulesWorks() throws Exception { assertEquals(1, objects.size()); assertSame(BEFORE, objects.get(0)); assertEquals("assertThatJUnit47RulesWorks", testName.getMethodName()); } private class MyRule implements TestRule { @Override public Statement apply(final Statement statement, Description description) { return new Statement() { @Override public void evaluate() throws Throwable { objects.add(BEFORE); statement.evaluate(); } }; } } } ================================================ FILE: tests/mockito/testng/src/test/java/samples/powermockito/testng/staticmocking/MockStaticNotPreparedTest.java ================================================ package samples.powermockito.testng.staticmocking; import org.powermock.api.mockito.ClassNotPreparedException; import org.powermock.modules.testng.PowerMockTestCase; import org.testng.annotations.Test; import samples.singleton.StaticService; import static org.powermock.api.mockito.PowerMockito.mockStatic; public class MockStaticNotPreparedTest extends PowerMockTestCase { @Test(expectedExceptions = ClassNotPreparedException.class) public void should_throw_exception_if_class_not_prepared_for_test() throws Exception { mockStatic(StaticService.class); } } ================================================ FILE: tests/mockito/testng/src/test/java/samples/powermockito/testng/staticmocking/MockStaticPreparedWithoutMockStaticTest.java ================================================ package samples.powermockito.testng.staticmocking; import org.mockito.exceptions.misusing.MissingMethodInvocationException; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.testng.PowerMockTestCase; import org.testng.annotations.Test; import samples.singleton.StaticService; import static org.powermock.api.mockito.PowerMockito.when; @PrepareForTest(StaticService.class) public class MockStaticPreparedWithoutMockStaticTest extends PowerMockTestCase { //FIXME? Cannot override reporter in Mockito2 @Test(expectedExceptions = MissingMethodInvocationException.class, expectedExceptionsMessageRegExp = "(?s).*PrepareForTest(?s).*", enabled = false) @Test(expectedExceptions = MissingMethodInvocationException.class, enabled = false) public void testWhenNotPrepared() throws Exception { when(StaticService.say("Hello")).thenReturn("Hello World!"); } } ================================================ FILE: tests/mockito/testng/src/test/java/samples/powermockito/testng/staticmocking/MockitoMockStaticTest.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.powermockito.testng.staticmocking; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.testng.PowerMockObjectFactory; import org.testng.Assert; import org.testng.IObjectFactory; import org.testng.annotations.ObjectFactory; import org.testng.annotations.Test; import samples.singleton.StaticHelper; import samples.singleton.StaticService; import static org.powermock.api.mockito.PowerMockito.mockStatic; import static org.powermock.api.mockito.PowerMockito.verifyStatic; import static org.powermock.api.mockito.PowerMockito.when; /** * Test class to demonstrate static, static+final, static+native and * static+final+native methods mocking. */ @PrepareForTest({StaticService.class, StaticHelper.class}) public class MockitoMockStaticTest { @ObjectFactory public IObjectFactory getObjectFactory() { return new PowerMockObjectFactory(); } @Test public void testMockStatic() throws Exception { System.out.println("Skip test while Mockito doesn't deliver fix"); mockStatic(StaticService.class); String expected = "Hello altered World"; when(StaticService.say("hello")).thenReturn("Hello altered World"); String actual = StaticService.say("hello"); verifyStatic(StaticService.class); StaticService.say("hello"); Assert.assertEquals(expected, actual); } @Test public void testMockStaticFinal() throws Exception { System.out.println("Skip test while Mockito doesn't deliver fix"); mockStatic(StaticService.class); String expected = "Hello altered World"; when(StaticService.sayFinal("hello")).thenReturn("Hello altered World"); String actual = StaticService.sayFinal("hello"); verifyStatic(StaticService.class); StaticService.sayFinal("hello"); Assert.assertEquals(expected, actual); } } ================================================ FILE: tests/mockito/testng/src/test/java/samples/testng/bugs/github656/GitHub656Test.java ================================================ package samples.testng.bugs.github656; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.testng.PowerMockTestCase; import org.testng.annotations.Test; import static org.mockito.Mockito.verify; /** * */ @PrepareForTest({ GitHub656Test.SimpleFoo.class }) public class GitHub656Test extends PowerMockTestCase { @Test public void should_be_only_one_invocation() { GitHub656Test.SimpleFoo foo = PowerMockito.spy(new GitHub656Test.SimpleFoo()); foo.setFoo(" "); verify(foo).setFoo(" "); } public static class SimpleFoo { private String foo; public void setFoo(String foo) { this.foo = foo; } public String getFoo() { return foo; } } } ================================================ FILE: tests/mockito/testng/src/test/java/samples/testng/bugs/github656/package-info.java ================================================ /** * TooManyActualInvocations when class is prepared for test. * https://github.com/jayway/powermock/issues/656 */ package samples.testng.bugs.github656; ================================================ FILE: tests/mockito/testng/suite.xml ================================================ ================================================ FILE: tests/testng/src/test/java/samples/testng/SimpleBaseTest.java ================================================ package samples.testng; import org.testng.Assert; import org.testng.ITestResult; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.collections.Lists; import org.testng.xml.XmlClass; import org.testng.xml.XmlInclude; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import java.io.File; import java.util.Arrays; import java.util.Iterator; import java.util.List; public class SimpleBaseTest { private static final String TEST_RESOURCES_DIR = "test.resources.dir"; public static TestNG create() { TestNG result = new TestNG(); result.setUseDefaultListeners(false); result.setVerbose(0); return result; } public static TestNG create(Class... testClasses) { TestNG result = create(); result.setTestClasses(testClasses); return result; } public static String getPathToResource(String fileName) { String result = System.getProperty(TEST_RESOURCES_DIR); if (result == null) { throw new IllegalArgumentException("System property " + TEST_RESOURCES_DIR + " was not defined."); } return result + File.separatorChar + fileName; } /** * Compare a list of ITestResult with a list of String method names, */ public static void assertTestResultsEqual(List results, List methods) { List resultMethods = Lists.newArrayList(); for (ITestResult r : results) { resultMethods.add(r.getMethod().getMethodName()); } Assert.assertEquals(resultMethods, methods); } protected TestNG create(XmlSuite... suites) { TestNG result = create(); result.setXmlSuites(Arrays.asList(suites)); return result; } protected TestNG createTests(String suiteName, Class... testClasses) { XmlSuite suite = createXmlSuite(suiteName); int i = 0; for (Class testClass : testClasses) { createXmlTest(suite, testClass.getName() + i, testClass); i++; } return create(suite); } protected XmlSuite createXmlSuite(String name) { XmlSuite result = new XmlSuite(); result.setName(name); return result; } protected XmlTest createXmlTest(XmlSuite suite, String name, Class clazz, Class... classes) { XmlTest result = new XmlTest(suite); int index = 0; result.setName(name); XmlClass xc = new XmlClass(clazz.getName(), index++, true /* load classes */); result.getXmlClasses().add(xc); for (Class c : classes) { xc = new XmlClass(c.getName(), index++, true /* load classes */); result.getXmlClasses().add(xc); } return result; } protected XmlTest createXmlTest(XmlSuite suite, String name, String... classes) { XmlTest result = new XmlTest(suite); int index = 0; result.setName(name); for (String c : classes) { XmlClass xc = new XmlClass(c, index++, true /* load classes */); result.getXmlClasses().add(xc); } return result; } protected void addMethods(XmlClass cls, String... methods) { int index = 0; for (String m : methods) { XmlInclude include = new XmlInclude(m, index++); cls.getIncludedMethods().add(include); } } protected void verifyPassedTests(TestListenerAdapter tla, String... methodNames) { Iterator it = tla.getPassedTests().iterator(); Assert.assertEquals(tla.getPassedTests().size(), methodNames.length); int i = 0; while (it.hasNext()) { Assert.assertEquals(it.next().getName(), methodNames[i++]); } } } ================================================ FILE: tests/testng/src/test/java/samples/testng/bugs/github647/GitHub647.java ================================================ package samples.testng.bugs.github647; import org.testng.IResultMap; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import samples.testng.SimpleBaseTest; import java.net.URL; import java.net.URLClassLoader; import static org.testng.Assert.assertEquals; public class GitHub647 extends SimpleBaseTest { private final TestListenerAdapter tla; public GitHub647() { tla = new TestListenerAdapter(); } @Test public void testSkipTest() throws Exception { final TestNG tng = createTestNG(); runTest(tng); assertOneTestSkipped(); } private TestNG createTestNG() { final TestNG tng = create(SkipExceptionTest.class); tng.setThreadCount(1); tng.setParallel(XmlSuite.ParallelMode.NONE); tng.setPreserveOrder(true); tng.addListener(tla); return tng; } private void assertOneTestSkipped() { IResultMap skippedTests = tla.getTestContexts().get(0).getSkippedTests(); assertEquals(1, skippedTests.size()); } private void runTest(TestNG tng) { ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader(); ClassLoader classLoader = new SimpleClassLoader(currentClassLoader); Thread.currentThread().setContextClassLoader(classLoader); tng.run(); Thread.currentThread().setContextClassLoader(currentClassLoader); } public static final class SimpleClassLoader extends ClassLoader { private final ClassLoader currentClassLoader; private final URLClassLoader delegate; public SimpleClassLoader(ClassLoader currentClassLoader) { this.currentClassLoader = currentClassLoader; this.delegate = new URLClassLoader(new URL[]{currentClassLoader.getResource("")}, null); } @Override protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { final Class clazz; if (shouldBeLoadedWithDelegate(name)) { clazz = delegate.loadClass(name); } else { clazz = currentClassLoader.loadClass(name); } if (resolve) { resolveClass(clazz); } return clazz; } private boolean shouldBeLoadedWithDelegate(String name) { return "org.testng.SkipException".equals(name) || "test.testng1003.SkipExceptionTest".equals(name) || "test.testng1003.SomeClass".equals(name); } } } ================================================ FILE: tests/testng/src/test/java/samples/testng/bugs/github647/SkipExceptionTest.java ================================================ package samples.testng.bugs.github647; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.testng.PowerMockTestCase; import org.testng.annotations.Test; /** * */ @PrepareForTest(SomeClass.class) public class SkipExceptionTest extends PowerMockTestCase{ @Test public void testSkipException() throws Throwable { new SomeClass().throwSkipException(); } } ================================================ FILE: tests/testng/src/test/java/samples/testng/bugs/github647/SomeClass.java ================================================ package samples.testng.bugs.github647; import org.testng.SkipException; /** * */ public class SomeClass { public void throwSkipException() { throw new SkipException("Skip test"); } } ================================================ FILE: tests/testng/suite.xml ================================================ ================================================ FILE: tests/utils/src/main/java/org/powermock/api/mockito/ConfigurationTestUtils.java ================================================ /* * * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.api.mockito; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import static org.powermock.utils.IOUtils.copyFileUsingStream; public final class ConfigurationTestUtils { private static final String CONFIG_FILE = "configuration.properties"; private File config; public void copyTemplateToPropertiesFile() throws URISyntaxException, IOException { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); URL resource = classLoader.getResource("org/powermock/extensions/configuration.template"); File file = new File(resource.toURI()); File parentFile = file.getParentFile(); config = new File(parentFile.getAbsolutePath() + File.separator + CONFIG_FILE); if (!config.createNewFile()) { throw new AssertionError("Test data not created: cannot create " + CONFIG_FILE); } copyFileUsingStream(file, config); } public void clear(){ if (config != null && !config.delete()){ throw new RuntimeException("Cannot delete temporary configuration."); } } } ================================================ FILE: tests/utils/src/main/java/org/powermock/api/mockito/MockitoVersion.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.powermock.api.mockito; import java.security.CodeSource; import java.security.ProtectionDomain; public class MockitoVersion { public static boolean isMockito1(){ return MOCKITO_VERSION.isMockito1_0(); } public static boolean isMockito2(){ return MOCKITO_VERSION.isMockito2_0(); } public static boolean isMockito3(){ return MOCKITO_VERSION.isMockito3_0(); } public static boolean isMockito4(){ return MOCKITO_VERSION.isMockito4_0(); } private static final MockitoVersion MOCKITO_VERSION = new MockitoVersion(); private final String version; private MockitoVersion() { String ver = ""; try { Class mockitoClass = Class.forName("org.mockito.Mock"); ProtectionDomain protectionDomain = mockitoClass.getProtectionDomain(); CodeSource codeSource = protectionDomain.getCodeSource(); String path = codeSource.getLocation().toString(); int x = path.lastIndexOf("-"); int y = path.lastIndexOf("."); ver = path.substring(x + 1, y); } catch (Exception e) { ver = ""; } finally { version = ver; } } private boolean isMockito1_0() { return version.startsWith("1"); } private boolean isMockito2_0() { return version.startsWith("2"); } private boolean isMockito3_0() { return version.startsWith("3"); } private boolean isMockito4_0() { return version.startsWith("4"); } } ================================================ FILE: tests/utils/src/main/java/samples/Service.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples; /** * A very simple service interface used as a dependency for various classes to * demonstrate different kinds of mocking. * * @author Johan Haleby */ public interface Service { public String getServiceMessage(); } ================================================ FILE: tests/utils/src/main/java/samples/abstractmocking/AbstractMethodMocking.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.abstractmocking; /** * Demonstrates that PowerMock can mock abstract methods. This was previously a * bug in PowerMock. */ public abstract class AbstractMethodMocking { public String getValue() { return getIt(); } protected abstract String getIt(); } ================================================ FILE: tests/utils/src/main/java/samples/annotationbased/AnnotatedClassDemo.java ================================================ package samples.annotationbased; import samples.annotationbased.testannotations.RuntimeAnnotation; @RuntimeAnnotation public class AnnotatedClassDemo { public static boolean staticMethod() { return false; } } ================================================ FILE: tests/utils/src/main/java/samples/annotationbased/AnnotationDemo.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.annotationbased; import samples.Service; public class AnnotationDemo { private Service service; public AnnotationDemo(Service service) { this.service = service; } public AnnotationDemo() { } public String getServiceMessage() { return service.getServiceMessage(); } } ================================================ FILE: tests/utils/src/main/java/samples/annotationbased/testannotations/RuntimeAnnotation.java ================================================ package samples.annotationbased.testannotations; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.TYPE; @Retention(RetentionPolicy.RUNTIME) @Target(value = {TYPE}) public @interface RuntimeAnnotation { } ================================================ FILE: tests/utils/src/main/java/samples/anonymousmocking/MyAbstractClass.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.anonymousmocking; public abstract class MyAbstractClass { public abstract String getMessage(); } ================================================ FILE: tests/utils/src/main/java/samples/anonymousmocking/StupidAnonymous.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.anonymousmocking; import samples.Service; public class StupidAnonymous { // TODO We need to make sure that you also can mock private members from an // inner class! protected Service service; public void setService(Service service) { this.service = service; } public String getMessageFromMyClass() { MyAbstractClass myclass = new MyAbstractClass() { @Override public String getMessage() { return "Hello world!"; } }; return myclass.getMessage(); } public String getMessagesFromSeveralInnerClasses() { MyAbstractClass myclass1 = new MyAbstractClass() { @Override public String getMessage() { return "Hello world 1!"; } }; MyAbstractClass myclass2 = new MyAbstractClass() { @Override public String getMessage() { return "Hello world 2!"; } }; return myclass1.getMessage() + " " + myclass2.getMessage(); } public String getServiceMessageFromInnerClass() { MyAbstractClass myclass = new MyAbstractClass() { @Override public String getMessage() { return service.getServiceMessage(); } }; return myclass.getMessage(); } public String getMessageFromOtherMethodInInnerClass() { MyAbstractClass myclass = new MyAbstractClass() { @Override public String getMessage() { return returnThisMessage(); } public String returnThisMessage() { return "A message"; } }; return myclass.getMessage(); } } ================================================ FILE: tests/utils/src/main/java/samples/argumentmatcher/ArgumentMatcherDemo.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.argumentmatcher; import java.util.List; public class ArgumentMatcherDemo { public List findByNamedQuery(String argument, List someList) { someList.add("one"); return someList; } } ================================================ FILE: tests/utils/src/main/java/samples/classhierarchy/ChildA.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.classhierarchy; public class ChildA extends Parent { } ================================================ FILE: tests/utils/src/main/java/samples/classhierarchy/ChildB.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.classhierarchy; public class ChildB extends Parent { } ================================================ FILE: tests/utils/src/main/java/samples/classhierarchy/Parent.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.classhierarchy; public class Parent { private int value; public int getValue() { return value; } public void setValue(int value) { this.value = value; } } ================================================ FILE: tests/utils/src/main/java/samples/classwithinnermembers/ClassWithInnerMembers.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.classwithinnermembers; /** * Class that is used to test that local and member class works with PowerMock. */ public class ClassWithInnerMembers { private interface InnerInterface { String doStuff(); } public static class MyInnerClassWithPrivateConstructorWithDiffMultArgs { private String mArg1; private int mArg2; private String mArg3; private MyInnerClassWithPrivateConstructorWithDiffMultArgs(String arg1, int arg2, String arg3) { mArg1 = arg1; mArg2 = arg2; mArg3 = arg3; } } public MyInnerClassWithPrivateConstructorWithDiffMultArgs makeMyInnerClassWithPrivateConstructorWithDiffMultArgs( String arg1, int arg2, String arg3) { return new MyInnerClassWithPrivateConstructorWithDiffMultArgs(arg1, arg2, arg3); } public static class MyInnerClassWithPrivateConstructorWithMultArgs { private String mArg1; private String mArg2; private String mArg3; private MyInnerClassWithPrivateConstructorWithMultArgs(String arg1, String arg2, String arg3) { mArg1 = arg1; mArg2 = arg2; mArg3 = arg3; } } public MyInnerClassWithPrivateConstructorWithMultArgs makeMyInnerClassWithPrivateConstructorWithMultArgs( String arg1, String arg2, String arg3) { return new MyInnerClassWithPrivateConstructorWithMultArgs(arg1, arg2, arg3); } public static class MyInnerClassWithPublicConstructorWithMultArgs { private String mArg1; private String mArg2; private String mArg3; private MyInnerClassWithPublicConstructorWithMultArgs(String arg1, String arg2, String arg3) { mArg1 = arg1; mArg2 = arg2; mArg3 = arg3; } } public MyInnerClassWithPublicConstructorWithMultArgs makeMyInnerClassWithPublicConstructorWithMultArgs( String arg1, String arg2, String arg3) { return new MyInnerClassWithPublicConstructorWithMultArgs(arg1, arg2, arg3); } public static class MyInnerClassWithPackageConstructorWithMultArgs { private String mArg1; private String mArg2; private String mArg3; MyInnerClassWithPackageConstructorWithMultArgs(String arg1, String arg2, String arg3) { mArg1 = arg1; mArg2 = arg2; mArg3 = arg3; } } public MyInnerClassWithPackageConstructorWithMultArgs makeMyInnerClassWithPackageConstructorWithMultArgs( String arg1, String arg2, String arg3) { return new MyInnerClassWithPackageConstructorWithMultArgs(arg1, arg2, arg3); } public static class MyInnerClassWithProtectedConstructorWithMultArgs { private String mArg1; private String mArg2; private String mArg3; MyInnerClassWithProtectedConstructorWithMultArgs(String arg1, String arg2, String arg3) { mArg1 = arg1; mArg2 = arg2; mArg3 = arg3; } } public MyInnerClassWithProtectedConstructorWithMultArgs makeMyInnerClassWithProtectedConstructorWithMultArgs( String arg1, String arg2, String arg3) { return new MyInnerClassWithProtectedConstructorWithMultArgs(arg1, arg2, arg3); } private static class MyInnerClass implements InnerInterface { @Override public String doStuff() { return "member class"; } } private static class StaticInnerClassWithConstructorArgument implements InnerInterface { private final String value; public StaticInnerClassWithConstructorArgument(String value) { this.value = value; } @Override public String doStuff() { return value; } } private class MyInnerClassWithConstructorArgument implements InnerInterface { private final String value; public MyInnerClassWithConstructorArgument(String value) { this.value = value; } @Override public String doStuff() { return value; } } public String getValue() { return new MyInnerClass().doStuff(); } public String getValueForInnerClassWithConstructorArgument() { return new MyInnerClassWithConstructorArgument("value").doStuff(); } public String getValueForStaticInnerClassWithConstructorArgument() { return new StaticInnerClassWithConstructorArgument("value").doStuff(); } public String getLocalClassValue() { class MyLocalClass implements InnerInterface { @Override public String doStuff() { return "local class"; } } return new MyLocalClass().doStuff(); } public String getLocalClassValueWithArgument() { class MyLocalClass implements InnerInterface { private final String value; public MyLocalClass(String value) { this.value = value; } @Override public String doStuff() { return value; } } return new MyLocalClass("my value").doStuff(); } public String getValueForAnonymousInnerClass() { InnerInterface inner = new InnerInterface() { @Override public String doStuff() { return "value"; } }; return inner.doStuff(); } } ================================================ FILE: tests/utils/src/main/java/samples/constructor/PrivateConstructorDemo.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.constructor; import samples.Service; /** * Demonstrates the ability to invoke a test on a private constructor as well as * lazy initialization of private collaborators. * * @author Johan Haleby */ public class PrivateConstructorDemo { private Service privateService; private String constructorResult; private PrivateConstructorDemo(String completeName) { constructorResult = privateService.getServiceMessage() + completeName; } public String getConstructorResult() { return constructorResult; } } ================================================ FILE: tests/utils/src/main/java/samples/constructor/PrivateConstructorInstantiationDemo.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.constructor; /** * Class used to demonstrate the private constructor instantiation. * * @author Johan Haleby */ public class PrivateConstructorInstantiationDemo { private final int state; private PrivateConstructorInstantiationDemo() { this(42); } private PrivateConstructorInstantiationDemo(int state) { this.state = state; } public int getState() { return state; } } ================================================ FILE: tests/utils/src/main/java/samples/constructor/PublicConstructorDemo.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.constructor; import samples.Service; /** * Demonstrates the ability to invoke a test on a private constructor as well as * lazy initialization of private collaborators. * * @author Johan Haleby */ public class PublicConstructorDemo { private Service privateService; private String constructorResult; public PublicConstructorDemo(String completeName) { constructorResult = privateService.getServiceMessage() + completeName; } public String getConstructorResult() { return constructorResult; } } ================================================ FILE: tests/utils/src/main/java/samples/constructor/PublicConstructorWithDependencyDemo.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.constructor; import samples.Service; /** * This class is used to demonstrate that error messages are correct when a * constructor is not found. */ public class PublicConstructorWithDependencyDemo { private final Service service; public PublicConstructorWithDependencyDemo(Service service) { this.service = service; } public Service getService() { return service; } public void aMethod() { System.out.println("Does basically nothing"); } } ================================================ FILE: tests/utils/src/main/java/samples/constructorargs/ConstructorArgsDemo.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.constructorargs; public class ConstructorArgsDemo { private static final String DEFAULT = "default"; private final String secret; public ConstructorArgsDemo(String secret) { this.secret = secret; } public ConstructorArgsDemo() { secret = DEFAULT; } public String getTheSecret() { return theSecretIsPrivate(); } private String theSecretIsPrivate() { return secret; } } ================================================ FILE: tests/utils/src/main/java/samples/enummocking/AnotherSomeObjectInterfaceImpl.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package samples.enummocking; /** * */ public class AnotherSomeObjectInterfaceImpl implements SomeObjectInterface { } ================================================ FILE: tests/utils/src/main/java/samples/enummocking/EnumWithConstructor.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package samples.enummocking; /** * */ public enum EnumWithConstructor { SOME_ENUM_VALUE( ) { @Override public SomeObjectInterface create() { return new SomeObjectInterfaceImpl(); } }; public abstract SomeObjectInterface create(); } ================================================ FILE: tests/utils/src/main/java/samples/enummocking/MyEnum.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.enummocking; public enum MyEnum { MY_VALUE; public static String getString() { return MY_VALUE.toString(); } } ================================================ FILE: tests/utils/src/main/java/samples/enummocking/SomeObjectInterface.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package samples.enummocking; /** * */ public interface SomeObjectInterface { } ================================================ FILE: tests/utils/src/main/java/samples/enummocking/SomeObjectInterfaceImpl.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package samples.enummocking; /** * */ public class SomeObjectInterfaceImpl implements SomeObjectInterface { } ================================================ FILE: tests/utils/src/main/java/samples/equalswithgetclass/EqualsWithGetClass.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.equalswithgetclass; /** * Class that implements an equals method that contains a call to getClass(); */ public class EqualsWithGetClass { private final String myString; public EqualsWithGetClass(String myString) { super(); this.myString = myString; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((myString == null) ? 0 : myString.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; EqualsWithGetClass other = (EqualsWithGetClass) obj; if (myString == null) { if (other.myString != null) return false; } else if (!myString.equals(other.myString)) return false; return true; } } ================================================ FILE: tests/utils/src/main/java/samples/expectnew/CreationException.java ================================================ package samples.expectnew; /** * */ public class CreationException extends RuntimeException { } ================================================ FILE: tests/utils/src/main/java/samples/expectnew/ExpectNewDemo.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.expectnew; import samples.Service; import samples.newmocking.MyClass; import java.io.*; import java.util.Date; public class ExpectNewDemo { private int dummyField; @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + dummyField; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final ExpectNewDemo other = (ExpectNewDemo) obj; if (dummyField != other.dummyField) return false; return true; } public String getMessage() { MyClass myClass = new MyClass(); return myClass.getMessage(); } public String getMessageWithArgument() { MyClass myClass = new MyClass(); return myClass.getMessage("test"); } public void invokeVoidMethod() { MyClass myClass = new MyClass(); myClass.voidMethod(); } /** * The purpose of the method is to demonstrate that a test case can mock the * new instance call and throw an exception upon instantiation. */ public void throwExceptionWhenInvoction() { new MyClass(); } /** * The purpose of the method is to demonstrate that a test case can mock the * new instance call and throw an exception upon instantiation. */ public void throwExceptionAndWrapInRunTimeWhenInvoction() { try { new MyClass(); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } public String multipleNew() { MyClass myClass1 = new MyClass(); MyClass myClass2 = new MyClass(); final String message1 = myClass1.getMessage(); final String message2 = myClass2.getMessage(); return message1 + message2; } public void simpleMultipleNew() { new MyClass(); new MyClass(); new MyClass(); } @SuppressWarnings("unused") private void simpleMultipleNewPrivate() { new MyClass(); new MyClass(); new MyClass(); } public void simpleSingleNew() { new MyClass(); } public Date makeDate() { return new Date(); } public boolean fileExists(String name) { return new File(name).exists(); } public InputStream alternativePath() { try { return new DataInputStream(null); } catch (RuntimeException e) { return new ByteArrayInputStream(new byte[0]); } } public String newWithArguments(Service service, int times) { return new ExpectNewServiceUser(service, times).useService(); } public String newWithWrongArguments(Service service, int times) { return new ExpectNewServiceUser(service, times * 2).useService(); } public String[] newVarArgs(String... strings) { return new VarArgsConstructorDemo(strings).getAllMessages(); } public Service[] newVarArgs(Service... services) { return new VarArgsConstructorDemo(services).getAllServices(); } public int[] newVarArgs(float myFloat, int ... ints) { return new VarArgsConstructorDemo(myFloat, ints).getInts(); } public byte[][] newVarArgs(byte[]... bytes) { return new VarArgsConstructorDemo(bytes).getByteArrays(); } public byte[][] newVarArgsWithMatchers() { return new VarArgsConstructorDemo(new byte[] { 42 }, new byte[] { 17 }).getByteArrays(); } public void fileWriter(String name, String msg) throws IOException { new FileWriter(name).write(msg); } public void fileWriterPrint(String name, String msg) throws IOException { new PrintWriter(new FileWriter(name)).write(msg); } public byte[][] newSimpleVarArgs(byte[]... bytes) { return new SimpleVarArgsConstructorDemo(bytes).getByteArrays(); } public Target createTarget(ITarget target) { Target domainTarget; try { domainTarget = new Target(getTargetName(target), target.getId()); } catch (CreationException e) { domainTarget = new Target("Unknown", -1); } return domainTarget; } private String getTargetName(ITarget target) { return target.getName(); } } ================================================ FILE: tests/utils/src/main/java/samples/expectnew/ExpectNewOfFinalSystemClassDemo.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.expectnew; public class ExpectNewOfFinalSystemClassDemo { public char getFirstChar() { String myString = new String("My String"); return myString.charAt(0); } } ================================================ FILE: tests/utils/src/main/java/samples/expectnew/ExpectNewServiceUser.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.expectnew; import samples.Service; public class ExpectNewServiceUser { private final Service service; private final int times; ExpectNewServiceUser(Service service, int times) { this.service = service; this.times = times; } public String useService() { StringBuilder builder = new StringBuilder(); for (int i = 0; i < times; i++) { builder.append(service.getServiceMessage()); } return builder.toString(); } } ================================================ FILE: tests/utils/src/main/java/samples/expectnew/ExpectNewWithMultipleCtorDemo.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.expectnew; import samples.Service; public class ExpectNewWithMultipleCtorDemo { private final Service service; private final int times; public ExpectNewWithMultipleCtorDemo(Service service) { this(service, 1); } public ExpectNewWithMultipleCtorDemo(Service service, int times) { this.service = service; this.times = times; } public String useService() { StringBuilder builder = new StringBuilder(); for (int i = 0; i < times; i++) { builder.append(service.getServiceMessage()); } return builder.toString(); } } ================================================ FILE: tests/utils/src/main/java/samples/expectnew/ITarget.java ================================================ package samples.expectnew; /** * */ public interface ITarget { int getId(); String getName(); } ================================================ FILE: tests/utils/src/main/java/samples/expectnew/MultiConstructor.java ================================================ package samples.expectnew; /** * Mocking object construction with {@code withAnyArguments()} does not treat all * the object's constructors equally. This test fixture provides an object which * has multiple constructors so that tests can cover both code-paths of constructor * matching. */ public class MultiConstructor { private final String first; public MultiConstructor(String first, String second) { this.first = first; } public MultiConstructor(String first) { this.first = first; } public MultiConstructor(String first, Runnable something, boolean b) { this.first = first; } public String getFirst() { return this.first; } } ================================================ FILE: tests/utils/src/main/java/samples/expectnew/NewFileExample.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.expectnew; import java.io.File; /** * Used to demonstrate PowerMock's ability to mock new instance calls. */ public class NewFileExample { public boolean createDirectoryStructure(String directoryPath) { File directory = new File(directoryPath); if (directory.exists()) { throw new IllegalArgumentException("\"" + directoryPath + "\" already exists."); } return directory.mkdirs(); } } ================================================ FILE: tests/utils/src/main/java/samples/expectnew/PrimitiveAndWrapperDemo.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.expectnew; /** * Used to demonstrate PowerMocks ability to deal with overloaded constructors * of primitive/wrapper types. */ public class PrimitiveAndWrapperDemo { private final int myInt; public PrimitiveAndWrapperDemo(int myInt) { this.myInt = myInt; } public PrimitiveAndWrapperDemo(Integer myInt) { this.myInt = myInt; } public int getMyInt() { return myInt; } } ================================================ FILE: tests/utils/src/main/java/samples/expectnew/PrimitiveAndWrapperUser.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.expectnew; /** * Used to demonstrate PowerMocks ability to deal with overloaded constructors * of primitive/wrapper types. */ public class PrimitiveAndWrapperUser { public int useThem() { PrimitiveAndWrapperDemo demo1 = new PrimitiveAndWrapperDemo(Integer.valueOf(42)); PrimitiveAndWrapperDemo demo2 = new PrimitiveAndWrapperDemo(21); return demo1.getMyInt() + demo2.getMyInt(); } } ================================================ FILE: tests/utils/src/main/java/samples/expectnew/SimpleVarArgsConstructorDemo.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.expectnew; public class SimpleVarArgsConstructorDemo { private final byte[][] byteArrays; public SimpleVarArgsConstructorDemo(byte[]... byteArrays) { this.byteArrays = byteArrays; } public byte[][] getByteArrays() { return byteArrays; } } ================================================ FILE: tests/utils/src/main/java/samples/expectnew/Target.java ================================================ package samples.expectnew; /** * */ public class Target implements ITarget{ private final String targetName; private final int id; public Target(String targetName, int id) { this.targetName = targetName; this.id = id; } @Override public int getId() { return id; } @Override public String getName() { return targetName; } } ================================================ FILE: tests/utils/src/main/java/samples/expectnew/VarArgsConstructorDemo.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.expectnew; import samples.Service; public class VarArgsConstructorDemo { private final String[] strings; private final Service[] services; private final byte[][] byteArrays; private final int[] ints; public VarArgsConstructorDemo(String... strings) { this.strings = strings; this.services = new Service[0]; this.byteArrays = new byte[0][0]; this.ints = new int[0]; } public VarArgsConstructorDemo(byte[]... byteArrays) { this.byteArrays = byteArrays; this.services = new Service[0]; this.strings = new String[0]; this.ints = new int[0]; } public VarArgsConstructorDemo(Service... services) { this.services = services; this.strings = new String[0]; this.byteArrays = new byte[0][0]; this.ints = new int[0]; } public VarArgsConstructorDemo(float myFloat, int... ints) { this.ints = ints; this.services = new Service[0]; strings = new String[0]; byteArrays = new byte[0][0]; } public String[] getAllMessages() { return strings; } public Service[] getAllServices() { return services; } public byte[][] getByteArrays() { return byteArrays; } public int[] getInts() { return ints; } } ================================================ FILE: tests/utils/src/main/java/samples/expectvoid/ExpectVoidDemo.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.expectvoid; public class ExpectVoidDemo { public void invokeAPrivateVoidMethod(int something) { privateInvoke(something); } private void privateInvoke(int something) { System.out.println("Error in test privateInvoke in class " + ExpectVoidDemo.class.getSimpleName()); } } ================================================ FILE: tests/utils/src/main/java/samples/fieldmock/FieldInitializerDemo.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.fieldmock; import java.util.HashMap; import java.util.Map; public class FieldInitializerDemo { private Map map = new HashMap(); private static Map staticMap = new HashMap(); private static Map staticMap2; static { staticMap2 = new HashMap(); System.out.println("### Static println!"); } public String getFromMap(int index) { System.out.println("getFromMap class = " + map.getClass()); System.out.println("staticMap = " + staticMap); System.out.println("staticMap2 = " + staticMap2); return map.get(index); } } ================================================ FILE: tests/utils/src/main/java/samples/finalmocking/FinalDemo.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.finalmocking; import samples.simplemix.SimpleMix; import samples.simplereturn.SimpleReturnExample; public final class FinalDemo { public final String say(String string) { return "Hello " + string; } public final void finalVoidCaller() { finalVoidCallee(); } public final void finalVoidCallee() { System.err.println("void method"); } public final native String sayFinalNative(String string); public final SimpleReturnExample simpleReturnExample() { return new SimpleReturnExample(); } public final SimpleMix simpleMix() { return new SimpleMix(); } } ================================================ FILE: tests/utils/src/main/java/samples/finalmocking/HoldingFinalDemo.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.finalmocking; public final class HoldingFinalDemo { public FinalDemo getFinalDemo() { return null; } } ================================================ FILE: tests/utils/src/main/java/samples/finalmocking/StaticHoldingFinalDemo.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.finalmocking; public class StaticHoldingFinalDemo { public static FinalDemo getFinalDemo() { return null; } } ================================================ FILE: tests/utils/src/main/java/samples/hashcode/HashCodeInitializedInCtor.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.hashcode; import java.util.HashMap; public class HashCodeInitializedInCtor { private final HashMap hash; public HashCodeInitializedInCtor() { hash = new HashMap(); } public static HashCodeInitializedInCtor newFaults() { HashCodeInitializedInCtor fault = new HashCodeInitializedInCtor(); return fault; } @Override public final int hashCode() { return hash.hashCode(); } } ================================================ FILE: tests/utils/src/main/java/samples/injectmocks/DependencyHolder.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.injectmocks; import samples.finalmocking.FinalDemo; /** * Simple class used to demonstrate setter injection.. */ public class DependencyHolder { private FinalDemo finalDemo; public FinalDemo getFinalDemo() { return finalDemo; } public void setFinalDemo(FinalDemo finalDemo) { this.finalDemo = finalDemo; } } ================================================ FILE: tests/utils/src/main/java/samples/injectmocks/DependencyHolderQualifier.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package samples.injectmocks; import samples.finalmocking.FinalDemo; /** * Simple class used to demonstrate setter injection.. */ @SuppressWarnings({"WeakerAccess", "unused"}) public class DependencyHolderQualifier { private FinalDemo finalDemo; private FinalDemo finalDemoQualifier; public FinalDemo getFinalDemo() { return finalDemo; } public void setFinalDemo(FinalDemo finalDemo) { this.finalDemo = finalDemo; } public FinalDemo getFinalDemoQualifier() { return finalDemoQualifier; } public void setFinalDemoQualifier(FinalDemo finalDemoQualifier) { this.finalDemoQualifier = finalDemoQualifier; } } ================================================ FILE: tests/utils/src/main/java/samples/injectmocks/InjectDemo.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package samples.injectmocks; /** * */ @SuppressWarnings({"SameReturnValue", "unused"}) public class InjectDemo { @SuppressWarnings("unused") public String getMessage() { return say("hello"); } @SuppressWarnings("UnusedParameters") private String say(String hello) { return hello; } } ================================================ FILE: tests/utils/src/main/java/samples/injectmocks/InjectDependencyHolder.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package samples.injectmocks; /** * Simple class used to demonstrate setter injection.. */ @SuppressWarnings("unused") public class InjectDependencyHolder { private InjectDemo injectDemo; public InjectDemo getInjectDemo() { return injectDemo; } public void setInjectDemo(InjectDemo injectDemo) { this.injectDemo = injectDemo; } } ================================================ FILE: tests/utils/src/main/java/samples/injectmocks/InjectDependencyHolderQualifier.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package samples.injectmocks; /** * Simple class used to demonstrate setter injection.. */ @SuppressWarnings("unused") public class InjectDependencyHolderQualifier { private InjectDemo injectDemo; private InjectDemo injectDemoQualifier; public InjectDemo getInjectDemo() { return injectDemo; } public void setInjectDemo(InjectDemo injectDemo) { this.injectDemo = injectDemo; } public InjectDemo getInjectDemoQualifier() { return injectDemoQualifier; } public void setInjectDemoQualifier(InjectDemo injectDemoQualifier) { this.injectDemoQualifier = injectDemoQualifier; } } ================================================ FILE: tests/utils/src/main/java/samples/innerclassmocking/ClassWithNonPrivateInnerClass.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.innerclassmocking; /** * Demonstrates the ability to mock an inner class (if the inner class is not * private). * * @author Johan Haleby */ public class ClassWithNonPrivateInnerClass { public String getMessage() { return new InnerClass().getInnerMessage(); } public class InnerClass { public String getInnerMessage() { return "A message from an inner class!"; } } } ================================================ FILE: tests/utils/src/main/java/samples/innerclassmocking/ClassWithPrivateInnerClass.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.innerclassmocking; /** * Used for demonstration of the ability to mock methods from a private inner * class. Due to limitations in Javassist (which doesn't seem to load inner * classes correctly??) we cannot mock private methods in inner classes. It * doesn't seem to have any effect when modifing the method modifier and setting * the method to public when loading the class by the mock class loader (but * why? Could be because the outer class has already been loaded?!). * */ public class ClassWithPrivateInnerClass { public String getMessage() { return new InnerClass().getInnerMessage(); } private class InnerClass { public String getInnerMessage() { return "A message from an inner class!"; } } } ================================================ FILE: tests/utils/src/main/java/samples/interfacefieldchange/InterfaceWithStaticFinalField.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.interfacefieldchange; /** * The purpose of the simple class is to demonstrate PowerMocks (possibly * future) ability to change static final fields in an interface. This is * normally not possible (the simple byte-code manipulation approach of removing * the final modifier doesn't work for interfaces since all static fields * must be final in interfaces according to the specification). */ public interface InterfaceWithStaticFinalField { static final String MY_STRING = "My value"; } ================================================ FILE: tests/utils/src/main/java/samples/interfacemethodfinding/InterfaceMethodHierarchyUsage.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.interfacemethodfinding; import org.powermock.reflect.internal.WhiteboxImpl; import java.sql.Connection; import java.sql.PreparedStatement; /** * There was a bug in PowerMock 1.2 and its predecessors that made PowerMock * {@link WhiteboxImpl#getMethod(Class, Class...)} fail when invoking proxified * interface methods declared in extended interfaces. E.g. if interface A * extends B & C and a method was declared in B it wouldn't be found by * {@link WhiteboxImpl#getMethod(Class, Class...)} since it only used to * traverse the class hierarchy and not the structure of the extended * interfaces. This was fixed in version 1.3 and this class is used to * demonstrate the issue. *

* Thanks to Lokesh Vaddi for finding this bug and to provide an example. */ public class InterfaceMethodHierarchyUsage { public void usePreparedStatement() throws Exception { Connection conn = null; // PreparedStatement extends other interfaces, this is the point of // interest. PreparedStatement prepared = null; try { conn = WsUtil.getConnection(); prepared = conn.prepareStatement("select * from emp"); } catch (Exception e) { System.out.println(e); } finally { conn.close(); prepared.close(); } } } ================================================ FILE: tests/utils/src/main/java/samples/interfacemethodfinding/WsUtil.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.interfacemethodfinding; import java.sql.Connection; /** * Dummy class that is used to setup expectations for the * {@link InterfaceMethodHierarchyUsage}. */ public class WsUtil { public static Connection getConnection() throws Exception { Connection conn = null; return conn; } } ================================================ FILE: tests/utils/src/main/java/samples/java/ClassInsideJavaPackage.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.java; public final class ClassInsideJavaPackage { public final String mockMe() { return "string"; } } ================================================ FILE: tests/utils/src/main/java/samples/largemethod/MethodExceedingJvmLimit.java ================================================ /* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package samples.largemethod; /** * Example of class with method which after instrumentation is larger than JVM limit. */ public class MethodExceedingJvmLimit { /** * Method size after instrumentation is equal to 91265. */ public static String init() { String a = "A"; a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A"; a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A"; a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A"; a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A"; a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A"; a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A"; a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A"; a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A"; a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A"; a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A"; a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A"; a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A"; a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A"; a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A"; a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A"; a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A"; a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A";a+="A"; return a; } } ================================================ FILE: tests/utils/src/main/java/samples/methodhierarchy/MethodInvocationDemo.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.methodhierarchy; public class MethodInvocationDemo extends MethodInvocationDemoParent { @SuppressWarnings("unused") private String getString() { return getTheString(); } } ================================================ FILE: tests/utils/src/main/java/samples/methodhierarchy/MethodInvocationDemoGrandParent.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.methodhierarchy; public class MethodInvocationDemoGrandParent { protected String getTheString() { return "a string from MethodInvocationDemoGrandParent"; } @SuppressWarnings("unused") private String getString() { return "MethodInvocationDemoGrandParent"; } @SuppressWarnings("unused") private String getString(int index) { return "MethodInvocationDemoGrandParent: " + index; } } ================================================ FILE: tests/utils/src/main/java/samples/methodhierarchy/MethodInvocationDemoParent.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.methodhierarchy; public class MethodInvocationDemoParent extends MethodInvocationDemoGrandParent { @Override protected String getTheString() { return "MethodInvocationDemoParent wrapped " + super.getTheString(); } @SuppressWarnings("unused") private String getString() { return "MethodInvocationDemoParent"; } } ================================================ FILE: tests/utils/src/main/java/samples/mockpolicy/ResultCalculator.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.mockpolicy; public class ResultCalculator { private int operand; public ResultCalculator(int operand) { this.operand = operand; } public double calculate() { return Math.PI*operand; } } ================================================ FILE: tests/utils/src/main/java/samples/mockpolicy/SimpleClassWithADependency.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.mockpolicy; public class SimpleClassWithADependency { private ResultCalculator calculator; public double getResult() { return calculator.calculate(); } } ================================================ FILE: tests/utils/src/main/java/samples/mockpolicy/SomeClassWithAMethod.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.mockpolicy; public class SomeClassWithAMethod extends SomeClassWithAMethodParent { @Override public double getResult() { return super.getResult() * 2; } } ================================================ FILE: tests/utils/src/main/java/samples/mockpolicy/SomeClassWithAMethodParent.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.mockpolicy; public class SomeClassWithAMethodParent { public double getResult() { return new ResultCalculator(4).calculate(); } } ================================================ FILE: tests/utils/src/main/java/samples/mockpolicy/frameworkexample/NativeResult.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.mockpolicy.frameworkexample; public class NativeResult { private final String result; public NativeResult(String result) { this.result = result; } public String get() { return result; } } ================================================ FILE: tests/utils/src/main/java/samples/mockpolicy/frameworkexample/SimpleFramework.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.mockpolicy.frameworkexample; public class SimpleFramework { static { System.loadLibrary("framework.dll"); } public NativeResult doNativeStuff(String nativeStuffToDo) { return new NativeResult(nativeStuffToDo); } } ================================================ FILE: tests/utils/src/main/java/samples/mockpolicy/frameworkexample/SimpleFrameworkUser.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.mockpolicy.frameworkexample; public class SimpleFrameworkUser { public String performComplexOperation(String operation) { return new SimpleFramework().doNativeStuff(operation).get(); } } ================================================ FILE: tests/utils/src/main/java/samples/nativemocking/NativeMockingSample.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.nativemocking; /** * The purpose of this class is to invoke a native method in a collaborator. */ public class NativeMockingSample { private final NativeService nativeService; public NativeMockingSample(NativeService nativeService) { this.nativeService = nativeService; } public String invokeNativeMethod(String param) { return nativeService.invokeNative(param); } } ================================================ FILE: tests/utils/src/main/java/samples/nativemocking/NativeService.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.nativemocking; /** * The purpose of this class is to demonstrate that it's possible to mock native * methods using plain EasyMock class extensions. */ public class NativeService { public native String invokeNative(String nativeParameter); } ================================================ FILE: tests/utils/src/main/java/samples/newmocking/MyClass.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.newmocking; public class MyClass { public String getMessage() { return "Hello world"; } public String getMessage(String message) { return "Hello world: " + message; } public void voidMethod() { System.out.println("Void method!"); } } ================================================ FILE: tests/utils/src/main/java/samples/newmocking/NewDemo.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.newmocking; public final class NewDemo { public void methodUnderTest() { SomeDependency loadingPool = new SomeDependency(); loadingPool.complete(); } } ================================================ FILE: tests/utils/src/main/java/samples/newmocking/SomeDependency.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.newmocking; public class SomeDependency { private String thing="complete"; void complete() { System.out.println(thing.toString()); // PowerMockBugPartATest gives NPE here, PowerMockBugPartBTest works } } ================================================ FILE: tests/utils/src/main/java/samples/newmocking/StupidNew.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.newmocking; public class StupidNew { public String getMessage() { MyClass myClass = new MyClass(); return myClass.getMessage(); } public String getMessageWithArgument() { MyClass myClass = new MyClass(); return myClass.getMessage("test"); } public void invokeVoidMethod() { MyClass myClass = new MyClass(); myClass.voidMethod(); } } ================================================ FILE: tests/utils/src/main/java/samples/nice/NiceDemo.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.nice; public class NiceDemo { public void callAThenB() { A("String"); B("String 2"); } void A(String aString) { // Does nothing } void B(String aString) { // Does nothing } } ================================================ FILE: tests/utils/src/main/java/samples/overloading/OverloadedMethodsExample.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.overloading; import samples.classhierarchy.ChildA; import samples.classhierarchy.Parent; public class OverloadedMethodsExample { public static void overloadedMethodWithOneArgument(Parent parent) { } public static void overloadedMethodWithOneArgument(ChildA child) { } public static void overloadedMethodWithTwoArguments(Parent parent, ChildA child) { } public static void overloadedMethodWithTwoArguments(Parent parent1, Parent parent2) { } } ================================================ FILE: tests/utils/src/main/java/samples/overloading/OverloadingDemo.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.overloading; import samples.classhierarchy.ChildA; import samples.classhierarchy.Parent; /** * Demonstrates that PowerMock correctly invoke overloaded methods from the * MockGateway. */ public class OverloadingDemo { public void performSingleOverloadedArgumentTest() { Parent object = new ChildA(); OverloadedMethodsExample.overloadedMethodWithOneArgument(object); } public void performMethodOverloadTestWhenBothArgumentSame() { Parent object1 = new ChildA(); Parent object2 = new ChildA(); OverloadedMethodsExample.overloadedMethodWithTwoArguments(object1, object2); } public void performMethodOverloadTestWithOneArgumentSameAndOneDiffernt() { Parent object1 = new ChildA(); Parent object2 = new Parent(); OverloadedMethodsExample.overloadedMethodWithTwoArguments(object2, object1); } } ================================================ FILE: tests/utils/src/main/java/samples/overloading/StaticAndInstanceMethodWithSameName.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.overloading; import samples.classhierarchy.ChildA; import samples.classhierarchy.Parent; public class StaticAndInstanceMethodWithSameName { public void overloaded(Parent parent) { } public static void overloaded(ChildA child) { } } ================================================ FILE: tests/utils/src/main/java/samples/overloading/StaticAndInstanceMethodWithSameNameUser.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.overloading; import samples.classhierarchy.ChildA; import samples.classhierarchy.Parent; /** * Demonstrates that PowerMock correctly methods that seam to be overloaded but * differ because one is static and one is instance. */ public class StaticAndInstanceMethodWithSameNameUser { public void performInstaceInvocation(StaticAndInstanceMethodWithSameName object) { Parent child = new ChildA(); object.overloaded(child); } public void performStaticInvocation() { Parent child = new ChildA(); StaticAndInstanceMethodWithSameName.overloaded((ChildA) child); } } ================================================ FILE: tests/utils/src/main/java/samples/packageprivate/PackagePrivateClass.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.packageprivate; /** * This class demonstrates the ability for PowerMock to mock package private * classes. This is normally not an issue but since we've changed the CgLib * naming policy to allow for signed mocking PowerMock needs to byte-code * manipulate this class. */ class PackagePrivateClass { public int getValue() { return returnAValue(); } private int returnAValue() { return 82; } } ================================================ FILE: tests/utils/src/main/java/samples/partialmocking/MockSelfDemo.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.partialmocking; import java.sql.Connection; public class MockSelfDemo { private int hello; @SuppressWarnings("unused") private MockSelfDemo() { hello = 42; } public MockSelfDemo(int hello) { this.hello = hello; } public MockSelfDemo(Object string) { this.hello = 4; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + hello; return result; } protected String establishConnection(Connection conn) throws Exception { if (conn== null) { return "works"; } else { return "doesn't work"; } } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final MockSelfDemo other = (MockSelfDemo) obj; if (hello != other.hello) return false; return true; } public String aMethod() { aMethod2(); return getString("world"); } public void aMethod2() { } public String getTwoStrings() { return getString() + getString("world2"); } private String getString() { return "A String"; } public String getString(String string) { return "Hello " + string; } public String getString2(String string) { return "Hello " + string; } public String getString2() { return "Hello world"; } public int timesTwo(Integer anInt) { return anInt * 2; } public int timesTwo(int anInt) { return anInt * 2; } public int timesThree(int anInt) { return anInt * 3; } public int getConstructorValue() { return hello; } public static int getSomething() { int retVal = methodToBeStubbed(); retVal = retVal * 2; return retVal; } public static int methodToBeStubbed() { return 6; } } ================================================ FILE: tests/utils/src/main/java/samples/partialmocking/MockSelfDemoSubClass.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.partialmocking; public class MockSelfDemoSubClass { public String getAMessage() { return "A message"; } protected String getAProtectedMessage() { return "protected"; } } ================================================ FILE: tests/utils/src/main/java/samples/partialmocking/MockSelfDemoWithSubClass.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.partialmocking; public class MockSelfDemoWithSubClass extends MockSelfDemoSubClass { public String getMessage() { return getInternalMessage() + getAMessage(); } public String getSecondMessage() { return getAProtectedMessage(); } private String getInternalMessage() { return "Internal message"; } } ================================================ FILE: tests/utils/src/main/java/samples/partialmocking/MockSelfWithNoDefaultConstructorDemo.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.partialmocking; public class MockSelfWithNoDefaultConstructorDemo { private int hello; public MockSelfWithNoDefaultConstructorDemo(int hello) { this.hello = hello; } public String aMethod() { aMethod2(); return "hello = " + hello; } public void aMethod2() { } } ================================================ FILE: tests/utils/src/main/java/samples/partialmocking/MockWithStaticStateDemo.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.partialmocking; public class MockWithStaticStateDemo { private static final int state = 5; public static int getState() { return state; } } ================================================ FILE: tests/utils/src/main/java/samples/partialmocking/PartialMockingExample.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.partialmocking; /** * Simple partial mocking example that should need no byte-code manipulation. */ public class PartialMockingExample { public String methodToTest() { return methodToMock(); } public String methodToMock() { System.out.println("If you see this the test is failing!"); return "REAL VALUE"; } } ================================================ FILE: tests/utils/src/main/java/samples/partialmocking/PartialMockingWithConstructor.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.partialmocking; public class PartialMockingWithConstructor { public PartialMockingWithConstructor() { initialize(); } public void initialize() { } public void touch() { } } ================================================ FILE: tests/utils/src/main/java/samples/partialmocking/PrivatePartialMockingExample.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.partialmocking; /** * Simple partial mocking example that should need no byte-code manipulation. */ public final class PrivatePartialMockingExample { public String methodToTest() { return methodToMock("input"); } private String methodToMock(String input) { return "REAL VALUE = " + input; } } ================================================ FILE: tests/utils/src/main/java/samples/powermockignore/PowerMockIgnoreDemo.java ================================================ package samples.powermockignore; import javax.swing.*; public class PowerMockIgnoreDemo { public void showDialog() { JOptionPane.showInputDialog("Input:"); } } ================================================ FILE: tests/utils/src/main/java/samples/privateandfinal/PrivateFinal.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.privateandfinal; /** * A class used to test the functionality to mock private methods that are also * final. * * @author Johan Haleby */ public class PrivateFinal { public String say(String name) { return sayIt(name); } private final String sayIt(String name) { return "Hello " + name; } } ================================================ FILE: tests/utils/src/main/java/samples/privateandfinal/PrivateFinalOverload.java ================================================ /* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.privateandfinal; /** * A class used to test the functionality of capturing arguments when methods are overloaded and private and final. * * @author Johan Haleby */ public class PrivateFinalOverload { public String say(String name) { return say("Hello", name); } private final String say(String prefix, String name) { return prefix + " " + name; } } ================================================ FILE: tests/utils/src/main/java/samples/privatefield/MockSelfPrivateFieldServiceClass.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.privatefield; import samples.Service; /** * A class that uses a private Service field and no setter. This is approach is * common in DI frameworks like Guice and Wicket IoC. * * @author Johan Haleby */ public class MockSelfPrivateFieldServiceClass { private Service service; public String getCompositeMessage() { final String message = getOwnMessage() + service.getServiceMessage(); return message; } private String getOwnMessage() { return "My message"; } } ================================================ FILE: tests/utils/src/main/java/samples/privatefield/SimplePrivateFieldServiceClass.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.privatefield; import samples.Service; /** * A class that uses a private Service field and no setter. This is approach is * common in DI frameworks like Guice and Wicket IoC. * * @author Johan Haleby */ public class SimplePrivateFieldServiceClass { private Service service; public String useService() { return service.getServiceMessage(); } } ================================================ FILE: tests/utils/src/main/java/samples/privatemocking/PrivateMethodDemo.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.privatemocking; import java.io.File; import java.io.FileNotFoundException; import java.io.Reader; /** * A class used to test the functionality to mock private methods. * * @author Johan Haleby */ public class PrivateMethodDemo { public String say(String name) { return sayIt(name); } public String enhancedSay(String firstName, String lastName) { return sayIt(firstName, " ", lastName); } public String sayYear(String name, int years) { return doSayYear(years, name); } private String doSayYear(int years, String name) { return "Hello " + name + ", you are " + years + " old."; } private String sayIt(String firstName, String spacing, String lastName) { return "Hello" + firstName + spacing + lastName; } private String sayIt(String name) { return "Hello " + name; } @SuppressWarnings("unused") private String sayIt() { return "Hello world"; } public int methodCallingPrimitiveTestMethod() { return aTestMethod(10); } public int methodCallingWrappedTestMethod() { return aTestMethod(new Integer(15)); } private int aTestMethod(int aValue) { return aValue; } private Integer aTestMethod(Integer aValue) { return aValue; } public void doArrayStuff(String v) { doArrayInternal(new String[]{v}); } private void doArrayInternal(String[] strings) { } public void doObjectStuff(Object o) { doObjectInternal(o); } private void doObjectInternal(Object o) { } public int invokeVarArgsMethod(int a, int b) { return varArgsMethod(a, b); } private int varArgsMethod(int... ints) { int sum = 0; for (int i : ints) { sum += i; } return sum; } private Reader createReader(File folder) throws FileNotFoundException { return null; } } ================================================ FILE: tests/utils/src/main/java/samples/reflection/ReflectionInstantiator.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.reflection; public class ReflectionInstantiator { public boolean instantiateUseMe() throws ClassNotFoundException { Class reflectionClass = Class.forName( "samples.reflection.UseMeInterface", true, Thread .currentThread().getContextClassLoader()); return reflectionClass.isAssignableFrom(UseMe.class); } } ================================================ FILE: tests/utils/src/main/java/samples/reflection/UseMe.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.reflection; public class UseMe implements UseMeInterface { } ================================================ FILE: tests/utils/src/main/java/samples/reflection/UseMeInterface.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.reflection; public interface UseMeInterface { } ================================================ FILE: tests/utils/src/main/java/samples/rule/SimpleThing.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.rule; public interface SimpleThing { String getThingName(); } ================================================ FILE: tests/utils/src/main/java/samples/rule/SimpleThingCreator.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.rule; public class SimpleThingCreator { public static SimpleThing createSimpleThing() { return new SimpleThingImpl(); } } ================================================ FILE: tests/utils/src/main/java/samples/rule/SimpleThingImpl.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.rule; public class SimpleThingImpl implements SimpleThing { @Override public String getThingName() { return null; } } ================================================ FILE: tests/utils/src/main/java/samples/rule/ThingToTest.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.rule; public class ThingToTest { private final SimpleThing simpleThing; public ThingToTest() { simpleThing = SimpleThingCreator.createSimpleThing(); } public String getName() { // uncomment the line below and the test passes // return simpleThing.getThingName(); return "Smith"; } } ================================================ FILE: tests/utils/src/main/java/samples/servletmocking/SampleServlet.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.servletmocking; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * @author volodymyr.tsukur */ public class SampleServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().write("out"); } } ================================================ FILE: tests/utils/src/main/java/samples/simplemix/SimpleMix.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.simplemix; /** * This class is used to demonstrate features such as static, final and partial * mocking as well as access internal state. */ public class SimpleMix { private SimpleMixCollaborator collaborator; public final int calculate() { return (SimpleMixUtilities.getRandomInteger() + getValue() - collaborator.getRandomInteger()) * new SimpleMixConstruction().getMyValue(); } private int getValue() { return (int) (System.currentTimeMillis() / 1000); } } ================================================ FILE: tests/utils/src/main/java/samples/simplemix/SimpleMixCollaborator.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.simplemix; import java.util.Random; public final class SimpleMixCollaborator { public final int getRandomInteger() { return new Random().nextInt(400); } } ================================================ FILE: tests/utils/src/main/java/samples/simplemix/SimpleMixConstruction.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.simplemix; public class SimpleMixConstruction { public int getMyValue() { return 4; } } ================================================ FILE: tests/utils/src/main/java/samples/simplemix/SimpleMixUtilities.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.simplemix; import java.util.Random; public class SimpleMixUtilities { public static int getRandomInteger() { return new Random().nextInt(); } } ================================================ FILE: tests/utils/src/main/java/samples/simplereturn/SimpleReturnExample.java ================================================ package samples.simplereturn; public class SimpleReturnExample { public int mySimpleMethod() { return 44; } } ================================================ FILE: tests/utils/src/main/java/samples/simplereturn/SimpleReturnExampleUser.java ================================================ package samples.simplereturn; public class SimpleReturnExampleUser { private SimpleReturnExample simpleReturnExample; public SimpleReturnExampleUser(SimpleReturnExample intReturn2) { super(); this.simpleReturnExample = intReturn2; } public int myMethod() { return simpleReturnExample.mySimpleMethod(); } } ================================================ FILE: tests/utils/src/main/java/samples/singleton/SimpleStaticService.java ================================================ package samples.singleton; public class SimpleStaticService { public static String say(final String string) { return "Hello " + string; } } ================================================ FILE: tests/utils/src/main/java/samples/singleton/StaticExample.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.singleton; /** *Can be used to assert that partial mocking of static methods works. */ public class StaticExample { public static void voidMethod() { privateVoidMethod(); } private static void privateVoidMethod() { } public static void voidFinalMethod() { privateVoidFinalMethod(); } private static final void privateVoidFinalMethod() { } public static void staticVoidMethod() { throw new IllegalArgumentException("This should never happen"); } public static String staticMethodReturningString() { throw new IllegalArgumentException("This should never happen"); } public static final void staticFinalVoidMethod() { throw new IllegalArgumentException("This should never happen"); } public static Object objectMethod() { return privateObjectMethod(); } private static Object privateObjectMethod() { return new Object(); } public static Object objectFinalMethod() { return privateObjectFinalMethod(); } private static final Object privateObjectFinalMethod() { return new Object(); } } ================================================ FILE: tests/utils/src/main/java/samples/singleton/StaticHelper.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.singleton; public class StaticHelper { public static void sayHelloHelper() { System.out.println("hello"); } public static void sayHelloAgain() { System.out.println("hello"); } } ================================================ FILE: tests/utils/src/main/java/samples/singleton/StaticService.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.singleton; import java.util.concurrent.Callable; /** * Test class to demonstrate static, static+final, static+native and * static+final+native methods mocking. * * @author Johan Haleby * @author Jan Kronquist */ public class StaticService { private static int number = 17; private static Integer intValue; public static String messageStorage; private int secret = 23; public static void sayHello(String message) { messageStorage = message; } public static void sayHello(Integer intValue) { StaticService.intValue = intValue; } public static int getNumberFromInner() { return new Callable() { @Override public Integer call() { return number; } }.call(); } public static int getNumberFromInnerInstance() { return new StaticService().internalGetNumberFromInnerInstance(); } public int internalGetNumberFromInnerInstance() { return new Callable() { @Override public Integer call() { return secret; } }.call(); } public static String doStatic(int i) { throw new UnsupportedOperationException("method not implemented yet..."); } public static void assertThatVerifyWorksForMultipleMocks() { StaticService.sayHello(); StaticHelper.sayHelloHelper(); } public static void sayHello() { StaticHelper.sayHelloHelper(); StaticHelper.sayHelloHelper(); } public static void sayHelloAgain() { StaticHelper.sayHelloAgain(); StaticHelper.sayHelloAgain(); } public static void throwException(){ throw new RuntimeException("How are you?"); } public static String say(String string) { return "Hello " + string; } public final static String sayFinal(String string) { return "Hello " + string; } public native static String sayNative(String string); public final native static String sayFinalNative(String string); public static int calculate(int a, int b) { return a + b; } private static String sayPrivateStatic(String string) { return "Hello private static " + string; } private static String sayPrivateFinalStatic(String string) { return "Hello private static " + string; } private static final native String sayPrivateNativeFinalStatic(String string); } ================================================ FILE: tests/utils/src/main/java/samples/singleton/StaticWithPrivateCtor.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.singleton; public class StaticWithPrivateCtor { private StaticWithPrivateCtor(){ } public static String staticMethod() { return "something"; } } ================================================ FILE: tests/utils/src/main/java/samples/spy/SpyObject.java ================================================ /* * Copyright 2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.spy; public class SpyObject { public String getMyString() { return "something"; } public String getStringTwo() { return "two"; } public void throwException() { throw new RuntimeException("Aaaaa! Test is failed."); } } ================================================ FILE: tests/utils/src/main/java/samples/staticandinstance/StaticAndInstanceDemo.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.staticandinstance; /** * Demonstrates how to mock both instance and static methods in the same test * * @author Johan Haleby */ public class StaticAndInstanceDemo { public String getMessage() { return getPrivateMessage() + StaticAndInstanceDemo.getStaticMessage(); } private String getPrivateMessage() { return "Private "; } public static final String getStaticMessage() { return "hello world!"; } public static void aVoidMethod() { } public static Object aMethod2(String aString) { return null; } } ================================================ FILE: tests/utils/src/main/java/samples/staticandinstance/StaticAndInstanceWithConstructorCodeDemo.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.staticandinstance; /** * The purpose of this class is to be used to verify that the * http://code.google.com/p/powermock/issues/detail?id=4 is fixed. * */ public class StaticAndInstanceWithConstructorCodeDemo { private final StaticAndInstanceDemo staticAndInstanceDemo; public StaticAndInstanceWithConstructorCodeDemo( StaticAndInstanceDemo staticAndInstanceDemo) { this.staticAndInstanceDemo = staticAndInstanceDemo; } public String getMessage() { return StaticAndInstanceDemo.getStaticMessage() + staticAndInstanceDemo.getMessage(); } } ================================================ FILE: tests/utils/src/main/java/samples/staticinitializer/AbstractStaticInitializerExample.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.staticinitializer; public abstract class AbstractStaticInitializerExample { static { if (true) { throw new RuntimeException("This code must be suppressed!"); } } public static String getStaticString() { return "something"; } public String getString() { return "something"; } } ================================================ FILE: tests/utils/src/main/java/samples/staticinitializer/EvilStaticInitializerExample.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.staticinitializer; /** * Simple example of a class with a static initializer. */ public class EvilStaticInitializerExample { public static final String FAILED_TO_LOAD_LIBRARY_MESSAGE = "Failed to load a required dll, please make sure that you've installed the software correctly"; static { try { System.loadLibrary("path/to/mylibrary.dll"); } catch (UnsatisfiedLinkError error) { throw new UnsatisfiedLinkError(FAILED_TO_LOAD_LIBRARY_MESSAGE); } } /* * We imagine that this method require the library to execute, but we want * to test it anyway in separation. */ public String doSomeNativeStuffUsingTheLoadedSystemLibrary() { return "native stuff"; } } ================================================ FILE: tests/utils/src/main/java/samples/staticinitializer/InterfaceComputation.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.staticinitializer; interface InterfaceA { public static final int A = 2 * InterfaceB.B; // public void methodA(); } // End of interface interface InterfaceB { public static final int B = InterfaceC.C + 1; // public String methodB(int qwe); } // End of interface interface InterfaceC extends InterfaceA { public static final int C = A + 1; } // End of interface public class InterfaceComputation implements InterfaceA, InterfaceB, InterfaceC { public static void main(String[] args) { System.out.println(calculateWithinHierarchy()); } public static int calculateWithinHierarchy() { return C + B + A; } public static int calculateWithReference() { return InterfaceC.C + InterfaceB.B + InterfaceA.A; } // public void methodA() { // } // // public String methodB(int qwe) { // return ""; // } } // End of class ================================================ FILE: tests/utils/src/main/java/samples/staticinitializer/SimpleStaticInitializerExample.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.staticinitializer; public class SimpleStaticInitializerExample { private static final String string; static { string = "static world!"; } public String getString() { return string; } public final String getConcatenatedString(String concat) { return concat + " " + string; } } ================================================ FILE: tests/utils/src/main/java/samples/staticinitializer/StaticInitializerExample.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.staticinitializer; import java.util.HashSet; import java.util.Set; public class StaticInitializerExample { private static final Set mySet; static { mySet = new HashSet(); if (true) { throw new RuntimeException("This code must be suppressed!"); } } public static Set getMySet() { return mySet; } } ================================================ FILE: tests/utils/src/main/java/samples/stress/ClassWithStatic.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.stress; public class ClassWithStatic { public static String a(){ return "str"; } public static String b(){ return "str"; } public static String c(){ return "str"; } public static String d(){ return "str"; } public static String e(){ return "str"; } public static String f(){ return "str"; } public static String g(){ return "str"; } public static String h(){ return "str"; } } ================================================ FILE: tests/utils/src/main/java/samples/stress/StressSample.java ================================================ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.stress; public class StressSample { public String a1(){ return ClassWithStatic.a(); } public String b1(){ return ClassWithStatic.b(); } public String c1(){ return ClassWithStatic.c(); } public String d1(){ return ClassWithStatic.d(); } public String e1(){ return ClassWithStatic.e(); } public String f1(){ return ClassWithStatic.f(); } public String g1(){ return ClassWithStatic.g(); } public String h1(){ return ClassWithStatic.h(); } } ================================================ FILE: tests/utils/src/main/java/samples/strict/StrictDemo.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.strict; public class StrictDemo { public void callAThenB() { A(); B(); } private void A() { // Does nothing } private void B() { // Does nothing } } ================================================ FILE: tests/utils/src/main/java/samples/suppressconstructor/AppaleList.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.suppressconstructor; import java.util.ArrayList; import java.util.List; public class AppaleList { public AppaleList() { throw new IllegalArgumentException("Shouldn't be called"); } public AppaleList(String str) { throw new IllegalArgumentException("Shouldn't be called"); } public String getAll() { List list = new ArrayList(); list.add("sb1"); List list1 = new ArrayList(10); list1.add("sb2"); list1.add("sb3"); list1.add("sb4"); return "str"; } } ================================================ FILE: tests/utils/src/main/java/samples/suppressconstructor/InvokeConstructor.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.suppressconstructor; public class InvokeConstructor { public String doStuff(String m) { return new SuppressConstructorHierarchy(m).getMessage(); } } ================================================ FILE: tests/utils/src/main/java/samples/suppressconstructor/SuppressConstructorDemo.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.suppressconstructor; public class SuppressConstructorDemo extends SuppressConstructorSubclassDemo { public SuppressConstructorDemo(String message) { super(message); } public String getMyOwnMessage() { return returnAMessage(); } private String returnAMessage() { return "my message"; } } ================================================ FILE: tests/utils/src/main/java/samples/suppressconstructor/SuppressConstructorHeirarchyEvilGrandParent.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.suppressconstructor; public class SuppressConstructorHeirarchyEvilGrandParent { SuppressConstructorHeirarchyEvilGrandParent() { throw new RuntimeException("This should be suppressed!!"); } } ================================================ FILE: tests/utils/src/main/java/samples/suppressconstructor/SuppressConstructorHierarchy.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.suppressconstructor; public class SuppressConstructorHierarchy extends SuppressConstructorHierarchyParent { public SuppressConstructorHierarchy(String message) { super(message); } /** * This method is just here to check if it works to execute several tests * with the same test suite class loader. * * @return 42. */ public int getNumber() { return 42; } } ================================================ FILE: tests/utils/src/main/java/samples/suppressconstructor/SuppressConstructorHierarchyParent.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.suppressconstructor; public class SuppressConstructorHierarchyParent extends SuppressConstructorHeirarchyEvilGrandParent { private String message; SuppressConstructorHierarchyParent() { System.out.println("Parent constructor"); this.message = "Default message"; } SuppressConstructorHierarchyParent(String message) { System.out.println("Parent constructor with message"); this.message = message; } public String getMessage() { return message; } } ================================================ FILE: tests/utils/src/main/java/samples/suppressconstructor/SuppressConstructorSubclassDemo.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.suppressconstructor; public class SuppressConstructorSubclassDemo { private String message; SuppressConstructorSubclassDemo(String message) { this.message = message; } public String getMessage() { return message; } } ================================================ FILE: tests/utils/src/main/java/samples/suppressconstructor/SuppressNonParentConstructorDemo.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.suppressconstructor; public class SuppressNonParentConstructorDemo { public SuppressNonParentConstructorDemo(String message) { throw new IllegalStateException(message); } public String getHello() { return "Hello"; } } ================================================ FILE: tests/utils/src/main/java/samples/suppressconstructor/SuppressSpecificConstructorDemo.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.suppressconstructor; public class SuppressSpecificConstructorDemo { public SuppressSpecificConstructorDemo() { throw new IllegalStateException( "This constructor should not be suppress"); } public SuppressSpecificConstructorDemo(String message) { throw new IllegalStateException(message); } public String getHello() { return "Hello"; } } ================================================ FILE: tests/utils/src/main/java/samples/suppresseverything/SuppressEverything.java ================================================ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.suppresseverything; public class SuppressEverything { public SuppressEverything() { throw new IllegalStateException("error"); } public SuppressEverything(String string) { throw new IllegalStateException("error"); } public int something() { throw new IllegalStateException("error"); } public void somethingElse() { throw new IllegalStateException("error"); } } ================================================ FILE: tests/utils/src/main/java/samples/suppressfield/DomainObject.java ================================================ package samples.suppressfield; public class DomainObject { public DomainObject() { } } ================================================ FILE: tests/utils/src/main/java/samples/suppressfield/ItemRepository.java ================================================ package samples.suppressfield; import java.util.HashMap; public class ItemRepository { private static HashMap itemMap = new HashMap(); @SuppressWarnings("unused") private MyClass myClass = new MyClass(); private int totalItems = 0; public void addItem(String key, String value) { itemMap.put(key, value); totalItems++; } public void delItem(String key) { if (itemMap.containsKey(key)) { itemMap.remove(key); totalItems--; } } private static class MyClass { public MyClass() { throw new IllegalArgumentException("Constructor should never be called during this test"); } } } ================================================ FILE: tests/utils/src/main/java/samples/suppressfield/SuppressField.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.suppressfield; public class SuppressField { private static final int MY_VALUE = 8; private static final Object MY_OBJECT = new Object(); private final boolean myBoolean = true; private final Boolean myWrappedBoolean = Boolean.TRUE; private final Object mySecondValue = new Object(); private DomainObject domainObject = new DomainObject(); public Object getMySecondValue() { return mySecondValue; } public DomainObject getDomainObject() { return domainObject; } private char myChar = 'a'; public static int getMyValue() { return MY_VALUE; } public static Object getMyObject() { return MY_OBJECT; } public boolean isMyBoolean() { return myBoolean; } public Boolean getMyWrappedBoolean() { return myWrappedBoolean; } public char getMyChar() { return myChar; } } ================================================ FILE: tests/utils/src/main/java/samples/suppressmethod/SuppressMethod.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.suppressmethod; public class SuppressMethod extends SuppressMethodParent { public static final Object OBJECT = new Object(); public Object getObjectWithArgument(String argument) { return OBJECT; } public Object getObject() { return OBJECT; } public static Object getObjectStatic() { return OBJECT; } public byte getByte() { return Byte.MAX_VALUE; } public short getShort() { return Short.MAX_VALUE; } public int getInt() { return Integer.MAX_VALUE; } public long getLong() { return Long.MAX_VALUE; } public boolean getBoolean() { return true; } public float getFloat() { return Float.MAX_VALUE; } public double getDouble() { return Double.MAX_VALUE; } public double getDouble(double value) { return value; } public void invokeVoid(StringBuilder s) { s.append("This should be suppressed!"); } @Override public int myMethod() { return 20 + super.myMethod(); } public Object sameName(int i) { return OBJECT; } public Object sameName(float f) { return OBJECT; } } ================================================ FILE: tests/utils/src/main/java/samples/suppressmethod/SuppressMethodExample.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.suppressmethod; public class SuppressMethodExample extends SuppressMethodParent { public static final Object OBJECT = new Object(); public Object getObject() { return OBJECT; } public Object getStringObject() { return "test"; } public static Object getStringObjectStatic() { return "test"; } } ================================================ FILE: tests/utils/src/main/java/samples/suppressmethod/SuppressMethodParent.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.suppressmethod; public abstract class SuppressMethodParent { public int myMethod() { return 42; } } ================================================ FILE: tests/utils/src/main/java/samples/swing/ReallySimpleSwingDemo.java ================================================ package samples.swing; import javax.swing.*; public class ReallySimpleSwingDemo { public void displayMessage(String message) { JOptionPane.showMessageDialog(null, message); } } ================================================ FILE: tests/utils/src/main/java/samples/swing/SimpleSwingDemo.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.swing; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; /** * A basic swing application example. * * @author Johan Haleby */ public class SimpleSwingDemo extends JFrame { private static final long serialVersionUID = -190175253588111657L; public SimpleSwingDemo() { initialize(); } private void initialize() { setLayout(new FlowLayout()); final JLabel jlbHelloWorld = new JLabel("Hello World!"); JButton jButton = new JButton("Click Me!"); jButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent actionevent) { jlbHelloWorld.setText("Clicked on button"); } }); add(jlbHelloWorld); add(jButton); setSize(100, 100); setVisible(true); } public static void main(String[] args) { new SimpleSwingDemo(); } } ================================================ FILE: tests/utils/src/main/java/samples/system/SystemClassUser.java ================================================ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.system; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.*; import java.util.Collections; import java.util.List; import java.util.UUID; /** * Class used to demonstrate PowerMock's ability to mock system classes. */ public class SystemClassUser { public void threadSleep() throws InterruptedException { Thread.sleep(5000); } public String performEncode() throws UnsupportedEncodingException { return URLEncoder.encode("string", "enc"); } public Process executeCommand() throws IOException { return Runtime.getRuntime().exec("command"); } public String getSystemProperty() throws IOException { return System.getProperty("property"); } public void doMoreComplicatedStuff() throws IOException { System.setProperty("nanoTime", Long.toString(System.nanoTime())); } public void copyProperty(String to, String from) throws IOException { System.setProperty(to, System.getProperty(from)); } public String format(String one, String args) throws IOException { return String.format(one, args); } public URL newURL(String anUrl) throws MalformedURLException { return new URL(anUrl); } public StringBuilder newStringBuilder() { return new StringBuilder(); } public void shuffleCollection(List list) { Collections.shuffle(list); } public URLConnection useURL(URL url) throws IOException { return url.openConnection(); } public InetAddress getLocalHost() throws IOException { return InetAddress.getLocalHost(); } public String generatePerishableToken() { final UUID uuid = UUID.randomUUID(); final String toString = uuid.toString(); final String result = toString.replaceAll("-", ""); return result; } public int lengthOf(StringBuilder to){ // The trick here is the casting to CharSequence, // this is to test that the runtime type(StringBuilder) is checked for mocked calls and not // the compile-time type (CharSequence) return lengthOf((CharSequence) to); } private int lengthOf(CharSequence to){ return to.length(); } } ================================================ FILE: tests/utils/src/main/java/samples/whitebox/ClassWithPowerMockGeneratedConstructor.java ================================================ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package samples.whitebox; import org.powermock.core.IndicateReloadClass; /** * Class that simulates a PowerMock generated constructor. */ public class ClassWithPowerMockGeneratedConstructor { public ClassWithPowerMockGeneratedConstructor(String string) { } /** * Simulates a PowerMock generated constructor. */ public ClassWithPowerMockGeneratedConstructor(IndicateReloadClass indicateReloadClass) { } } ================================================ FILE: version.properties ================================================ #Currently building version version=2.0.10 #Prevoius version used to generate release notes delta previousVersion=2.0.9