From c9cd906881e9800768dd6eda9cd484ee9c985b4f Mon Sep 17 00:00:00 2001 From: Valery Yatsynovich Date: Sat, 29 Jan 2022 00:40:28 +0300 Subject: [PATCH] Change minimal required JDK from 1.6 to 1.8 --- build.gradle | 3 +- config/checkstyle/checkstyle.xml | 16 +- gradle/java-module.gradle | 14 +- gradle/modules.gradle | 10 - .../api/easymock/EasyMockConfiguration.java | 4 +- .../org/powermock/api/easymock/PowerMock.java | 45 ++- .../impl/AbstractMockStrategyBase.java | 2 +- .../easymock/mockpolicies/JclMockPolicy.java | 3 +- .../extension/listener/AnnotationEnabler.java | 5 +- .../listener/AnnotationGlobalMetadata.java | 6 +- .../AnnotationMockCreatorFactory.java | 30 +- .../listener/AnnotationMockMetadata.java | 5 +- .../listener/AnnotationMockScanner.java | 2 +- .../listener/DefaultInjectFieldSearcher.java | 4 +- .../listener/TestSubjectInjector.java | 6 +- .../extension/listener/AnnotationEnabler.java | 8 +- .../powermock/api/mockito/PowerMockito.java | 12 +- .../ConstructorAwareExpectationSetup.java | 2 +- .../DefaultConstructorExpectationSetup.java | 4 +- .../mockito/internal/PowerMockitoCore.java | 44 +-- .../PowerMockitoSpyAnnotationEngine.java | 2 +- .../exceptions/StackTraceCleanerProvider.java | 15 +- .../InvocationControlAssertionError.java | 2 +- .../mockcreation/DefaultMockCreator.java | 10 +- .../internal/mockcreation/MockCreator.java | 4 +- .../MockTypeValidatorFactory.java | 6 +- .../stubbing/MockitoRealMethodInvocation.java | 4 +- .../mockito/invocation/InvocationFactory.java | 25 +- .../invocation/MockHandlerAdaptor.java | 2 +- .../MockitoMethodInvocationControl.java | 4 +- .../mockito/mockpolicies/Slf4jMockPolicy.java | 2 +- .../mockcreation/MockCreatorTestCase.java | 2 +- .../mockmaker/PowerMockMakerTestCase.java | 7 +- .../membermodification/MemberMatcher.java | 14 +- .../membermodification/MemberModifier.java | 2 +- .../impl/MethodReplaceStrategyImpl.java | 4 +- .../strategy/impl/MethodStubStrategyImpl.java | 58 ++-- .../powermock/classloading/DeepCloner.java | 7 +- .../ObjenesisClassloaderExecutorTest.java | 59 ++-- .../classloading/ObjenesisDeepClonerTest.java | 36 +-- .../classloading/classes/MyArgument.java | 67 +++-- .../powermock/classloading/DeepCloner.java | 54 ++-- .../XStreamClassloaderExecutorTest.java | 25 +- .../classloading/XStreamDeepClonerTest.java | 22 +- .../classloading/classes/MyArgument.java | 67 +++-- .../configuration/ConfigurationType.java | 2 +- .../configuration/GlobalConfiguration.java | 4 +- .../support/ConfigurationBuilder.java | 6 +- .../support/ConfigurationMapper.java | 2 +- .../support/PropertiesFinder.java | 2 +- .../powermock/core/ClassReplicaCreator.java | 12 +- .../core/ConcreteClassGenerator.java | 7 +- .../org/powermock/core/IdentityHashSet.java | 2 +- .../main/java/org/powermock/core/ListMap.java | 12 +- .../java/org/powermock/core/MockGateway.java | 6 +- .../org/powermock/core/MockRepository.java | 26 +- .../org/powermock/core/PowerMockUtils.java | 2 +- .../org/powermock/core/bytebuddy/Frame.java | 19 +- .../core/bytebuddy/MethodMaxLocals.java | 6 +- .../core/bytebuddy/MockGetawayCall.java | 18 +- .../DeferSupportingClassLoader.java | 9 +- .../classloader/MockClassLoaderBuilder.java | 2 +- .../MockClassLoaderConfiguration.java | 2 +- .../classloader/MockClassLoaderFactory.java | 13 +- .../javassist/ClassPathAdjuster.java | 3 +- .../javassist/ClassPoolFactory.java | 3 +- .../JavaAssistClassMarkerFactory.java | 5 +- .../javassist/JavassistMockClassLoader.java | 10 +- .../GlobalNotificationBuildSupport.java | 12 +- .../core/transformers/MethodSignatures.java | 7 +- .../TestClassTransformerBuilder.java | 3 +- .../AbstractJavaAssistMockTransformer.java | 3 +- .../ClassFinalModifierMockTransformer.java | 3 +- .../ConstructorsMockTransformer.java | 3 +- .../javassist/InstrumentMockTransformer.java | 5 +- .../javassist/MethodMockTransformer.java | 5 +- .../javassist/MethodSizeMockTransformer.java | 4 +- .../PackagePrivateClassesMockTransformer.java | 3 +- .../StaticFinalFieldsMockTransformer.java | 4 +- ...taticFinalNativeMethodMockTransformer.java | 3 +- ...pressStaticInitializerMockTransformer.java | 5 +- .../JavaAssistClassWrapperFactory.java | 3 +- .../support/PowerMockExpressionEditor.java | 7 +- .../javassist/support/Primitives.java | 6 +- ...MethodsJavaAssistTestClassTransformer.java | 5 +- ...sExceptJavaAssistTestClassTransformer.java | 3 +- .../JavaAssistTestClassTransformer.java | 17 +- .../support/DefaultMockTransformerChain.java | 5 +- .../support/FilterPredicates.java | 8 +- .../MockPolicyClassLoadingSettingsImpl.java | 8 +- .../MockPolicyInterceptionSettingsImpl.java | 16 +- .../AbstractCommonTestSuiteChunkerImpl.java | 30 +- .../impl/AbstractTestClassExtractor.java | 6 +- .../impl/AbstractTestSuiteChunkerImpl.java | 5 +- .../PowerMockIgnorePackagesExtractorImpl.java | 6 +- .../impl/PrepareForTestExtractorImpl.java | 4 +- ...taticConstructorSuppressExtractorImpl.java | 4 +- .../tests/utils/impl/TestChunkImpl.java | 42 +-- .../java/org/powermock/utils/ArrayUtil.java | 4 +- .../java/org/powermock/utils/IOUtils.java | 13 +- .../java/org/powermock/utils/JavaVersion.java | 232 --------------- .../support/ConfigurationBuilderTest.java | 2 +- .../support/ConfigurationFactoryImplTest.java | 2 +- .../MockClassLoaderBuilderTest.java | 25 +- .../MockClassLoaderConfigurationTest.java | 3 +- .../MockClassLoaderFactoryTest.java | 22 +- .../core/classloader/MockClassLoaderTest.java | 14 +- .../core/test/ClassLoaderTestHelper.java | 9 +- .../GlobalNotificationBuildSupportTest.java | 5 +- .../AbstractBaseMockTransformerTest.java | 3 +- ...ClassFinalModifierMockTransformerTest.java | 38 +-- .../ConstructorCallMockTransformerTest.java | 80 ++--- ...nstructorModifiersMockTransformerTest.java | 35 +-- .../InstrumentMockTransformerTest.java | 17 +- .../MethodSizeMockTransformerTest.java | 17 +- .../MethodsMockTransformerTest.java | 58 ++-- .../MockTransformerChainTest.java | 2 +- .../MockTransformerTestHelper.java | 6 +- .../NativeMethodsMockTransformerTest.java | 47 ++- .../StaticFinalFieldsMockTransformerTest.java | 14 +- .../StaticMethodsMockTransformerTest.java | 19 +- ...sStaticInitializerMockTransformerTest.java | 16 +- .../TestClassTransformerTest.java | 23 +- .../javassist/TestPrimitives.java | 14 +- .../transformers/mock/MockGatewaySpy.java | 14 +- ...erMockIgnorePackagesExtractorImplTest.java | 2 +- .../impl/PrepareForTestExtractorImplTest.java | 2 +- .../org/powermock/utils/JavaVersionTest.java | 16 - .../org/powermock/utils/NumberUtilsTest.java | 2 +- .../MainMockTransformerTestSupport.java | 1 + .../com/sun/tools/attach/VirtualMachine.java | 50 ++-- .../attach/VirtualMachineDescriptor.java | 11 +- .../sun/tools/attach/spi/AttachProvider.java | 22 +- .../agent/AbstractClassTransformer.java | 6 +- .../modules/agent/AgentInitialization.java | 15 +- .../powermock/modules/agent/AgentLoader.java | 23 +- .../agent/DefinalizingClassTransformer.java | 7 +- .../modules/agent/PowerMockAgent.java | 18 +- .../agent/PowerMockClassTransformer.java | 15 +- .../support/JavaAgentClassRegisterImpl.java | 12 +- .../sun/tools/attach/BsdVirtualMachine.java | 27 +- .../tools/attach/HotSpotVirtualMachine.java | 22 +- .../sun/tools/attach/LinuxVirtualMachine.java | 27 +- .../tools/attach/SolarisVirtualMachine.java | 14 +- .../tools/attach/WindowsVirtualMachine.java | 16 +- .../impl/JUnit4TestMethodChecker.java | 2 - .../impl/JUnit4TestSuiteChunkerImpl.java | 8 +- .../modules/junit4/rule/PowerMockRule.java | 2 +- .../junit4/PowerMockRunnerDelegate.java | 6 +- .../impl/DelegatingPowerMockRunner.java | 68 ++--- .../internal/impl/NotificationBuilder.java | 7 +- .../PowerMockJUnit4RunnerDelegateImpl.java | 30 +- .../internal/impl/PowerMockRunNotifier.java | 3 +- .../PowerMockJUnit4MethodValidator.java | 5 +- .../impl/PowerMockRunNotifierTest.java | 4 +- .../testng/PowerMockObjectFactory.java | 2 +- ...erMockExpectedExceptionsExtractorImpl.java | 5 +- .../PowerMockTestNGMethodHandler.java | 8 +- .../internal/TestClassInstanceFactory.java | 3 +- .../testng/internal/TestNGMethodFilter.java | 4 +- .../java/org/powermock/reflect/Whitebox.java | 2 +- .../CandidateConstructorSearcher.java | 4 +- .../reflect/internal/ConstructorFinder.java | 2 +- .../reflect/internal/ParametersMatcher.java | 4 +- .../reflect/internal/WhiteboxImpl.java | 149 ++++------ .../primitivesupport/BoxedWrapper.java | 2 +- .../primitivesupport/PrimitiveWrapper.java | 2 +- .../internal/proxy/UnproxiedTypeFactory.java | 4 +- .../reflect/WhiteBoxGetFieldTest.java | 4 +- .../org/powermock/reflect/WhiteBoxTest.java | 172 +++++------ .../ClassFieldsNotInTargetContext.java | 2 +- .../InstanceFieldsNotInTargetContext.java | 2 +- .../reflect/internal/WhiteboxImplTest.java | 11 +- .../internal/proxy/ProxyFrameworksTest.java | 38 +-- .../testclasses/ClassWithInternalState.java | 2 +- .../reflect/testclasses/ClassWithList.java | 2 +- .../testclasses/ClassWithPrivateMethods.java | 76 ++--- tests/build.gradle | 4 - .../junit4/agent/AnnotationUsageTest.java | 5 +- .../junit4/agent/LargeMethodTest.java | 3 +- .../AssertThatJUnit4FailuresWorkTest.java | 1 - .../AbstractMethodMockingTest.java | 6 +- .../AnnotationDemoWithSetupMethodTest.java | 4 +- ...otationInjectionAndFieldDefaulterTest.java | 1 + .../FinalDemoWithAnnotationInjectionTest.java | 1 + ...alDemoWithNiceAnnotationInjectionTest.java | 1 + ...DemoWithStrictAnnotationInjectionTest.java | 1 + .../TestSubjectEasymockAnnotationTest.java | 1 + .../TestSubjectPowermockAnnotationTest.java | 1 + .../classhierarchy/CommonParentTest.java | 1 + .../ClassWithInnerMembersTest.java | 7 +- ...ivateConstructorInstantiationDemoTest.java | 1 + ...blicConstructorWithDependencyDemoTest.java | 5 +- .../ConstructorArgsDemoTest.java | 9 +- .../easymock/EasyMockAndPowerMockMixTest.java | 6 +- .../junit4/enummocking/EnumMockingTest.java | 5 +- .../EqualsWithGetClassTest.java | 1 + .../junit4/expectnew/ExpectNewCases.java | 20 +- .../junit4/expectnew/ExpectNewDemoTest.java | 5 +- .../ExpectNewOfFinalSystemClassTest.java | 6 +- .../junit4/expectnew/MockDateTest.java | 7 +- .../PrimitiveAndWrapperDemoTest.java | 1 + .../PrimitiveAndWrapperUserTest.java | 6 +- .../junit4/expectvoid/ExpectVoidDemoTest.java | 7 +- .../junit4/finalmocking/FinalDemoTest.java | 5 +- ...InstanceMethodsInFinalSystemClassTest.java | 77 ++--- .../junit4/finalmocking/NoDuplicateTest.java | 5 +- ...erMockUsesIdentityHashMapToStoreMocks.java | 1 + ...eOfStaticFinalFieldInInterfacesDefect.java | 1 + .../java/MockClassesInsideJavaPackage.java | 5 +- .../junit4/largemethod/LargeMethodTest.java | 3 +- ...PrivateInnerInterfacesInTestClassTest.java | 20 +- .../MockPolicyUsageExampleTest.java | 5 +- .../MockPolicyWithExpectationsTest.java | 9 +- .../MockPolicyWithInvocationHandlerTest.java | 44 ++- .../SimpleFrameworkMockPolicy.java | 5 +- .../SimpleFrameworkUserTest.java | 1 + .../MultiReplayVerifyTest.java | 8 +- .../NativeMockingSampleTest.java | 6 +- .../junit4/newmocking/StupidNewTest.java | 5 +- .../samples/junit4/nice/NiceDemoTest.java | 5 +- .../noannotation/NoAnnotationUsageTest.java | 9 +- ...pAndTearDownWhenExtendingTestCaseTest.java | 3 +- ...lyCalledOnceWhenExtendingTestCaseTest.java | 3 +- ...ConstructorWorksWhenExtendingTestCase.java | 7 +- ...ameNameButDifferentDefinitionTypeTest.java | 8 +- .../overloading/OverloadingDemoTest.java | 8 +- .../partialmocking/MockSelfDemoTest.java | 12 +- .../MockSelfDemoWithSubClassTest.java | 6 +- .../PartialMockingWithConstructorTest.java | 5 +- ...ckingWithConstructorUsingEasyMockTest.java | 47 +-- .../PowerMockIgnoreAndPrepareForTest.java | 8 +- ...ingThePrepareEverythingAnnotationTest.java | 32 +- .../privateandfinal/PrivateFinalTest.java | 1 + .../MockSelfPrivateFieldServiceClassTest.java | 6 +- .../SimplePrivateFieldServiceClassTest.java | 1 + .../privatemocking/PrivateMethodDemoTest.java | 11 +- .../ReflectionInstantiatorTest.java | 1 + .../replayall/ReplayAllForExpectNewTest.java | 14 +- .../ReplayAllForStaticMethodsTest.java | 7 +- .../resetmock/ResetForStaticMethodsTest.java | 7 +- .../junit4/resetmock/ResetMockTest.java | 8 +- .../rules/AssertThatJUnitRulesWorks.java | 2 +- .../rules/ExceptionHandlingRuleTest.java | 5 +- .../samples/junit4/rules/RuleOrderTest.java | 4 +- .../servletmocking/SampleServletTest.java | 9 +- .../SimpleReturnExampleUserTest.java | 5 +- .../LogicAndTestInSameClassTest.java | 7 +- .../junit4/singleton/MockStaticTest.java | 7 +- .../singleton/SimpleStaticServiceTest.java | 5 +- .../StaticAndInstanceDemoTest.java | 7 +- ...ndInstanceWithConstructorCodeDemoTest.java | 7 +- .../AbstractStaticInitializerTest.java | 1 + .../EvilStaticInitializerExampleTest.java | 1 + ...InterfaceStaticInitializerExampleTest.java | 1 + .../StaticInitializerExampleTest.java | 5 +- .../samples/junit4/strict/StrictDemoTest.java | 7 +- .../junit4/stubmethod/StubMethodTest.java | 3 +- .../CreateUnmockedTest.java | 1 + .../SuppressConstructorDemoTest.java | 10 +- .../SuppressConstructorHierarchyDemoTest.java | 81 ++--- .../SuppressNonParentConstructorDemoTest.java | 1 + .../suppressfield/ItemRepositoryTest.java | 1 + .../suppressfield/SuppressFieldTest.java | 1 + .../suppressmethod/SuppressMethodTest.java | 1 + .../swing/ReallySimpleSwingDemoTest.java | 10 +- .../junit4/system/FieldMockDefect.java | 4 +- .../junit4/system/SystemClassUserTest.java | 16 +- .../testhierarchy/RunWithHierarchyTest.java | 1 + .../junit4/verify/AssertVerifyWorksTest.java | 6 +- .../PowerMockConstructorFiltrationTest.java | 3 +- .../MethodInvocationDemoTest.java | 5 +- .../PackagePrivateClassTest.java | 5 +- .../SuppressDefaultConstructorTest.java | 1 - .../junit410/expectnew/ExpectNewDemoTest.java | 5 +- .../ExpectNewOfFinalSystemClassTest.java | 6 +- .../rules/AssertThatJUnit410RulesWorks.java | 5 +- .../rules/ExceptionHandlingRuleTest.java | 5 +- .../github755/TwoObjectsAnnotatedTest.java | 4 +- .../junit412/expectnew/ExpectNewDemoTest.java | 5 +- .../ExpectNewOfFinalSystemClassTest.java | 1 + .../TwoMockFieldsWithDifferentTypesClass.java | 1 + .../testng/agent/AnnotationDemoTest.java | 1 + .../AnnotationDemoWithBeforeMethodTest.java | 31 +- .../samples/testng/agent/FinalDemoTest.java | 8 +- ...ockStaticExtendsPowerMockTestCaseTest.java | 5 +- .../samples/testng/agent/MockStaticTest.java | 1 + .../PartialMockingWithBeforeClassTest.java | 1 + .../testng/agent/PrivateFinalTest.java | 1 + .../testng/agent/SampleServletTest.java | 9 +- .../testng/agent/SystemClassUserTest.java | 12 +- .../samples/testng/AnnotationDemoTest.java | 1 + .../AnnotationDemoWithBeforeMethodTest.java | 31 +- .../test/java/samples/testng/FinalTest.java | 5 +- ...ockStaticExtendsPowerMockTestCaseTest.java | 5 +- .../java/samples/testng/MockStaticTest.java | 1 + .../PartialMockingWithBeforeClassTest.java | 1 + .../java/samples/testng/PrivateFinalTest.java | 1 + .../samples/testng/SampleServletTest.java | 9 +- .../testng/StaticInitializerExampleTest.java | 12 +- .../samples/testng/SystemClassUserTest.java | 12 +- tests/java11/build.gradle | 27 +- .../junit4/bugs/github958/Github958Test.java | 2 +- .../github510/ClassUsesInterfaceTest.java | 2 +- .../github510/ClassUsesInterfaceTest.java | 2 +- .../LargeMethodInInterfaceTest.java | 1 + .../junit4/bugs/github510/Github510Test.java | 2 +- .../junit4/bugs/github352/GitHub352Test.java | 2 +- .../junit4/bugs/github722/GitHub722Test.java | 2 +- .../bugs/github722/UseTheoriesTest.java | 2 +- .../MockitoFinalClassMockingTest.java | 11 +- .../github793/PartialMockingExampleTest.java | 1 + .../github793/PowerMockStaticMockingTest.java | 14 +- .../junit4/agent/AnnotationUsageTest.java | 5 +- ...owerMockRuleDelagatesToOtherRulesTest.java | 4 +- .../junit4/agent/LargeMethodTest.java | 1 + .../agent/MemberModificationExampleTest.java | 7 +- .../agent/MockFinalNonStaticMethodsTest.java | 1 + .../agent/MockFinalUsingAnnotationsTest.java | 3 +- .../junit4/agent/MockStaticTest.java | 1 + .../agent/MockStaticWithPrivateCtorTest.java | 1 + .../agent/PrivateInstanceMockingTest.java | 1 + .../junit4/agent/StubMethodTest.java | 3 +- .../agent/SuppressConstructorDemoTest.java | 1 + .../SuppressConstructorHierarchyDemoTest.java | 77 ++--- .../junit4/agent/SystemClassUserTest.java | 12 +- .../junit4/agent/WhenNewTest.java | 5 +- .../junit4/agent/github512/Github512Test.java | 3 +- .../mockito/junit4/delegate/EnclosedTest.java | 6 +- .../junit4/delegate/JUnitParamsTest.java | 5 +- .../mockito/junit4/delegate/SelfieTest.java | 4 +- .../delegate/SuppressedMethodStubbing.java | 22 +- .../junit4/delegate/SystemClassUserCases.java | 12 +- .../delegate/SystemClassUserMethod.java | 8 +- .../junit4/delegate/WhenNewCaseMethod.java | 8 +- .../delegate/parameterized/FinalDemoTest.java | 17 +- .../MockFinalUsingAnnotationsTest.java | 10 +- .../parameterized/StubMethodTest.java | 23 +- .../SuppressConstructorDemoTest.java | 8 +- .../SuppressConstructorHierarchyDemoTest.java | 10 +- .../SupressMethodExampleTest.java | 21 +- .../parameterized/SystemClassUserTest.java | 10 +- .../delegate/parameterized/WhenNewTest.java | 21 +- .../MockFinalNonStaticMethodsTest.java | 1 + .../junit4/rule/objenesis/MockStaticTest.java | 1 + .../rule/objenesis/PowerMockRuleTest.java | 2 +- .../objenesis/PrivateInstanceMockingTest.java | 1 + .../StaticInitializerExampleTest.java | 5 +- .../rule/objenesis/SystemClassUserTest.java | 5 +- .../junit4/rule/objenesis/WhenNewTest.java | 5 +- .../bugs/github512/Github512Test.java | 3 +- ...owerMockRuleDelagatesToOtherRulesTest.java | 5 +- .../MockFinalNonStaticMethodsTest.java | 1 + .../junit4/rule/xstream/MockStaticTest.java | 1 + .../rule/xstream/PowerMockRuleTest.java | 2 +- .../xstream/PrivateInstanceMockingTest.java | 1 + .../xstream/StaticInitializerExampleTest.java | 5 +- .../rule/xstream/SystemClassUserTest.java | 5 +- .../junit4/rule/xstream/WhenNewTest.java | 1 + .../rule/xstream/github512/Github512Test.java | 3 +- .../junit4/FinalEqualsClassTest.java | 5 +- .../AbstractMethodMockingTest.java | 9 +- .../annotationbased/CaptorAnnotationTest.java | 6 +- ...unkingAndStaticInitializerRemovalTest.java | 1 + .../InjectMocksAnnotationTest.java | 1 + .../MockFinalUsingAnnotationsTest.java | 3 +- ...kFinalUsingAnnotationsWithAnswersTest.java | 1 + .../annotationbased/SpyAnnotationTest.java | 1 + .../argumentmatcher/ArgumentMatcherTest.java | 5 +- .../junit4/bugs/github668/GitHub668Test.java | 8 +- .../junit4/bugs/github701/GitHub701Test.java | 2 +- .../github704/PrepareForTestSignedTest.java | 2 +- .../bugs/github731/MockingInterfacesTest.java | 1 - .../junit4/bugs/github781/GitHub781Test.java | 2 +- .../github801/GlobalPowerMockIgnoreTest.java | 2 +- .../InnerConstructorsAreFoundTest.java | 4 +- .../junit4/enums/EnumWithConstructorTest.java | 1 + .../finalmocking/MockFinalMethodsCases.java | 7 +- .../MockFinalNonStaticMethodsTest.java | 1 + .../getannotation/GetAnnotationTest.java | 9 +- .../junit4/getclass/GetClassTest.java | 5 +- .../junit4/jacoco/JacocoCoverageTest.java | 24 +- .../junit4/jacoco/TargetTest.java | 2 +- .../junit4/largemethod/LargeMethodTest.java | 1 + .../MemberModificationExampleTest.java | 16 +- .../PartialMockingExampleTest.java | 24 +- .../PartialMockingRetainsStateTest.java | 1 + .../PrivatePartialMockingExampleTest.java | 8 +- .../StaticPartialMockingTest.java | 25 +- .../PrivateInstanceMockingCases.java | 12 +- .../PrivateInstanceMockingTest.java | 1 + .../junit4/proxymethod/ProxyMethodTest.java | 5 +- .../junit4/simplemix/SimpleMixTest.java | 12 +- .../powermockito/junit4/spy/SpyTest.java | 5 +- .../LocationFromStackTraceTest.java | 15 +- .../StaticAndInstanceDemoTest.java | 6 +- .../junit4/staticmocking/MockStaticCases.java | 13 +- .../junit4/staticmocking/MockStaticTest.java | 1 + .../junit4/stress/PowerMockStressTest.java | 1 + .../junit4/system/SystemClassUserTest.java | 27 +- .../verify/VerifyNoMoreInteractionsTest.java | 3 +- .../verify/VerifyZeroInteractionsTest.java | 36 +-- ...ortCreatingMocksInFieldsWhenNewDefect.java | 1 + .../junit4/whennew/NewFileExampleTest.java | 8 +- .../whennew/VerifyNewMultipleTimesTest.java | 7 +- .../whennew/VerifyNewWithoutWhenNewTest.java | 1 + .../junit4/whennew/WhenNewCases.java | 32 +- .../junit4/withsettings/WithSettingsTest.java | 1 + .../junit4/rules/JUnit49RuleTest.java | 8 +- .../MockStaticNotPreparedTest.java | 1 + ...ckStaticPreparedWithoutMockStaticTest.java | 1 + .../staticmocking/MockitoMockStaticTest.java | 1 + .../testng/bugs/github647/GitHub647.java | 3 +- .../utils/src/main/java/samples/Service.java | 2 +- .../EqualsWithGetClass.java | 8 +- .../java/samples/expectnew/ExpectNewDemo.java | 276 +++++++++--------- .../fieldmock/FieldInitializerDemo.java | 6 +- .../hashcode/HashCodeInitializedInCtor.java | 5 +- .../InterfaceWithStaticFinalField.java | 2 +- .../InterfaceMethodHierarchyUsage.java | 27 +- .../interfacemethodfinding/WsUtil.java | 4 +- .../samples/partialmocking/MockSelfDemo.java | 4 +- .../MockSelfPrivateFieldServiceClass.java | 3 +- .../samples/servletmocking/SampleServlet.java | 3 +- .../java/samples/singleton/StaticService.java | 2 +- .../StaticAndInstanceDemo.java | 2 +- .../InterfaceComputation.java | 6 +- .../StaticInitializerExample.java | 2 +- .../suppressconstructor/AppaleList.java | 4 +- .../samples/suppressfield/ItemRepository.java | 2 +- .../java/samples/swing/SimpleSwingDemo.java | 46 ++- .../java/samples/system/SystemClassUser.java | 9 +- 432 files changed, 2384 insertions(+), 2569 deletions(-) delete mode 100644 powermock-core/src/main/java/org/powermock/utils/JavaVersion.java delete mode 100644 powermock-core/src/test/java/org/powermock/utils/JavaVersionTest.java diff --git a/build.gradle b/build.gradle index cde5092cb..5799cd6f5 100644 --- a/build.gradle +++ b/build.gradle @@ -14,7 +14,6 @@ buildscript { classpath 'net.researchgate:gradle-release:2.4.0' classpath 'com.github.jengelman.gradle.plugins:shadow:1.2.4' classpath 'org.shipkit:shipkit:2.3.5' - classpath 'ru.vyarus:gradle-animalsniffer-plugin:1.5.4' } } @@ -35,7 +34,7 @@ ext{ servletVersion = "2.5" jacocoVersion = "0.7.7.201606060606" eclipseJdt = "3.3.0-v_771" - checkstyleVersion= "7.6.1" + checkstyleVersion = "9.2.1" systemRulesVersion="1.18.0" } diff --git a/config/checkstyle/checkstyle.xml b/config/checkstyle/checkstyle.xml index 464bfbd53..01c09fa44 100644 --- a/config/checkstyle/checkstyle.xml +++ b/config/checkstyle/checkstyle.xml @@ -1,4 +1,4 @@ - + @@ -48,7 +48,6 @@ - @@ -65,7 +64,7 @@ - + @@ -96,7 +95,7 @@ - + @@ -140,7 +139,11 @@ - + + + + + @@ -160,4 +163,7 @@ + + + diff --git a/gradle/java-module.gradle b/gradle/java-module.gradle index accbf20ab..50cf8b095 100644 --- a/gradle/java-module.gradle +++ b/gradle/java-module.gradle @@ -10,19 +10,17 @@ apply plugin: 'propdeps' apply plugin: 'propdeps-maven' apply plugin: 'java' -targetCompatibility = 1.6 -sourceCompatibility = 1.6 +targetCompatibility = JavaVersion.VERSION_1_8 +sourceCompatibility = JavaVersion.VERSION_1_8 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') - } +apply plugin: 'checkstyle' +checkstyle { + toolVersion = checkstyleVersion + configFile = rootProject.file('config/checkstyle/checkstyle.xml') } test{ diff --git a/gradle/modules.gradle b/gradle/modules.gradle index 7d1225e6d..fe4e59c9c 100644 --- a/gradle/modules.gradle +++ b/gradle/modules.gradle @@ -43,16 +43,6 @@ configure(genericModules) { project -> } } -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." diff --git a/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/EasyMockConfiguration.java b/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/EasyMockConfiguration.java index fde018ab0..bc639195c 100644 --- a/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/EasyMockConfiguration.java +++ b/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/EasyMockConfiguration.java @@ -62,9 +62,7 @@ private void initInjectMocksSupported() { Class clazz = Class.forName("org.easymock.EasyMockSupport"); clazz.getDeclaredMethod("injectMocks", Object.class); injectMocksSupported = true; - } catch (NoSuchMethodException e) { - injectMocksSupported = false; - } catch (ClassNotFoundException e) { + } catch (NoSuchMethodException | ClassNotFoundException e) { injectMocksSupported = false; } } diff --git a/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/PowerMock.java b/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/PowerMock.java index 3a501ec70..1d2448cb9 100644 --- a/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/PowerMock.java +++ b/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/PowerMock.java @@ -15,16 +15,16 @@ */ package org.powermock.api.easymock; -import net.sf.cglib.proxy.Enhancer; import org.easymock.ConstructorArgs; +import org.easymock.EasyMock; 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.invocationcontrol.NewInvocationControlAssertionError; 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; @@ -58,6 +58,8 @@ import java.util.List; import java.util.Set; +import net.sf.cglib.proxy.Enhancer; + /** * PowerMock extends EasyMock functionality with several new features such as * mocking static and private methods, mocking new instances and more. Use @@ -616,7 +618,7 @@ public static synchronized void mockStaticPartialNice(Class clazz, String... static T doMockSpecific(Class type, MockStrategy mockStrategy, String[] methodNamesToMock, ConstructorArgs constructorArgs, Class... argumentTypes) { - List methods = new LinkedList(); + List methods = new LinkedList<>(); for (String methodName : methodNamesToMock) { methods.add(WhiteboxImpl.findMethodOrThrowException(type, methodName, argumentTypes)); } @@ -1246,13 +1248,13 @@ public static synchronized IExpectationSetters expectPrivate(Object insta /** * This method just delegates to EasyMock class extensions - * {@link org.easymock.EasyMock#expectLastCall()} method. + * {@link EasyMock#expectLastCall()} method. * * @return The expectation setter. - * @see org.easymock.EasyMock#expectLastCall() + * @see EasyMock#expectLastCall() */ public static synchronized IExpectationSetters expectLastCall() { - return org.easymock.EasyMock.expectLastCall(); + return EasyMock.expectLastCall(); } /** @@ -1375,7 +1377,7 @@ public static synchronized void reset(Object... mocks) { * no handler registered for this object. */ try { - org.easymock.EasyMock.reset(mock); + EasyMock.reset(mock); } catch (RuntimeException e) { throw new RuntimeException(mock + " is not a mock object", e); } @@ -1441,7 +1443,7 @@ public static synchronized void replay(Object... mocks) { * no handler registered for this object. */ try { - org.easymock.EasyMock.replay(mock); + EasyMock.replay(mock); } catch (RuntimeException e) { throw new RuntimeException(mock + " is not a mock object", e); } @@ -1483,7 +1485,7 @@ public static synchronized void verify(Object... objects) { * handler registered for this object. */ try { - org.easymock.EasyMock.verify(mock); + EasyMock.verify(mock); } catch (RuntimeException e) { throw new RuntimeException(mock + " is not a mock object", e); } @@ -1645,7 +1647,7 @@ private static IExpectationSetters doExpectNew(Class type, MockStrateg if (newInvocationControl == null) { InvocationSubstitute mock = doMock(InvocationSubstitute.class, false, mockStrategy, null, (Method[]) null); - newInvocationControl = new EasyMockNewInvocationControl(mock, type); + newInvocationControl = new EasyMockNewInvocationControl<>(mock, type); MockRepository.putNewInstanceControl(type, newInvocationControl); MockRepository.addObjectsToAutomaticallyReplayAndVerify(WhiteboxImpl.getOriginalUnmockedType(type)); } @@ -1924,12 +1926,7 @@ private static T doMock(Class type, boolean isStatic, MockStrategy mockSt /* * Clear the EasyMock state after the test method is executed. */ - MockRepository.addAfterMethodRunner(new Runnable() { - @Override - public void run() { - LastControl.reportLastControl(null); - } - }); + MockRepository.addAfterMethodRunner(() -> LastControl.reportLastControl(null)); IMocksControl control = mockStrategy.createMockControl(type); MockRepository.addAfterMethodRunner(new EasyMockStateCleaner()); @@ -1943,8 +1940,8 @@ public void run() { MockInvocationHandler h = new MockInvocationHandler((MocksControl) control); final Set methodsToMock = toSet(methods); if (isStatic) { - MockRepository.putStaticMethodInvocationControl(type, new EasyMockMethodInvocationControl(h, - methodsToMock, replica)); + MockRepository.putStaticMethodInvocationControl(type, + new EasyMockMethodInvocationControl<>(h, methodsToMock, replica)); MockRepository.addObjectsToAutomaticallyReplayAndVerify(type); return null; } else { @@ -1960,7 +1957,7 @@ public void run() { } } MockRepository.putInstanceMethodInvocationControl(newInstance, - new EasyMockMethodInvocationControl(h, methodsToMock, replica)); + new EasyMockMethodInvocationControl<>(h, methodsToMock, replica)); if (!(newInstance instanceof InvocationSubstitute)) { MockRepository.addObjectsToAutomaticallyReplayAndVerify(newInstance); } @@ -1972,8 +1969,8 @@ public void run() { MockInvocationHandler h = new MockInvocationHandler((MocksControl) control); final Set methodsToMock = toSet(methods); if (isStatic) { - MockRepository.putStaticMethodInvocationControl(type, new EasyMockMethodInvocationControl(h, - methodsToMock, mock)); + MockRepository.putStaticMethodInvocationControl(type, + new EasyMockMethodInvocationControl<>(h, methodsToMock, mock)); MockRepository.addObjectsToAutomaticallyReplayAndVerify(type); } else { MockRepository.putInstanceMethodInvocationControl(mock, new EasyMockMethodInvocationControl(h, @@ -2035,7 +2032,7 @@ private static T doCreateMock(Class type, ConstructorArgs constructorArgs } private static Set toSet(Method[] methods) { - return methods == null ? null : new HashSet(Arrays.asList(methods)); + return methods == null ? null : new HashSet<>(Arrays.asList(methods)); } private static Class[] mergeArgumentTypes(Class firstArgumentType, Class... additionalArgumentTypes) { @@ -2056,7 +2053,7 @@ private static Class[] mergeArgumentTypes(Class firstArgumentType, Class IExpectationSetters doExpectPrivate(Object instance, Method methodToExpect, Object... arguments) throws Exception { WhiteboxImpl.performMethodInvocation(instance, methodToExpect, arguments); - return (IExpectationSetters) org.easymock.EasyMock.expectLastCall(); + return (IExpectationSetters) EasyMock.expectLastCall(); } private static synchronized void replay(Class... types) { @@ -2125,7 +2122,7 @@ private void clearStateFromOtherClassLoaders() { } private Iterable classloadersToClear() { - List loaders = new ArrayList(); + List loaders = new ArrayList<>(); final ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader(); final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); if (classFoundInClassloader(LastControl.class, systemClassLoader)) { diff --git a/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/internal/mockstrategy/impl/AbstractMockStrategyBase.java b/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/internal/mockstrategy/impl/AbstractMockStrategyBase.java index 2868e3f14..87be76983 100644 --- a/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/internal/mockstrategy/impl/AbstractMockStrategyBase.java +++ b/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/internal/mockstrategy/impl/AbstractMockStrategyBase.java @@ -1,8 +1,8 @@ package org.powermock.api.easymock.internal.mockstrategy.impl; import org.easymock.IMocksControl; -import org.easymock.internal.MocksControl; import org.easymock.MockType; +import org.easymock.internal.MocksControl; import org.powermock.api.easymock.internal.mockstrategy.MockStrategy; /** diff --git a/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/mockpolicies/JclMockPolicy.java b/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/mockpolicies/JclMockPolicy.java index 6274a2d1e..8fce1a9a2 100644 --- a/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/mockpolicies/JclMockPolicy.java +++ b/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/easymock/mockpolicies/JclMockPolicy.java @@ -36,7 +36,8 @@ public class JclMockPolicy extends AbstractEasyMockLogPolicyBase { /** * Loads all log4j classes with the mock classloader. */ - protected String[] getFullyQualifiedNamesOfClassesToLoadByMockClassloader() { + @Override + protected String[] getFullyQualifiedNamesOfClassesToLoadByMockClassloader() { return new String[] { "org.apache.commons.logging.*", "org.apache.log4j.Appender", "org.apache.log4j.xml.DOMConfigurator" }; } diff --git a/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/AnnotationEnabler.java b/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/AnnotationEnabler.java index fbb8626f5..c15063cc0 100644 --- a/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/AnnotationEnabler.java +++ b/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/AnnotationEnabler.java @@ -29,7 +29,7 @@ /** *

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

@@ -42,7 +42,7 @@ * {@code null}). *

* - * @see org.powermock.api.easymock.annotation.Mock + * @see Mock * @see org.easymock.Mock * @see org.easymock.TestSubject * @@ -51,6 +51,7 @@ public class AnnotationEnabler extends AbstractPowerMockTestListenerBase implements AnnotationEnablerListener { + @Override @SuppressWarnings("unchecked") public Class[] getMockAnnotations() { return new Class[]{Mock.class, MockNice.class, MockStrict.class}; diff --git a/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/AnnotationGlobalMetadata.java b/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/AnnotationGlobalMetadata.java index ce32bcd1c..263c261ae 100644 --- a/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/AnnotationGlobalMetadata.java +++ b/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/AnnotationGlobalMetadata.java @@ -27,11 +27,11 @@ */ class AnnotationGlobalMetadata { - private final List qualifiedInjections = new ArrayList(5); + private final List qualifiedInjections = new ArrayList<>(5); - private final List unqualifiedInjections = new ArrayList(5); + private final List unqualifiedInjections = new ArrayList<>(5); - private final Set qualifiers = new HashSet(); + private final Set qualifiers = new HashSet<>(); public List getQualifiedInjections() { return qualifiedInjections; diff --git a/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/AnnotationMockCreatorFactory.java b/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/AnnotationMockCreatorFactory.java index 7a4fd3b84..28aef3f65 100644 --- a/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/AnnotationMockCreatorFactory.java +++ b/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/AnnotationMockCreatorFactory.java @@ -17,40 +17,18 @@ package org.powermock.api.extension.listener; -import java.lang.reflect.Method; +import org.powermock.api.easymock.PowerMock; -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); - } - }; + return PowerMock::createMock; } public AnnotationMockCreator createNiceMockCreator() { - return new AnnotationMockCreator() { - @Override - public Object createMockInstance(Class type, Method[] methods) { - return createNiceMock(type, methods); - } - }; + return PowerMock::createNiceMock; } public AnnotationMockCreator createStrictMockCreator() { - return new AnnotationMockCreator() { - @Override - public Object createMockInstance(Class type, Method[] methods) { - return createStrictMock(type, methods); - } - }; + return PowerMock::createStrictMock; } } diff --git a/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/AnnotationMockMetadata.java b/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/AnnotationMockMetadata.java index 5fe5726cb..4a33cc92d 100644 --- a/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/AnnotationMockMetadata.java +++ b/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/AnnotationMockMetadata.java @@ -23,6 +23,7 @@ import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Arrays; +import java.util.Objects; @SuppressWarnings("WeakerAccess") public class AnnotationMockMetadata implements MockMetadata { @@ -111,9 +112,9 @@ public boolean equals(Object o) { AnnotationMockMetadata that = (AnnotationMockMetadata) o; - if (type != null ? !type.equals(that.type) : that.type != null) { return false; } + if (!Objects.equals(type, that.type)) { 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); + return Arrays.equals(methods, that.methods) && (Objects.equals(qualifier, that.qualifier)); } diff --git a/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/AnnotationMockScanner.java b/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/AnnotationMockScanner.java index 06907da08..dbf45eee5 100644 --- a/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/AnnotationMockScanner.java +++ b/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/AnnotationMockScanner.java @@ -33,7 +33,7 @@ public AnnotationMockScanner(Class annotation) { } public List scan(Object instance) throws Exception { - final List mocksMetadata = new ArrayList(); + final List mocksMetadata = new ArrayList<>(); final Set fields = getFields(instance); for (Field field : fields) { if (field.get(instance) != null) { diff --git a/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/DefaultInjectFieldSearcher.java b/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/DefaultInjectFieldSearcher.java index 2f0228d99..9ab7240a5 100644 --- a/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/DefaultInjectFieldSearcher.java +++ b/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/DefaultInjectFieldSearcher.java @@ -66,7 +66,7 @@ private Set filterByType(Set candidates, Class type) { } private Set doFilterByType(Set candidates, Class type) { - Set fields = new HashSet(); + Set fields = new HashSet<>(); for (Field candidate : candidates) { if (candidate.getType().isAssignableFrom(type)) { fields.add(candidate); @@ -83,7 +83,7 @@ private Set filterByQualifier(Set candidates, String qualifier) { } private Set doFilterByQualifier(Set candidates, String qualifier) { - Set fields = new HashSet(); + Set fields = new HashSet<>(); for (Field candidate : candidates) { if (candidate.getName().equals(qualifier)) { fields.add(candidate); diff --git a/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/TestSubjectInjector.java b/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/TestSubjectInjector.java index 5c0765c5f..cac13ec00 100644 --- a/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/TestSubjectInjector.java +++ b/powermock-api/powermock-api-easymock/src/main/java/org/powermock/api/extension/listener/TestSubjectInjector.java @@ -58,7 +58,7 @@ protected void injectTestSubjectMocks() throws IllegalAccessException { } protected void injectTestSubjectFields(Object testSubject) throws IllegalAccessException { - Set targetFields = new HashSet(Whitebox.getAllInstanceFields(testSubject)); + Set targetFields = new HashSet<>(Whitebox.getAllInstanceFields(testSubject)); targetFields = injectByName(targetFields, testSubject); injectByType(targetFields, testSubject); } @@ -115,9 +115,7 @@ Set injectByName(Set targetFields, Object targetObject) throws Ill private Field getFieldByName(Class clazz, String fieldName) { try { return clazz.getDeclaredField(fieldName); - } catch (NoSuchFieldException e) { - return null; - } catch (SecurityException e) { + } catch (NoSuchFieldException | SecurityException e) { return null; } } diff --git a/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/extension/listener/AnnotationEnabler.java b/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/extension/listener/AnnotationEnabler.java index 70a9425ca..db3ed591d 100644 --- a/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/extension/listener/AnnotationEnabler.java +++ b/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/extension/listener/AnnotationEnabler.java @@ -39,7 +39,7 @@ /** * Before each test method all fields annotated with {@link Mock}, - * {@link org.mockito.Mock} or {@link Mock} have mock objects created for them + * {@link 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. @@ -77,8 +77,8 @@ private void standardInject(Object testInstance) throws IllegalAccessException { } final Class type = field.getType(); - if (field.isAnnotationPresent(org.mockito.Mock.class)) { - org.mockito.Mock mockAnnotation = field.getAnnotation(org.mockito.Mock.class); + if (field.isAnnotationPresent(Mock.class)) { + Mock mockAnnotation = field.getAnnotation(Mock.class); MockSettings mockSettings = withSettings(); Answers answers = mockAnnotation.answer(); if (answers != null) { @@ -105,7 +105,7 @@ private void standardInject(Object testInstance) throws IllegalAccessException { @SuppressWarnings("unchecked") @Override public Class[] getMockAnnotations() { - return new Class[]{org.mockito.Mock.class, Mock.class}; + return new Class[]{ Mock.class, Mock.class}; } private Object processAnnotationOn(Captor annotation, Field field) { diff --git a/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/PowerMockito.java b/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/PowerMockito.java index af98d5fec..d9eb33b74 100644 --- a/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/PowerMockito.java +++ b/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/PowerMockito.java @@ -203,7 +203,7 @@ public static synchronized T spy(T object) { * @see PowerMockito#spy(Object) */ public static synchronized void spy(Class type) { - MockSettings mockSettings = Mockito.withSettings().defaultAnswer(Mockito.CALLS_REAL_METHODS); + MockSettings mockSettings = withSettings().defaultAnswer(Mockito.CALLS_REAL_METHODS); DefaultMockCreator.mock(type, true, true, type, mockSettings, (Method[]) null); } @@ -366,7 +366,7 @@ public static OngoingStubbing when(Object instance, String methodName, Ob * @see PowerMockito#when(Object) */ public static WithOrWithoutExpectedArguments when(Object instance, Method method) { - return new DefaultMethodExpectationSetup(instance, method); + return new DefaultMethodExpectationSetup<>(instance, method); } /** @@ -375,7 +375,7 @@ public static WithOrWithoutExpectedArguments when(Object instance, Method * @see PowerMockito#when(Object) */ public static WithOrWithoutExpectedArguments when(Class cls, Method method) { - return new DefaultMethodExpectationSetup(cls, method); + return new DefaultMethodExpectationSetup<>(cls, method); } /** @@ -427,7 +427,7 @@ public static OngoingStubbing when(T methodCall) { * want to throw an exception or return a mock. */ public static synchronized WithOrWithoutExpectedArguments whenNew(Constructor ctor) { - return new ConstructorAwareExpectationSetup(ctor); + return new ConstructorAwareExpectationSetup<>(ctor); } /** @@ -435,7 +435,7 @@ public static synchronized WithOrWithoutExpectedArguments whenNew(Constru * want to throw an exception or return a mock. */ public static synchronized ConstructorExpectationSetup whenNew(Class type) { - return new DefaultConstructorExpectationSetup(type); + return new DefaultConstructorExpectationSetup<>(type); } /** @@ -449,7 +449,7 @@ public static synchronized ConstructorExpectationSetup whenNew(Class t @SuppressWarnings("unchecked") public static synchronized ConstructorExpectationSetup whenNew(String fullyQualifiedName) throws Exception { final Class forName = (Class) Class.forName(fullyQualifiedName); - return new DefaultConstructorExpectationSetup(forName); + return new DefaultConstructorExpectationSetup<>(forName); } /** diff --git a/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/expectation/ConstructorAwareExpectationSetup.java b/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/expectation/ConstructorAwareExpectationSetup.java index f209b63ba..323e86eee 100644 --- a/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/expectation/ConstructorAwareExpectationSetup.java +++ b/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/expectation/ConstructorAwareExpectationSetup.java @@ -44,7 +44,7 @@ public OngoingStubbing withNoArguments() throws Exception { } private DefaultConstructorExpectationSetup setupExpectation() { - DefaultConstructorExpectationSetup setup = new DefaultConstructorExpectationSetup(ctor.getDeclaringClass()); + DefaultConstructorExpectationSetup setup = new DefaultConstructorExpectationSetup<>(ctor.getDeclaringClass()); setup.setParameterTypes(ctor.getParameterTypes()); return setup; } diff --git a/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/expectation/DefaultConstructorExpectationSetup.java b/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/expectation/DefaultConstructorExpectationSetup.java index 8f6d3c8fa..8bb23f58f 100644 --- a/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/expectation/DefaultConstructorExpectationSetup.java +++ b/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/expectation/DefaultConstructorExpectationSetup.java @@ -104,7 +104,7 @@ public OngoingStubbing withAnyArguments() throws Exception { System.arraycopy(allConstructors, 1, otherCtors, 0, allConstructors.length - 1); final OngoingStubbing ongoingStubbing = createNewSubstituteMock(mockType, parameterTypes, paramArgs); - return new DelegatingToConstructorsOngoingStubbing(otherCtors, ongoingStubbing); + return new DelegatingToConstructorsOngoingStubbing<>(otherCtors, ongoingStubbing); } private Object createParamArgMatcher(Class paramType) { @@ -125,7 +125,7 @@ public WithExpectedArguments withParameterTypes(Class parameterType, Class private DefaultMockCreator getMockCreator() {return mockCreator;} private NewInvocationControl> createNewInvocationControl(InvocationSubstitute mock) { - return new MockitoNewInvocationControl(mock); + return new MockitoNewInvocationControl<>(mock); } void setParameterTypes(Class[] parameterTypes) { diff --git a/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/PowerMockitoCore.java b/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/PowerMockitoCore.java index 2445e71df..58b86cb55 100644 --- a/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/PowerMockitoCore.java +++ b/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/PowerMockitoCore.java @@ -44,57 +44,27 @@ public class PowerMockitoCore { 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); - } - }); + return doAnswer(() -> Mockito.doAnswer(answer)); } public PowerMockitoStubber doThrow(final Throwable toBeThrown) { - return doAnswer(new Callable() { - @Override - public Stubber call() throws Exception { - return Mockito.doThrow(toBeThrown); - } - }); + return doAnswer(() -> Mockito.doThrow(toBeThrown)); } public PowerMockitoStubber doCallRealMethod() { - return doAnswer(new Callable() { - @Override - public Stubber call() throws Exception { - return Mockito.doCallRealMethod(); - } - }); + return doAnswer(Mockito::doCallRealMethod); } public PowerMockitoStubber doNothing() { - return doAnswer(new Callable() { - @Override - public Stubber call() throws Exception { - return Mockito.doNothing(); - } - }); + return doAnswer(Mockito::doNothing); } public PowerMockitoStubber doReturn(final Object toBeReturned) { - return doAnswer(new Callable() { - @Override - public Stubber call() throws Exception { - return Mockito.doReturn(toBeReturned); - } - }); + return doAnswer(() -> 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); - } - }); + return doAnswer(() -> Mockito.doReturn(toBeReturned, othersToBeReturned)); } public DefaultConstructorArgumentsVerification verifyNew(final Class mock, final VerificationMode mode) { @@ -107,7 +77,7 @@ public DefaultConstructorArgumentsVerification verifyNew(final Class m invocationControl.verify(mode); //noinspection unchecked - return new DefaultConstructorArgumentsVerification((NewInvocationControl) invocationControl, mock); + return new DefaultConstructorArgumentsVerification<>((NewInvocationControl) invocationControl, mock); } public T spy(final T object) { diff --git a/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/configuration/PowerMockitoSpyAnnotationEngine.java b/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/configuration/PowerMockitoSpyAnnotationEngine.java index 55909164c..fe9428728 100644 --- a/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/configuration/PowerMockitoSpyAnnotationEngine.java +++ b/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/configuration/PowerMockitoSpyAnnotationEngine.java @@ -40,7 +40,7 @@ public void process(Class context, Object testClass) { if (field.isAnnotationPresent(Spy.class)) { try { Whitebox.invokeMethod(this, Spy.class, field, new Class[] { Mock.class, - org.mockito.Mock.class, Captor.class }); + Mock.class, Captor.class }); } catch (RuntimeException e) { throw e; } catch (Exception e1) { diff --git a/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/exceptions/StackTraceCleanerProvider.java b/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/exceptions/StackTraceCleanerProvider.java index 25e7a8ca7..90858daea 100644 --- a/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/exceptions/StackTraceCleanerProvider.java +++ b/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/exceptions/StackTraceCleanerProvider.java @@ -22,15 +22,10 @@ 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; - } - }; + return candidate -> 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; } } diff --git a/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/invocation/InvocationControlAssertionError.java b/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/invocation/InvocationControlAssertionError.java index cc87e95dc..438b4a72f 100644 --- a/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/invocation/InvocationControlAssertionError.java +++ b/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/invocation/InvocationControlAssertionError.java @@ -144,7 +144,7 @@ private static void removeAndReplaceText(StringBuilder builder, String text, cha previousTextIndex, end, String.valueOf(builder.charAt(previousTextIndex)).toLowerCase() ); - builder.insert(previousTextIndex, String.valueOf(appender)); + builder.insert(previousTextIndex, appender); currentTextIndex++; isSingleConcat = false; } diff --git a/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/mockcreation/DefaultMockCreator.java b/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/mockcreation/DefaultMockCreator.java index b67a8e19f..9e5f14829 100644 --- a/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/mockcreation/DefaultMockCreator.java +++ b/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/mockcreation/DefaultMockCreator.java @@ -40,6 +40,7 @@ public static T mock(Class type, boolean isStatic, boolean isSpy, Object return MOCK_CREATOR.createMock(type, isStatic, isSpy, delegator, mockSettings, methods); } + @Override @SuppressWarnings("unchecked") public T createMock(Class type, boolean isStatic, boolean isSpy, Object delegatorCandidate, MockSettings mockSettings, Method... methods) { @@ -73,12 +74,7 @@ private T doCreateMock(final Class type, final boolean isStatic, final bo } private void registerAfterMethodRunner() { - MockRepository.addAfterMethodRunner(new Runnable() { - @Override - public void run() { - Mockito.reset(); - } - }); + MockRepository.addAfterMethodRunner(Mockito::reset); } private void putMethodInvocationControlToRepository(final Class type, final boolean isStatic, final MockData mockData, final T mock) { @@ -109,7 +105,7 @@ private MockData createMethodInvocationControl(Class type, Method[] me cacheMockClass(mock.getClass()); - return new MockData(new MockitoMethodInvocationControl(delegator, mock, methods), mock); + return new MockData<>(new MockitoMethodInvocationControl(delegator, mock, methods), mock); } private void cacheMockClass(final Class mockClass) { diff --git a/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/mockcreation/MockCreator.java b/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/mockcreation/MockCreator.java index 9331edef4..8b9837e1f 100644 --- a/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/mockcreation/MockCreator.java +++ b/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/mockcreation/MockCreator.java @@ -1,10 +1,12 @@ package org.powermock.api.mockito.internal.mockcreation; +import org.mockito.MockSettings; + 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); + T createMock(Class type, boolean isStatic, boolean isSpy, Object delegator, MockSettings mockSettings, Method... methods); } diff --git a/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/mockcreation/MockTypeValidatorFactory.java b/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/mockcreation/MockTypeValidatorFactory.java index 2751109c1..af2f7b946 100644 --- a/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/mockcreation/MockTypeValidatorFactory.java +++ b/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/mockcreation/MockTypeValidatorFactory.java @@ -12,11 +12,11 @@ public class MockTypeValidatorFactory { public static MockTypeValidator createValidator(Class type, boolean isStatic, boolean isSpy, JavaAgentClassRegister agentClassRegister) { if (!isStatic || isSpy || isLoadedByBootstrap(type)) { - return new NullMockTypeValidator(); + return new NullMockTypeValidator<>(); } else if (agentClassRegister == null) { - return new DefaultMockTypeValidator(type); + return new DefaultMockTypeValidator<>(type); } else { - return new JavaAgentMockTypeValidator(type, agentClassRegister); + return new JavaAgentMockTypeValidator<>(type, agentClassRegister); } } diff --git a/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/stubbing/MockitoRealMethodInvocation.java b/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/stubbing/MockitoRealMethodInvocation.java index e63f31874..b0291e803 100644 --- a/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/stubbing/MockitoRealMethodInvocation.java +++ b/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/internal/stubbing/MockitoRealMethodInvocation.java @@ -20,7 +20,7 @@ public class MockitoRealMethodInvocation { - private static final ThreadLocal handledByMockito = new ThreadLocal(); + private static final ThreadLocal handledByMockito = new ThreadLocal<>(); private MockitoRealMethodInvocation() { } @@ -35,6 +35,6 @@ public static void mockitoInvocationFinished() { public static boolean isHandledByMockito() { final Boolean handled = handledByMockito.get(); - return handled == null ? false : handled; + return handled != null && handled; } } diff --git a/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/invocation/InvocationFactory.java b/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/invocation/InvocationFactory.java index 6e005c639..d12a863a6 100644 --- a/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/invocation/InvocationFactory.java +++ b/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/invocation/InvocationFactory.java @@ -43,21 +43,18 @@ Invocation createInvocation(final Object mock, final Method method, final MockCr 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; + return () -> { + 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; }; } } diff --git a/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/invocation/MockHandlerAdaptor.java b/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/invocation/MockHandlerAdaptor.java index a9e2a4c82..253c4ee0d 100644 --- a/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/invocation/MockHandlerAdaptor.java +++ b/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/invocation/MockHandlerAdaptor.java @@ -31,7 +31,7 @@ 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. + * The class provides a access to method and data of {@link MockHandler} from the given mock instance. */ public class MockHandlerAdaptor { private final T mock; diff --git a/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/invocation/MockitoMethodInvocationControl.java b/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/invocation/MockitoMethodInvocationControl.java index 5413d3586..e2dcac77f 100644 --- a/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/invocation/MockitoMethodInvocationControl.java +++ b/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/invocation/MockitoMethodInvocationControl.java @@ -61,7 +61,7 @@ public class MockitoMethodInvocationControl implements MethodInvocationContro * the {@code invocationHandler} are considered to be */ public MockitoMethodInvocationControl(Object delegator, T mockInstance, Method... methodsToMock) { - this.mockHandlerAdaptor = new MockHandlerAdaptor(mockInstance); + this.mockHandlerAdaptor = new MockHandlerAdaptor<>(mockInstance); this.mockedMethods = toSet(methodsToMock); this.delegator = delegator; } @@ -134,7 +134,7 @@ public void verifyNoMoreInteractions() { } private Set toSet(Method... methods) { - return methods == null ? null : new HashSet(Arrays.asList(methods)); + return methods == null ? null : new HashSet<>(Arrays.asList(methods)); } private boolean hasDelegator() { diff --git a/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/mockpolicies/Slf4jMockPolicy.java b/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/mockpolicies/Slf4jMockPolicy.java index 208fa222c..e39468bda 100644 --- a/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/mockpolicies/Slf4jMockPolicy.java +++ b/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/mockpolicies/Slf4jMockPolicy.java @@ -44,7 +44,7 @@ public class Slf4jMockPolicy implements PowerMockPolicy { private static final String FRAMEWORK_NAME = "sfl4j"; private static final String LOGGER_CLASS_NAME = "org.slf4j.Logger"; - private static ThreadLocal threadLogger = new ThreadLocal(); + private static ThreadLocal threadLogger = new ThreadLocal<>(); @Override public void applyClassLoadingPolicy(MockPolicyClassLoadingSettings mockPolicyClassLoadingSettings) { diff --git a/powermock-api/powermock-api-mockito2/src/test/java/org/powermock/api/mockito/internal/mockcreation/MockCreatorTestCase.java b/powermock-api/powermock-api-mockito2/src/test/java/org/powermock/api/mockito/internal/mockcreation/MockCreatorTestCase.java index 821c41df5..7c2b04098 100644 --- a/powermock-api/powermock-api-mockito2/src/test/java/org/powermock/api/mockito/internal/mockcreation/MockCreatorTestCase.java +++ b/powermock-api/powermock-api-mockito2/src/test/java/org/powermock/api/mockito/internal/mockcreation/MockCreatorTestCase.java @@ -9,7 +9,7 @@ import java.util.List; -import static org.assertj.core.api.Java6Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; public class MockCreatorTestCase { diff --git a/powermock-api/powermock-api-mockito2/src/test/java/org/powermock/api/mockito/mockmaker/PowerMockMakerTestCase.java b/powermock-api/powermock-api-mockito2/src/test/java/org/powermock/api/mockito/mockmaker/PowerMockMakerTestCase.java index 81f5badce..81c454488 100644 --- a/powermock-api/powermock-api-mockito2/src/test/java/org/powermock/api/mockito/mockmaker/PowerMockMakerTestCase.java +++ b/powermock-api/powermock-api-mockito2/src/test/java/org/powermock/api/mockito/mockmaker/PowerMockMakerTestCase.java @@ -40,10 +40,9 @@ import java.net.URLClassLoader; import java.util.ArrayList; import java.util.List; -import java.util.stream.Stream; -import static org.assertj.core.api.Java6Assertions.assertThat; -import static org.assertj.core.api.Java6Assertions.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.junit.Assume.assumeFalse; public class PowerMockMakerTestCase { @@ -84,7 +83,7 @@ private static URL[] urlsFromClassLoader(ClassLoader classLoader) { if (classLoader instanceof URLClassLoader) { return ((URLClassLoader) classLoader).getURLs(); } - List list = new ArrayList(); + List list = new ArrayList<>(); for (String classPathEntry : ManagementFactory.getRuntimeMXBean().getClassPath().split(File.pathSeparator)) { list.add(toURL(classPathEntry)); } diff --git a/powermock-api/powermock-api-support/src/main/java/org/powermock/api/support/membermodification/MemberMatcher.java b/powermock-api/powermock-api-support/src/main/java/org/powermock/api/support/membermodification/MemberMatcher.java index b5a652139..7771844be 100644 --- a/powermock-api/powermock-api-support/src/main/java/org/powermock/api/support/membermodification/MemberMatcher.java +++ b/powermock-api/powermock-api-support/src/main/java/org/powermock/api/support/membermodification/MemberMatcher.java @@ -53,12 +53,11 @@ public static Method[] methodsDeclaredIn(final Class cls, final Class... a if (cls == null) { throw new IllegalArgumentException("You need to supply at least one class."); } - Set methods = new HashSet(); - methods.addAll(asList(WhiteboxImpl.getAllMethods(cls))); + Set methods = new HashSet<>(asList(WhiteboxImpl.getAllMethods(cls))); for (Class klass : additionalClasses) { methods.addAll(asList(WhiteboxImpl.getAllMethods(klass))); } - return methods.toArray(new Method[methods.size()]); + return methods.toArray(new Method[0]); } /** @@ -302,12 +301,11 @@ public static Constructor[] constructorsDeclaredIn(final Class cls, final if (cls == null) { throw new IllegalArgumentException("You need to supply at least one class."); } - Set> constructors = new HashSet>(); - constructors.addAll(asList(WhiteboxImpl.getAllConstructors(cls))); + Set> constructors = new HashSet<>(asList(WhiteboxImpl.getAllConstructors(cls))); for (Class klass : additionalClasses) { constructors.addAll(asList(WhiteboxImpl.getAllConstructors(klass))); } - return constructors.toArray(new Constructor[constructors.size()]); + return constructors.toArray(new Constructor[0]); } /** @@ -336,11 +334,11 @@ public static AccessibleObject[] everythingDeclaredIn(final Class cls, final if (cls == null) { throw new IllegalArgumentException("You need to supply at least one class."); } - Set accessibleObjects = new HashSet(); + 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()]); + return accessibleObjects.toArray(new AccessibleObject[0]); } private static String[] merge(String first, String... additional) { diff --git a/powermock-api/powermock-api-support/src/main/java/org/powermock/api/support/membermodification/MemberModifier.java b/powermock-api/powermock-api-support/src/main/java/org/powermock/api/support/membermodification/MemberModifier.java index 42c9bc76e..08c252d46 100644 --- a/powermock-api/powermock-api-support/src/main/java/org/powermock/api/support/membermodification/MemberModifier.java +++ b/powermock-api/powermock-api-support/src/main/java/org/powermock/api/support/membermodification/MemberModifier.java @@ -102,7 +102,7 @@ public static void suppress(AccessibleObject[] accessibleObjects) { * the method is stubbed). */ public static MethodStubStrategy stub(Method method) { - return new MethodStubStrategyImpl(method); + return new MethodStubStrategyImpl<>(method); } /** diff --git a/powermock-api/powermock-api-support/src/main/java/org/powermock/api/support/membermodification/strategy/impl/MethodReplaceStrategyImpl.java b/powermock-api/powermock-api-support/src/main/java/org/powermock/api/support/membermodification/strategy/impl/MethodReplaceStrategyImpl.java index 3be60dd0b..57a85b333 100644 --- a/powermock-api/powermock-api-support/src/main/java/org/powermock/api/support/membermodification/strategy/impl/MethodReplaceStrategyImpl.java +++ b/powermock-api/powermock-api-support/src/main/java/org/powermock/api/support/membermodification/strategy/impl/MethodReplaceStrategyImpl.java @@ -44,9 +44,9 @@ public void with(Method 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())); + throw new IllegalArgumentException(String.format("The replacing method (%s) needs to return %s and not %s.", method, 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())); + 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, this.method)); } else { MethodProxy.proxy(this.method, new MethodInvocationHandler(method)); } diff --git a/powermock-api/powermock-api-support/src/main/java/org/powermock/api/support/membermodification/strategy/impl/MethodStubStrategyImpl.java b/powermock-api/powermock-api-support/src/main/java/org/powermock/api/support/membermodification/strategy/impl/MethodStubStrategyImpl.java index 3f413c4b4..77c81e5df 100644 --- a/powermock-api/powermock-api-support/src/main/java/org/powermock/api/support/membermodification/strategy/impl/MethodStubStrategyImpl.java +++ b/powermock-api/powermock-api-support/src/main/java/org/powermock/api/support/membermodification/strategy/impl/MethodStubStrategyImpl.java @@ -24,35 +24,31 @@ 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); - } + 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 = (proxy, method, args) -> { + throw throwable; + }; + MethodProxy.proxy(method, throwingInvocationHandler); + } + + @Override + public void toReturn(T returnValue) { + Stubber.stubMethod(method, returnValue); + } } diff --git a/powermock-classloading/powermock-classloading-objenesis/src/main/java/org/powermock/classloading/DeepCloner.java b/powermock-classloading/powermock-classloading-objenesis/src/main/java/org/powermock/classloading/DeepCloner.java index 63fe26c2f..649c2a435 100644 --- a/powermock-classloading/powermock-classloading-objenesis/src/main/java/org/powermock/classloading/DeepCloner.java +++ b/powermock-classloading/powermock-classloading-objenesis/src/main/java/org/powermock/classloading/DeepCloner.java @@ -21,7 +21,6 @@ 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; @@ -36,6 +35,8 @@ import java.lang.reflect.Modifier; import java.util.Map; +import sun.misc.Unsafe; + /** *

* The purpose of the deep cloner is to create a deep clone of an object. An @@ -45,7 +46,7 @@ public class DeepCloner implements DeepClonerSPI { private final ClassLoader targetCL; - private final Map referenceMap = new ListMap(); + private final Map referenceMap = new ListMap<>(); private final Class doNotClone; /** @@ -354,7 +355,7 @@ public static void write(Field field, Object object, Object value) { } try { final long offset; - if (DeepCloner.isStaticFinalModifier(field)) { + if (isStaticFinalModifier(field)) { offset = unsafe.staticFieldOffset(field); } else { offset = unsafe.objectFieldOffset(field); diff --git a/powermock-classloading/powermock-classloading-objenesis/src/test/java/powermock/classloading/ObjenesisClassloaderExecutorTest.java b/powermock-classloading/powermock-classloading-objenesis/src/test/java/powermock/classloading/ObjenesisClassloaderExecutorTest.java index 82aa0caa8..962d20727 100644 --- a/powermock-classloading/powermock-classloading-objenesis/src/test/java/powermock/classloading/ObjenesisClassloaderExecutorTest.java +++ b/powermock-classloading/powermock-classloading-objenesis/src/test/java/powermock/classloading/ObjenesisClassloaderExecutorTest.java @@ -16,7 +16,6 @@ package powermock.classloading; -import org.junit.Ignore; import org.junit.Test; import org.powermock.classloading.SingleClassloaderExecutor; import org.powermock.core.classloader.MockClassLoader; @@ -24,6 +23,10 @@ import org.powermock.core.transformers.ClassWrapper; import org.powermock.core.transformers.MockTransformer; import org.powermock.core.transformers.support.DefaultMockTransformerChain; + +import java.lang.reflect.Method; +import java.util.concurrent.Callable; + import powermock.classloading.classes.MyArgument; import powermock.classloading.classes.MyClass; import powermock.classloading.classes.MyEnum; @@ -35,25 +38,22 @@ 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.assertNotEquals; 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 { + public void loadsObjectGraphInSpecifiedClassloaderAndReturnsResultInOriginalClassloader() { 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 { + @Override + public MyReturnValue[] call() { assertEquals(JavassistMockClassLoader.class.getName(), this.getClass() .getClassLoader() .getClass() @@ -61,8 +61,8 @@ public MyReturnValue[] call() throws Exception { return myClass.myMethod(expected); } }); - - assertFalse(MockClassLoader.class.getName().equals(this.getClass().getClassLoader().getClass().getName())); + + assertNotEquals(MockClassLoader.class.getName(), this.getClass().getClassLoader().getClass().getName()); final MyReturnValue myReturnValue = actual[0]; assertEquals(expectedConstructorValue.getMyArgument().getValue(), myReturnValue.getMyArgument().getValue()); @@ -70,13 +70,13 @@ public MyReturnValue[] call() throws Exception { } @Test - public void loadsObjectGraphThatIncludesPrimitiveValuesInSpecifiedClassloaderAndReturnsResultInOriginalClassloader() - throws Exception { + public void loadsObjectGraphThatIncludesPrimitiveValuesInSpecifiedClassloaderAndReturnsResultInOriginalClassloader() { 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 { + @Override + public Integer call() { assertEquals(JavassistMockClassLoader.class.getName(), this.getClass() .getClassLoader() .getClass() @@ -86,20 +86,20 @@ public Integer call() throws Exception { return myInteger; } }); - - assertFalse(MockClassLoader.class.getName().equals(this.getClass().getClassLoader().getClass().getName())); + + assertNotEquals(MockClassLoader.class.getName(), this.getClass().getClassLoader().getClass().getName()); assertEquals(expected, actual); } @Test - public void loadsObjectGraphThatIncludesEnumsInSpecifiedClassloaderAndReturnsResultInOriginalClassloader() - throws Exception { + public void loadsObjectGraphThatIncludesEnumsInSpecifiedClassloaderAndReturnsResultInOriginalClassloader() { 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 { + @Override + public MyEnum call() { assertEquals(JavassistMockClassLoader.class.getName(), this.getClass() .getClassLoader() .getClass() @@ -109,20 +109,20 @@ public MyEnum call() throws Exception { return myEnum; } }); - - assertFalse(MockClassLoader.class.getName().equals(this.getClass().getClassLoader().getClass().getName())); + + assertNotEquals(MockClassLoader.class.getName(), this.getClass().getClassLoader().getClass().getName()); assertEquals(expected, actual); } @Test - public void loadsObjectGraphThatIncludesPrimitiveArraysInSpecifiedClassloaderAndReturnsResultInOriginalClassloader() - throws Exception { + public void loadsObjectGraphThatIncludesPrimitiveArraysInSpecifiedClassloaderAndReturnsResultInOriginalClassloader() { 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 { + @Override + public int[] call() { assertEquals(JavassistMockClassLoader.class.getName(), this.getClass() .getClassLoader() .getClass() @@ -132,18 +132,19 @@ public int[] call() throws Exception { return myArray; } }); - - assertFalse(MockClassLoader.class.getName().equals(this.getClass().getClassLoader().getClass().getName())); + + assertNotEquals(MockClassLoader.class.getName(), this.getClass().getClassLoader().getClass().getName()); assertArrayEquals(expected, actual); } @Test - public void usesReferenceCloningWhenTwoFieldsPointToSameInstance() throws Exception { + public void usesReferenceCloningWhenTwoFieldsPointToSameInstance() { 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() { + @Override public void run() { assertEquals(JavassistMockClassLoader.class.getName(), this.getClass() .getClassLoader() @@ -159,12 +160,13 @@ public void run() { } @Test - public void worksWithObjectHierarchy() throws Exception { + public void worksWithObjectHierarchy() { 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() { + @Override public void run() { assertEquals(JavassistMockClassLoader.class.getName(), this.getClass() .getClassLoader() @@ -184,6 +186,7 @@ public void worksWithReflection() throws Exception { Method method = instance.getClass().getMethod("getMyArgument"); final ReflectionMethodInvoker tested = new ReflectionMethodInvoker(method, instance); new SingleClassloaderExecutor(classloader).execute(new Runnable() { + @Override public void run() { Object invoke = tested.invoke(); assertSame(invoke, myArgument); @@ -196,7 +199,7 @@ private MockClassLoader createClassloader() { MyArgument.class.getName(), MyReturnValue.class.getName()}); MockTransformer mainMockTransformer = new MockTransformer() { @Override - public ClassWrapper transform(ClassWrapper clazz) throws Exception { + public ClassWrapper transform(ClassWrapper clazz) { return clazz; } }; diff --git a/powermock-classloading/powermock-classloading-objenesis/src/test/java/powermock/classloading/ObjenesisDeepClonerTest.java b/powermock-classloading/powermock-classloading-objenesis/src/test/java/powermock/classloading/ObjenesisDeepClonerTest.java index 951d38ed2..416dc1633 100644 --- a/powermock-classloading/powermock-classloading-objenesis/src/test/java/powermock/classloading/ObjenesisDeepClonerTest.java +++ b/powermock-classloading/powermock-classloading-objenesis/src/test/java/powermock/classloading/ObjenesisDeepClonerTest.java @@ -16,8 +16,6 @@ package powermock.classloading; -import org.junit.Before; -import org.junit.Ignore; import org.junit.Test; import org.powermock.classloading.DeepCloner; @@ -28,21 +26,9 @@ 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"); @@ -52,7 +38,7 @@ public void clonesJavaInstances() throws Exception { } @Test - public void clonesUnmodifiableLists() throws Exception { + public void clonesUnmodifiableLists() { final UnmodifiableListExample original = new UnmodifiableListExample(); UnmodifiableListExample clone = new DeepCloner().clone(original); assertEquals(clone, original); @@ -60,7 +46,7 @@ public void clonesUnmodifiableLists() throws Exception { } @Test - public void clonesArraysWithNullValues() throws Exception { + public void clonesArraysWithNullValues() { Object[] original = new Object[]{"Test", null}; Object[] clone = new DeepCloner().clone(original); assertArrayEquals(clone, original); @@ -85,11 +71,12 @@ 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; + UnmodifiableListExample other = (UnmodifiableListExample) obj; if (cl == null) { - if (other.cl != null) { return false; } - } else if (!cl.equals(other.cl)) { return false; } - return true; + return other.cl == null; + } else { + return cl.equals(other.cl); + } } } @@ -109,10 +96,11 @@ 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; + NotSerializable other = (NotSerializable) obj; if (state == null) { - if (other.state != null) { return false; } - } else if (!state.equals(other.state)) { return false; } - return true; + return other.state == null; + } else { + return state.equals(other.state); + } } } \ No newline at end of file diff --git a/powermock-classloading/powermock-classloading-objenesis/src/test/java/powermock/classloading/classes/MyArgument.java b/powermock-classloading/powermock-classloading-objenesis/src/test/java/powermock/classloading/classes/MyArgument.java index 29b3e6d42..b56ec9236 100644 --- a/powermock-classloading/powermock-classloading-objenesis/src/test/java/powermock/classloading/classes/MyArgument.java +++ b/powermock-classloading/powermock-classloading-objenesis/src/test/java/powermock/classloading/classes/MyArgument.java @@ -17,43 +17,42 @@ public class MyArgument { - private String value; + private String value; - public MyArgument(String value) { - this.value = value; - } + public MyArgument(String value) { + this.value = value; + } - public String getValue() { - return value; - } + public String getValue() { + return value; + } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((value == null) ? 0 : value.hashCode()); - return result; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((value == null) ? 0 : value.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; - MyArgument other = (MyArgument) obj; - if (value == null) { - if (other.value != null) - return false; - } else if (!value.equals(other.value)) - return false; - return true; - } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + MyArgument other = (MyArgument) obj; + if (value == null) { + return other.value == null; + } else { + return value.equals(other.value); + } + } - @Override - public String toString() { - return "MyArgument [value=" + value + "]"; - } + @Override + public String toString() { + return "MyArgument [value=" + value + "]"; + } } \ No newline at end of file diff --git a/powermock-classloading/powermock-classloading-xstream/src/main/java/org/powermock/classloading/DeepCloner.java b/powermock-classloading/powermock-classloading-xstream/src/main/java/org/powermock/classloading/DeepCloner.java index c4e46836d..db4656fdb 100644 --- a/powermock-classloading/powermock-classloading-xstream/src/main/java/org/powermock/classloading/DeepCloner.java +++ b/powermock-classloading/powermock-classloading-xstream/src/main/java/org/powermock/classloading/DeepCloner.java @@ -15,9 +15,10 @@ */ package org.powermock.classloading; -import com.thoughtworks.xstream.XStream; import org.powermock.classloading.spi.DeepClonerSPI; +import com.thoughtworks.xstream.XStream; + /** *

* The purpose of the deep cloner is to create a deep clone of an object. An @@ -27,39 +28,40 @@ 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) { + /** + * 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"); + disableSecurity(); + xStream.omitField(SingleClassloaderExecutor.class, "classloader"); xStream.setClassLoader(classLoader); - } + } - private void disableSecurity() { - XStream.setupDefaultSecurity(xStream); - xStream.allowTypesByRegExp(new String[]{".*"}); - } + private void disableSecurity() { + XStream.setupDefaultSecurity(xStream); + xStream.allowTypesByRegExp(new String[]{".*"}); + } - /** - * Clone using the current ContextClassLoader. - */ - public DeepCloner() { - this(Thread.currentThread().getContextClassLoader()); - } + /** + * Clone using the current ContextClassLoader. + */ + public DeepCloner() { + this(Thread.currentThread().getContextClassLoader()); + } - /** - * Clones an object. - * + /** + * 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) { + * @return A deep clone of the object to clone. + */ + @Override + @SuppressWarnings("unchecked") + public T clone(T objectToClone) { final String serialized = xStream.toXML(objectToClone); return (T) xStream.fromXML(serialized); } diff --git a/powermock-classloading/powermock-classloading-xstream/src/test/java/powermock/classloading/XStreamClassloaderExecutorTest.java b/powermock-classloading/powermock-classloading-xstream/src/test/java/powermock/classloading/XStreamClassloaderExecutorTest.java index 493c98d25..476d467f7 100644 --- a/powermock-classloading/powermock-classloading-xstream/src/test/java/powermock/classloading/XStreamClassloaderExecutorTest.java +++ b/powermock-classloading/powermock-classloading-xstream/src/test/java/powermock/classloading/XStreamClassloaderExecutorTest.java @@ -23,6 +23,12 @@ import org.powermock.core.transformers.ClassWrapper; import org.powermock.core.transformers.MockTransformer; import org.powermock.core.transformers.support.DefaultMockTransformerChain; + +import java.lang.reflect.Method; +import java.util.Collection; +import java.util.LinkedList; +import java.util.concurrent.Callable; + import powermock.classloading.classes.MyArgument; import powermock.classloading.classes.MyClass; import powermock.classloading.classes.MyCollectionHolder; @@ -39,11 +45,6 @@ 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; @@ -60,6 +61,7 @@ public void loadsObjectGraphInSpecifiedClassloaderAndReturnsResultInOriginalClas final MyClass myClass = new MyClass(expectedConstructorValue); final MyArgument expected = new MyArgument("A value"); MyReturnValue[] actual = new SingleClassloaderExecutor(classloader).execute(new Callable() { + @Override public MyReturnValue[] call() throws Exception { assertEquals(JavassistMockClassLoader.class.getName(), this.getClass().getClassLoader().getClass().getName()); return myClass.myMethod(expected); @@ -80,6 +82,7 @@ public void loadsObjectGraphThatIncludesPrimitiveValuesInSpecifiedClassloaderAnd final Integer expected = 42; final MyIntegerHolder myClass = new MyIntegerHolder(expected); Integer actual = new SingleClassloaderExecutor(classloader).execute(new Callable() { + @Override public Integer call() throws Exception { assertEquals(JavassistMockClassLoader.class.getName(), this.getClass().getClassLoader().getClass().getName()); final int myInteger = myClass.getMyInteger(); @@ -100,6 +103,7 @@ public void loadsObjectGraphThatIncludesEnumsInSpecifiedClassloaderAndReturnsRes final MyEnum expected = MyEnum.MyEnum1; final MyEnumHolder myClass = new MyEnumHolder(expected); MyEnum actual = new SingleClassloaderExecutor(classloader).execute(new Callable() { + @Override public MyEnum call() throws Exception { assertEquals(JavassistMockClassLoader.class.getName(), this.getClass().getClassLoader().getClass().getName()); MyEnum myEnum = myClass.getMyEnum(); @@ -118,6 +122,7 @@ public void clonesStaticFinalObjectFields() throws Exception { final MyStaticFinalArgumentHolder expected = new MyStaticFinalArgumentHolder(); MyStaticFinalArgumentHolder actual = new SingleClassloaderExecutor(classloader) .execute(new Callable() { + @Override public MyStaticFinalArgumentHolder call() throws Exception { assertEquals(JavassistMockClassLoader.class.getName(), this.getClass().getClassLoader().getClass() .getName()); @@ -137,6 +142,7 @@ public void clonesStaticFinalPrimitiveFields() throws Exception { final MyStaticFinalPrimitiveHolder expected = new MyStaticFinalPrimitiveHolder(); MyStaticFinalPrimitiveHolder actual = new SingleClassloaderExecutor(classloader) .execute(new Callable() { + @Override public MyStaticFinalPrimitiveHolder call() throws Exception { assertEquals(JavassistMockClassLoader.class.getName(), this.getClass().getClassLoader().getClass() .getName()); @@ -156,6 +162,7 @@ public void clonesStaticFinalNumberFields() throws Exception { final MyStaticFinalNumberHolder expected = new MyStaticFinalNumberHolder(); MyStaticFinalNumberHolder actual = new SingleClassloaderExecutor(classloader) .execute(new Callable() { + @Override public MyStaticFinalNumberHolder call() throws Exception { assertEquals(JavassistMockClassLoader.class.getName(), this.getClass().getClassLoader().getClass() .getName()); @@ -176,6 +183,7 @@ public void loadsObjectGraphThatIncludesPrimitiveArraysInSpecifiedClassloaderAnd final int[] expected = new int[] { 1, 2 }; final MyPrimitiveArrayHolder myClass = new MyPrimitiveArrayHolder(expected); int[] actual = new SingleClassloaderExecutor(classloader).execute(new Callable() { + @Override public int[] call() throws Exception { assertEquals(JavassistMockClassLoader.class.getName(), this.getClass().getClassLoader().getClass().getName()); int[] myArray = myClass.getMyArray(); @@ -192,11 +200,12 @@ public int[] call() throws Exception { public void loadsObjectGraphThatIncludesCollectionInSpecifiedClassloaderAndReturnsResultInOriginalClassloader() throws Exception { final MockClassLoader classloader = createClassloader(); - final Collection expected = new LinkedList(); + 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>() { + @Override public Collection call() throws Exception { assertEquals(JavassistMockClassLoader.class.getName(), this.getClass().getClassLoader().getClass().getName()); Collection myCollection = myClass.getMyCollection(); @@ -223,6 +232,7 @@ public void usesReferenceCloningWhenTwoFieldsPointToSameInstance() throws Except assertSame(tested.getMyArgument1(), tested.getMyArgument2()); assertSame(tested.getMyArgument1(), MyReferenceFieldHolder.MY_ARGUMENT); new SingleClassloaderExecutor(classloader).execute(new Runnable() { + @Override public void run() { assertEquals(JavassistMockClassLoader.class.getName(), this.getClass().getClassLoader().getClass().getName()); assertEquals(tested.getMyArgument1(), tested.getMyArgument2()); @@ -241,6 +251,7 @@ public void worksWithObjectHierarchy() throws Exception { assertSame(tested.getMyArgument1(), tested.getMyArgument2()); assertEquals(tested.getMyArgument3(), tested.getMyArgument2()); new SingleClassloaderExecutor(classloader).execute(new Runnable() { + @Override public void run() { assertEquals(JavassistMockClassLoader.class.getName(), this.getClass().getClassLoader().getClass().getName()); assertSame(tested.getMyArgument1(), tested.getMyArgument2()); @@ -259,6 +270,7 @@ public void worksWithObjectHierarchyAndOverloadedFields() throws Exception { assertNotSame(MyReferenceFieldHolder.MY_ARGUMENT, MyHierarchicalOverloadedFieldHolder.MY_ARGUMENT); assertEquals(MyReferenceFieldHolder.MY_ARGUMENT, MyHierarchicalOverloadedFieldHolder.MY_ARGUMENT); new SingleClassloaderExecutor(classloader).execute(new Runnable() { + @Override public void run() { assertEquals(JavassistMockClassLoader.class.getName(), this.getClass().getClassLoader().getClass().getName()); assertSame(tested.getMyArgument1(), tested.getMyArgument2()); @@ -279,6 +291,7 @@ public void worksWithReflection() throws Exception { Method method = instance.getClass().getMethod("getMyArgument"); final ReflectionMethodInvoker tested = new ReflectionMethodInvoker(method, instance); new SingleClassloaderExecutor(classloader).execute(new Runnable() { + @Override public void run() { Object invoke = tested.invoke(); assertSame(invoke, myArgument); diff --git a/powermock-classloading/powermock-classloading-xstream/src/test/java/powermock/classloading/XStreamDeepClonerTest.java b/powermock-classloading/powermock-classloading-xstream/src/test/java/powermock/classloading/XStreamDeepClonerTest.java index bc93ef97f..7ecebf61e 100644 --- a/powermock-classloading/powermock-classloading-xstream/src/test/java/powermock/classloading/XStreamDeepClonerTest.java +++ b/powermock-classloading/powermock-classloading-xstream/src/test/java/powermock/classloading/XStreamDeepClonerTest.java @@ -74,13 +74,12 @@ public boolean equals(Object obj) { return false; if (getClass() != obj.getClass()) return false; - powermock.classloading.UnmodifiableListExample other = (powermock.classloading.UnmodifiableListExample) obj; + UnmodifiableListExample other = (UnmodifiableListExample) obj; if (cl == null) { - if (other.cl != null) - return false; - } else if (!cl.equals(other.cl)) - return false; - return true; + return other.cl == null; + } else { + return cl.equals(other.cl); + } } } @@ -103,12 +102,11 @@ public boolean equals(Object obj) { return false; if (getClass() != obj.getClass()) return false; - powermock.classloading.NotSerializable other = (powermock.classloading.NotSerializable) obj; + NotSerializable other = (NotSerializable) obj; if (state == null) { - if (other.state != null) - return false; - } else if (!state.equals(other.state)) - return false; - return true; + return other.state == null; + } else { + return state.equals(other.state); + } } } \ No newline at end of file diff --git a/powermock-classloading/powermock-classloading-xstream/src/test/java/powermock/classloading/classes/MyArgument.java b/powermock-classloading/powermock-classloading-xstream/src/test/java/powermock/classloading/classes/MyArgument.java index 29b3e6d42..b56ec9236 100644 --- a/powermock-classloading/powermock-classloading-xstream/src/test/java/powermock/classloading/classes/MyArgument.java +++ b/powermock-classloading/powermock-classloading-xstream/src/test/java/powermock/classloading/classes/MyArgument.java @@ -17,43 +17,42 @@ public class MyArgument { - private String value; + private String value; - public MyArgument(String value) { - this.value = value; - } + public MyArgument(String value) { + this.value = value; + } - public String getValue() { - return value; - } + public String getValue() { + return value; + } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((value == null) ? 0 : value.hashCode()); - return result; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((value == null) ? 0 : value.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; - MyArgument other = (MyArgument) obj; - if (value == null) { - if (other.value != null) - return false; - } else if (!value.equals(other.value)) - return false; - return true; - } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + MyArgument other = (MyArgument) obj; + if (value == null) { + return other.value == null; + } else { + return value.equals(other.value); + } + } - @Override - public String toString() { - return "MyArgument [value=" + value + "]"; - } + @Override + public String toString() { + return "MyArgument [value=" + value + "]"; + } } \ No newline at end of file diff --git a/powermock-core/src/main/java/org/powermock/configuration/ConfigurationType.java b/powermock-core/src/main/java/org/powermock/configuration/ConfigurationType.java index a88ae8f55..88ea1c7ac 100644 --- a/powermock-core/src/main/java/org/powermock/configuration/ConfigurationType.java +++ b/powermock-core/src/main/java/org/powermock/configuration/ConfigurationType.java @@ -36,7 +36,7 @@ public String getPrefix() { } public static ConfigurationType forClass(final Class configurationClass) { - for (ConfigurationType configurationType : ConfigurationType.values()) { + for (ConfigurationType configurationType : values()) { if (configurationType.configurationClass.isAssignableFrom(configurationClass)){ return configurationType; } diff --git a/powermock-core/src/main/java/org/powermock/configuration/GlobalConfiguration.java b/powermock-core/src/main/java/org/powermock/configuration/GlobalConfiguration.java index 8261b855e..407c6f8a1 100644 --- a/powermock-core/src/main/java/org/powermock/configuration/GlobalConfiguration.java +++ b/powermock-core/src/main/java/org/powermock/configuration/GlobalConfiguration.java @@ -33,8 +33,8 @@ 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(); + 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(); diff --git a/powermock-core/src/main/java/org/powermock/configuration/support/ConfigurationBuilder.java b/powermock-core/src/main/java/org/powermock/configuration/support/ConfigurationBuilder.java index 38f87e5a0..ccf0f91d0 100644 --- a/powermock-core/src/main/java/org/powermock/configuration/support/ConfigurationBuilder.java +++ b/powermock-core/src/main/java/org/powermock/configuration/support/ConfigurationBuilder.java @@ -28,7 +28,7 @@ class ConfigurationBuilder> { static > ConfigurationBuilder createConfigurationFor(final Class configurationType) { - return new ConfigurationBuilder(configurationType); + return new ConfigurationBuilder<>(configurationType); } private final Map alias; @@ -36,7 +36,7 @@ static > ConfigurationBuilder createConfigurationF private ConfigurationBuilder(final Class configurationType) { this.configurationType = configurationType; - alias = new HashMap(); + alias = new HashMap<>(); } ConfigurationBuilder withValueAlias(final String alias, final String value) { @@ -77,7 +77,7 @@ public T create(Class configurationClass, final Pro private void mapConfiguration(final Class configurationClass, final T configuration, final Properties properties) { - new ConfigurationMapper(configurationClass, configuration, alias).map(properties); + new ConfigurationMapper<>(configurationClass, configuration, alias).map(properties); } } } diff --git a/powermock-core/src/main/java/org/powermock/configuration/support/ConfigurationMapper.java b/powermock-core/src/main/java/org/powermock/configuration/support/ConfigurationMapper.java index f3dfcb27f..2818fb64e 100644 --- a/powermock-core/src/main/java/org/powermock/configuration/support/ConfigurationMapper.java +++ b/powermock-core/src/main/java/org/powermock/configuration/support/ConfigurationMapper.java @@ -18,9 +18,9 @@ package org.powermock.configuration.support; +import org.powermock.PowerMockInternalException; import org.powermock.configuration.Configuration; import org.powermock.configuration.ConfigurationType; -import org.powermock.PowerMockInternalException; import java.beans.BeanInfo; import java.beans.Introspector; diff --git a/powermock-core/src/main/java/org/powermock/configuration/support/PropertiesFinder.java b/powermock-core/src/main/java/org/powermock/configuration/support/PropertiesFinder.java index 8905cd8e4..77cac0344 100644 --- a/powermock-core/src/main/java/org/powermock/configuration/support/PropertiesFinder.java +++ b/powermock-core/src/main/java/org/powermock/configuration/support/PropertiesFinder.java @@ -19,7 +19,7 @@ class PropertiesFinder { List find(final String configurationFile) throws IOException, URISyntaxException { - final List configurations = new ArrayList(); + final List configurations = new ArrayList<>(); Enumeration resources = classLoader.getResources(configurationFile); diff --git a/powermock-core/src/main/java/org/powermock/core/ClassReplicaCreator.java b/powermock-core/src/main/java/org/powermock/core/ClassReplicaCreator.java index 525872155..d28448ff1 100644 --- a/powermock-core/src/main/java/org/powermock/core/ClassReplicaCreator.java +++ b/powermock-core/src/main/java/org/powermock/core/ClassReplicaCreator.java @@ -15,6 +15,11 @@ */ package org.powermock.core; +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; + import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; @@ -26,11 +31,6 @@ 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 @@ -130,7 +130,7 @@ private String generateReplicaClassName(final Class clazz) { private void copyFields(CtClass originalClassAsCtClass, final CtClass newClass) throws CannotCompileException, NotFoundException { CtField[] declaredFields = originalClassAsCtClass.getDeclaredFields(); CtField[] undeclaredFields = originalClassAsCtClass.getFields(); - Set allFields = new HashSet(); + Set allFields = new HashSet<>(); Collections.addAll(allFields, declaredFields); Collections.addAll(allFields, undeclaredFields); diff --git a/powermock-core/src/main/java/org/powermock/core/ConcreteClassGenerator.java b/powermock-core/src/main/java/org/powermock/core/ConcreteClassGenerator.java index 94cdfa162..00f9b0803 100644 --- a/powermock-core/src/main/java/org/powermock/core/ConcreteClassGenerator.java +++ b/powermock-core/src/main/java/org/powermock/core/ConcreteClassGenerator.java @@ -15,6 +15,10 @@ */ package org.powermock.core; +import org.powermock.reflect.internal.TypeUtils; + +import java.util.concurrent.atomic.AtomicInteger; + import javassist.ClassPool; import javassist.CtClass; import javassist.CtConstructor; @@ -22,9 +26,6 @@ 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 diff --git a/powermock-core/src/main/java/org/powermock/core/IdentityHashSet.java b/powermock-core/src/main/java/org/powermock/core/IdentityHashSet.java index 1610d3575..ed29e18e0 100644 --- a/powermock-core/src/main/java/org/powermock/core/IdentityHashSet.java +++ b/powermock-core/src/main/java/org/powermock/core/IdentityHashSet.java @@ -24,7 +24,7 @@ public class IdentityHashSet extends AbstractSet { protected final Map backedMap; public IdentityHashSet() { - this.backedMap = new ListMap(); + this.backedMap = new ListMap<>(); } @Override diff --git a/powermock-core/src/main/java/org/powermock/core/ListMap.java b/powermock-core/src/main/java/org/powermock/core/ListMap.java index 1bfca5692..c508a53ff 100644 --- a/powermock-core/src/main/java/org/powermock/core/ListMap.java +++ b/powermock-core/src/main/java/org/powermock/core/ListMap.java @@ -25,7 +25,7 @@ public class ListMap implements Map { - private List> entries = new LinkedList>(); + private List> entries = new LinkedList<>(); private static class SimpleEntry implements Entry { @@ -90,7 +90,7 @@ public V put(K key, V value) { return entry.setValue(value); } } - Map.Entry entry = new SimpleEntry(key, value); + Map.Entry entry = new SimpleEntry<>(key, value); entries.add(entry); return null; } @@ -111,7 +111,7 @@ public boolean containsValue(Object value) { } @Override - public Set> entrySet() { + public Set> entrySet() { throw new UnsupportedOperationException(); } @@ -122,7 +122,7 @@ public boolean isEmpty() { @Override public Set keySet() { - Set identityHashSet = new HashSet(); + Set identityHashSet = new HashSet<>(); for (Map.Entry entry : entries) { identityHashSet.add(entry.getKey()); } @@ -134,7 +134,7 @@ public Set keySet() { public void putAll(Map t) { Set entrySet = t.entrySet(); for (Object object : entrySet) { - entries.add((java.util.Map.Entry) object); + entries.add((Map.Entry) object); } } @@ -145,7 +145,7 @@ public int size() { @Override public Collection values() { - Set hashSet = new HashSet(); + Set hashSet = new HashSet<>(); for (Map.Entry entry : entries) { hashSet.add(entry.getValue()); } diff --git a/powermock-core/src/main/java/org/powermock/core/MockGateway.java b/powermock-core/src/main/java/org/powermock/core/MockGateway.java index 2c071b671..cc3b11ec9 100644 --- a/powermock-core/src/main/java/org/powermock/core/MockGateway.java +++ b/powermock-core/src/main/java/org/powermock/core/MockGateway.java @@ -120,14 +120,14 @@ public static boolean suppressConstructorCall(Class type, Object[] args, Clas /** * Tells PowerMock whether or not to mock - * {@link java.lang.Object#getClass()}. + * {@link 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)}. + * {@link Class#isAnnotationPresent(Class)} and + * {@link Class#getAnnotation(Class)}. */ public static boolean MOCK_ANNOTATION_METHODS = false; diff --git a/powermock-core/src/main/java/org/powermock/core/MockRepository.java b/powermock-core/src/main/java/org/powermock/core/MockRepository.java index 9b10451bb..49b50b136 100644 --- a/powermock-core/src/main/java/org/powermock/core/MockRepository.java +++ b/powermock-core/src/main/java/org/powermock/core/MockRepository.java @@ -35,68 +35,68 @@ */ public class MockRepository { - private static Set objectsToAutomaticallyReplayAndVerify = new IdentityHashSet(); + private static Set objectsToAutomaticallyReplayAndVerify = new IdentityHashSet<>(); - private static Map, NewInvocationControl> newSubstitutions = new HashMap, NewInvocationControl>(); + private static Map, NewInvocationControl> newSubstitutions = new HashMap<>(); /** * Holds info about general method invocation mocks for classes. */ - private static Map, MethodInvocationControl> classMocks = new HashMap, MethodInvocationControl>(); + private static Map, MethodInvocationControl> classMocks = new HashMap<>(); /** * Holds info about general method invocation mocks for instances. */ - private static Map instanceMocks = new ListMap(); + 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(); + private static Map substituteReturnValues = new HashMap<>(); /** * Holds info about which methods that are proxied. */ - private static Map methodProxies = new HashMap(); + private static Map methodProxies = new HashMap<>(); /** * Holds info about which class that should have their static initializers * suppressed. */ - private static Set suppressStaticInitializers = new HashSet(); + 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(); + private static Map additionalState = new HashMap<>(); /** * Set of constructors that should be suppressed. */ - private static final Set> suppressConstructor = new HashSet>(); + private static final Set> suppressConstructor = new HashSet<>(); /** * Set of methods that should be suppressed. */ - private static final Set suppressMethod = new HashSet(); + private static final Set suppressMethod = new HashSet<>(); /** * Set of methods that should be suppressed. */ - private static final Set suppressField = new HashSet(); + 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(); + 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(); + private static final Set afterMethodRunners = new HashSet<>(); /** * Clear all state of the mock repository except for static initializers. diff --git a/powermock-core/src/main/java/org/powermock/core/PowerMockUtils.java b/powermock-core/src/main/java/org/powermock/core/PowerMockUtils.java index a9e8a6985..b2d87e533 100644 --- a/powermock-core/src/main/java/org/powermock/core/PowerMockUtils.java +++ b/powermock-core/src/main/java/org/powermock/core/PowerMockUtils.java @@ -51,7 +51,7 @@ public static void printClassesLoadedByClassloader(ClassLoader classLoader, bool IllegalAccessException { while (classLoader != null) { System.out.println("ClassLoader: " + classLoader); - for (Iterator iter = PowerMockUtils.getClassIterator(classLoader); iter.hasNext();) { + for (Iterator iter = getClassIterator(classLoader); iter.hasNext();) { System.out.println("\t" + iter.next()); } if (includeParent) { diff --git a/powermock-core/src/main/java/org/powermock/core/bytebuddy/Frame.java b/powermock-core/src/main/java/org/powermock/core/bytebuddy/Frame.java index 8ada26250..2efa6d523 100644 --- a/powermock-core/src/main/java/org/powermock/core/bytebuddy/Frame.java +++ b/powermock-core/src/main/java/org/powermock/core/bytebuddy/Frame.java @@ -18,6 +18,11 @@ package org.powermock.core.bytebuddy; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Deque; +import java.util.LinkedList; +import java.util.List; import net.bytebuddy.description.method.ParameterDescription; import net.bytebuddy.description.method.ParameterDescription.InDefinedShape; @@ -27,16 +32,10 @@ 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(); + List locals = new ArrayList<>(); locals.add(LocalVariable.UNINITIALIZED_THIS); @@ -56,11 +55,11 @@ public static Frame beforeConstructorCall(final Iterable locals) { this.locals = Collections.unmodifiableList(locals); - this.stack = new LinkedList(); + this.stack = new LinkedList<>(); } public Frame addTopToLocals(final int count) { - List locals = new ArrayList(); + List locals = new ArrayList<>(); for (int i = 0; i < count; i++) { locals.add(LocalVariable.TOP); } @@ -78,7 +77,7 @@ public Frame addLocalVariable(final LocalVariable localVariable) { public Frame addLocalVariables(final ParameterList types) { - List frameLocals = new ArrayList(); + List frameLocals = new ArrayList<>(); for (ParameterDescription parameter : types) { Generic type = parameter.getType(); diff --git a/powermock-core/src/main/java/org/powermock/core/bytebuddy/MethodMaxLocals.java b/powermock-core/src/main/java/org/powermock/core/bytebuddy/MethodMaxLocals.java index 47c95896f..cc398a5f1 100644 --- a/powermock-core/src/main/java/org/powermock/core/bytebuddy/MethodMaxLocals.java +++ b/powermock-core/src/main/java/org/powermock/core/bytebuddy/MethodMaxLocals.java @@ -18,18 +18,18 @@ package org.powermock.core.bytebuddy; -import net.bytebuddy.description.method.MethodDescription; - import java.util.HashMap; import java.util.Map; +import net.bytebuddy.description.method.MethodDescription; + public class MethodMaxLocals { private final Map methodMaxLocals; MethodMaxLocals() { - methodMaxLocals = new HashMap(); + methodMaxLocals = new HashMap<>(); } public void add(String name, String signature, int maxLocals) { diff --git a/powermock-core/src/main/java/org/powermock/core/bytebuddy/MockGetawayCall.java b/powermock-core/src/main/java/org/powermock/core/bytebuddy/MockGetawayCall.java index db84196c8..96b3ae385 100644 --- a/powermock-core/src/main/java/org/powermock/core/bytebuddy/MockGetawayCall.java +++ b/powermock-core/src/main/java/org/powermock/core/bytebuddy/MockGetawayCall.java @@ -18,6 +18,13 @@ package org.powermock.core.bytebuddy; +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; + import net.bytebuddy.description.method.MethodDescription.ForLoadedMethod; import net.bytebuddy.description.method.ParameterDescription.InDefinedShape; import net.bytebuddy.description.method.ParameterList; @@ -28,13 +35,6 @@ 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 { @@ -104,7 +104,7 @@ private ConstructorMockGetawayCall(final Method getawayMethod, } private List loadSignatureParametersClasess() { - List constructorSignature = new ArrayList(); + List constructorSignature = new ArrayList<>(); for (InDefinedShape targetParameter : targetParameters) { constructorSignature.add( @@ -115,7 +115,7 @@ private List loadSignatureParametersClasess() { } private List loadArgumentsFromVariable() { - List loadTargetParameters = new ArrayList(); + List loadTargetParameters = new ArrayList<>(); for (Variable argument : arguments) { loadTargetParameters.add( VariableAccess.load(argument, true) diff --git a/powermock-core/src/main/java/org/powermock/core/classloader/DeferSupportingClassLoader.java b/powermock-core/src/main/java/org/powermock/core/classloader/DeferSupportingClassLoader.java index b88793624..50097d7ee 100644 --- a/powermock-core/src/main/java/org/powermock/core/classloader/DeferSupportingClassLoader.java +++ b/powermock-core/src/main/java/org/powermock/core/classloader/DeferSupportingClassLoader.java @@ -44,14 +44,14 @@ abstract class DeferSupportingClassLoader extends ClassLoader { DeferSupportingClassLoader(ClassLoader classloader, MockClassLoaderConfiguration configuration) { this.configuration = configuration; - this.classes = new ConcurrentHashMap>>(); + this.classes = new ConcurrentHashMap<>(); if (classloader == null) { deferTo = ClassLoader.getSystemClassLoader(); } else { deferTo = classloader; } - parallelLockMap = new ConcurrentHashMap(); + parallelLockMap = new ConcurrentHashMap<>(); } @Override @@ -84,7 +84,7 @@ public MockClassLoaderConfiguration getConfiguration() { */ public void cache(Class cls) { if (cls != null) { - classes.put(cls.getName(), new SoftReference>(cls)); + classes.put(cls.getName(), new SoftReference<>(cls)); } } @@ -101,6 +101,7 @@ protected Class loadClass(String name, boolean resolve) throws ClassNotFoundE } } + @Override protected Object getClassLoadingLock(String className) { Object lock = this; if (parallelLockMap != null) { @@ -149,7 +150,7 @@ private Class loadClass1(String name, boolean resolve) throws ClassNotFoundEx if (resolve) { resolveClass(clazz); } - classes.put(name, new SoftReference>(clazz)); + classes.put(name, new SoftReference<>(clazz)); return clazz; } diff --git a/powermock-core/src/main/java/org/powermock/core/classloader/MockClassLoaderBuilder.java b/powermock-core/src/main/java/org/powermock/core/classloader/MockClassLoaderBuilder.java index aff2ed386..2c88a5a05 100644 --- a/powermock-core/src/main/java/org/powermock/core/classloader/MockClassLoaderBuilder.java +++ b/powermock-core/src/main/java/org/powermock/core/classloader/MockClassLoaderBuilder.java @@ -48,7 +48,7 @@ public static MockClassLoaderBuilder create(ByteCodeFramework byteCodeFramework) private MockClassLoaderBuilder(final ByteCodeFramework byteCodeFramework) { this.byteCodeFramework = byteCodeFramework; transformerChainFactory = byteCodeFramework.createTransformerChainFactory(); - extraMockTransformers = new ArrayList(); + extraMockTransformers = new ArrayList<>(); } public MockClassLoader build() { diff --git a/powermock-core/src/main/java/org/powermock/core/classloader/MockClassLoaderConfiguration.java b/powermock-core/src/main/java/org/powermock/core/classloader/MockClassLoaderConfiguration.java index e2a739102..38e9d5b8a 100644 --- a/powermock-core/src/main/java/org/powermock/core/classloader/MockClassLoaderConfiguration.java +++ b/powermock-core/src/main/java/org/powermock/core/classloader/MockClassLoaderConfiguration.java @@ -75,7 +75,7 @@ public class MockClassLoaderConfiguration { ClassReplicaCreator.class.getName() }; - private final Set modify = Collections.synchronizedSet(new HashSet()); + private final Set modify = Collections.synchronizedSet(new HashSet<>()); private String[] deferPackages; /** diff --git a/powermock-core/src/main/java/org/powermock/core/classloader/MockClassLoaderFactory.java b/powermock-core/src/main/java/org/powermock/core/classloader/MockClassLoaderFactory.java index 8e38d23ff..eb44a85d1 100644 --- a/powermock-core/src/main/java/org/powermock/core/classloader/MockClassLoaderFactory.java +++ b/powermock-core/src/main/java/org/powermock/core/classloader/MockClassLoaderFactory.java @@ -119,13 +119,10 @@ private ClassLoader createMockClassLoader(final ByteCodeFramework byteCodeFramew 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); - } - }); + return AccessController.doPrivileged((PrivilegedAction) () -> { + final UseClassPathAdjuster useClassPathAdjuster = testClass.getAnnotation(UseClassPathAdjuster.class); + return MockClassLoaderFactory.this.createMockClassLoader(byteCodeFramework, classesToLoadByMockClassloader, useClassPathAdjuster, extraMockTransformer); + }); } private MockClassLoader createMockClassLoader(final ByteCodeFramework byteCodeFramework, @@ -154,7 +151,7 @@ private String[] makeSureArrayContainsTestClassName(String[] arrayOfClassNames, return new String[]{testClassName}; } else { - List modifiedArrayOfClassNames = new ArrayList(arrayOfClassNames.length + 1); + List modifiedArrayOfClassNames = new ArrayList<>(arrayOfClassNames.length + 1); modifiedArrayOfClassNames.add(testClassName); for (String className : arrayOfClassNames) { if (testClassName.equals(className)) { diff --git a/powermock-core/src/main/java/org/powermock/core/classloader/javassist/ClassPathAdjuster.java b/powermock-core/src/main/java/org/powermock/core/classloader/javassist/ClassPathAdjuster.java index 6435a56b9..33b22e943 100644 --- a/powermock-core/src/main/java/org/powermock/core/classloader/javassist/ClassPathAdjuster.java +++ b/powermock-core/src/main/java/org/powermock/core/classloader/javassist/ClassPathAdjuster.java @@ -16,9 +16,10 @@ package org.powermock.core.classloader.javassist; -import javassist.ClassPool; import org.powermock.core.classloader.annotations.UseClassPathAdjuster; +import javassist.ClassPool; + /** * This interface can be used to adjust the classpath used by powermock to locate * class files. Use the @{@link UseClassPathAdjuster} to activate. diff --git a/powermock-core/src/main/java/org/powermock/core/classloader/javassist/ClassPoolFactory.java b/powermock-core/src/main/java/org/powermock/core/classloader/javassist/ClassPoolFactory.java index 0f08f32a6..078b6d49f 100644 --- a/powermock-core/src/main/java/org/powermock/core/classloader/javassist/ClassPoolFactory.java +++ b/powermock-core/src/main/java/org/powermock/core/classloader/javassist/ClassPoolFactory.java @@ -18,9 +18,10 @@ package org.powermock.core.classloader.javassist; +import org.powermock.core.classloader.annotations.UseClassPathAdjuster; + import javassist.ClassClassPath; import javassist.ClassPool; -import org.powermock.core.classloader.annotations.UseClassPathAdjuster; class ClassPoolFactory { private UseClassPathAdjuster useClassPathAdjuster; diff --git a/powermock-core/src/main/java/org/powermock/core/classloader/javassist/JavaAssistClassMarkerFactory.java b/powermock-core/src/main/java/org/powermock/core/classloader/javassist/JavaAssistClassMarkerFactory.java index ae3322c55..d962c2425 100644 --- a/powermock-core/src/main/java/org/powermock/core/classloader/javassist/JavaAssistClassMarkerFactory.java +++ b/powermock-core/src/main/java/org/powermock/core/classloader/javassist/JavaAssistClassMarkerFactory.java @@ -17,12 +17,13 @@ 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; +import javassist.ClassPool; +import javassist.CtClass; + class JavaAssistClassMarkerFactory { static ClassMarker createClassMarker(ClassPool classPool) { diff --git a/powermock-core/src/main/java/org/powermock/core/classloader/javassist/JavassistMockClassLoader.java b/powermock-core/src/main/java/org/powermock/core/classloader/javassist/JavassistMockClassLoader.java index 4ac2bd18d..e9ad718eb 100644 --- a/powermock-core/src/main/java/org/powermock/core/classloader/javassist/JavassistMockClassLoader.java +++ b/powermock-core/src/main/java/org/powermock/core/classloader/javassist/JavassistMockClassLoader.java @@ -18,9 +18,6 @@ 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; @@ -29,6 +26,10 @@ import java.security.ProtectionDomain; +import javassist.ClassPool; +import javassist.CtClass; +import javassist.NotFoundException; + public class JavassistMockClassLoader extends MockClassLoader { public static final String CGLIB_ENHANCER = "net.sf.cglib.proxy.Enhancer$EnhancerKey$$KeyFactoryByCGLIB$$"; @@ -60,7 +61,7 @@ public JavassistMockClassLoader(MockClassLoaderConfiguration configuration, @Override protected Class loadUnmockedClass(String name, ProtectionDomain protectionDomain) throws ClassFormatError, ClassNotFoundException { - byte bytes[] = null; + byte[] bytes = null; try { /* * TODO This if-statement is a VERY ugly hack to avoid the @@ -90,6 +91,7 @@ protected Class loadUnmockedClass(String name, ProtectionDomain protectionDom return bytes == null ? null : defineClass(name, bytes, 0, bytes.length, protectionDomain); } + @Override protected byte[] defineAndTransformClass(String name, ProtectionDomain protectionDomain) { final byte[] clazz; diff --git a/powermock-core/src/main/java/org/powermock/core/testlisteners/GlobalNotificationBuildSupport.java b/powermock-core/src/main/java/org/powermock/core/testlisteners/GlobalNotificationBuildSupport.java index c3e1be6d1..272bb4a0c 100644 --- a/powermock-core/src/main/java/org/powermock/core/testlisteners/GlobalNotificationBuildSupport.java +++ b/powermock-core/src/main/java/org/powermock/core/testlisteners/GlobalNotificationBuildSupport.java @@ -15,6 +15,7 @@ */ package org.powermock.core.testlisteners; +import java.util.Collections; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -31,14 +32,11 @@ public interface Callback { void testInstanceCreated(Object testInstance); } - private static final Map testSuiteCallbacks = - new ConcurrentHashMap(); + private static final Map testSuiteCallbacks = new ConcurrentHashMap<>(); - private static final Map, Callback> initiatedTestSuiteClasses = - new ConcurrentHashMap, Callback>(); + private static final Map, Callback> initiatedTestSuiteClasses = new ConcurrentHashMap<>(); - private static final ThreadLocal> pendingInitiatedTestClass = - new ThreadLocal>(); + private static final ThreadLocal> pendingInitiatedTestClass = new ThreadLocal<>(); public static void prepareTestSuite( String testClassName, Callback callback) { @@ -105,6 +103,6 @@ public static void closeTestSuite(Class testClass) { public static void closePendingTestSuites(Callback callback) { testSuiteCallbacks.values().remove(callback); initiatedTestSuiteClasses.values() - .removeAll(java.util.Collections.singleton(callback)); + .removeAll(Collections.singleton(callback)); } } diff --git a/powermock-core/src/main/java/org/powermock/core/transformers/MethodSignatures.java b/powermock-core/src/main/java/org/powermock/core/transformers/MethodSignatures.java index bf2172ebc..89941a37e 100644 --- a/powermock-core/src/main/java/org/powermock/core/transformers/MethodSignatures.java +++ b/powermock-core/src/main/java/org/powermock/core/transformers/MethodSignatures.java @@ -1,12 +1,13 @@ package org.powermock.core.transformers; +import org.powermock.PowerMockInternalException; + +import java.lang.reflect.Method; + 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 { diff --git a/powermock-core/src/main/java/org/powermock/core/transformers/TestClassTransformerBuilder.java b/powermock-core/src/main/java/org/powermock/core/transformers/TestClassTransformerBuilder.java index 49ba22c8f..781e2b650 100644 --- a/powermock-core/src/main/java/org/powermock/core/transformers/TestClassTransformerBuilder.java +++ b/powermock-core/src/main/java/org/powermock/core/transformers/TestClassTransformerBuilder.java @@ -1,6 +1,5 @@ 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; @@ -9,6 +8,8 @@ import java.lang.reflect.Method; import java.util.Collection; +import javassist.CtMethod; + public class TestClassTransformerBuilder { public static TestClassTransformerBuilder forTestClass(final Class testClass) { diff --git a/powermock-core/src/main/java/org/powermock/core/transformers/javassist/AbstractJavaAssistMockTransformer.java b/powermock-core/src/main/java/org/powermock/core/transformers/javassist/AbstractJavaAssistMockTransformer.java index 975422a74..9e08b0899 100644 --- a/powermock-core/src/main/java/org/powermock/core/transformers/javassist/AbstractJavaAssistMockTransformer.java +++ b/powermock-core/src/main/java/org/powermock/core/transformers/javassist/AbstractJavaAssistMockTransformer.java @@ -18,11 +18,12 @@ 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; +import javassist.CtClass; + public abstract class AbstractJavaAssistMockTransformer implements MockTransformer { private final TransformStrategy strategy; diff --git a/powermock-core/src/main/java/org/powermock/core/transformers/javassist/ClassFinalModifierMockTransformer.java b/powermock-core/src/main/java/org/powermock/core/transformers/javassist/ClassFinalModifierMockTransformer.java index 3c21afdf4..10e27ad07 100644 --- a/powermock-core/src/main/java/org/powermock/core/transformers/javassist/ClassFinalModifierMockTransformer.java +++ b/powermock-core/src/main/java/org/powermock/core/transformers/javassist/ClassFinalModifierMockTransformer.java @@ -18,12 +18,13 @@ package org.powermock.core.transformers.javassist; +import org.powermock.core.transformers.TransformStrategy; + 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; diff --git a/powermock-core/src/main/java/org/powermock/core/transformers/javassist/ConstructorsMockTransformer.java b/powermock-core/src/main/java/org/powermock/core/transformers/javassist/ConstructorsMockTransformer.java index eab840711..2556c064c 100644 --- a/powermock-core/src/main/java/org/powermock/core/transformers/javassist/ConstructorsMockTransformer.java +++ b/powermock-core/src/main/java/org/powermock/core/transformers/javassist/ConstructorsMockTransformer.java @@ -18,11 +18,12 @@ package org.powermock.core.transformers.javassist; +import org.powermock.core.transformers.TransformStrategy; + 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; diff --git a/powermock-core/src/main/java/org/powermock/core/transformers/javassist/InstrumentMockTransformer.java b/powermock-core/src/main/java/org/powermock/core/transformers/javassist/InstrumentMockTransformer.java index b5dc56d65..8b24c20c4 100644 --- a/powermock-core/src/main/java/org/powermock/core/transformers/javassist/InstrumentMockTransformer.java +++ b/powermock-core/src/main/java/org/powermock/core/transformers/javassist/InstrumentMockTransformer.java @@ -18,12 +18,13 @@ 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 javassist.CannotCompileException; +import javassist.CtClass; + public class InstrumentMockTransformer extends AbstractJavaAssistMockTransformer { private Class mockGetawayClass; diff --git a/powermock-core/src/main/java/org/powermock/core/transformers/javassist/MethodMockTransformer.java b/powermock-core/src/main/java/org/powermock/core/transformers/javassist/MethodMockTransformer.java index b53604dad..3f103d650 100644 --- a/powermock-core/src/main/java/org/powermock/core/transformers/javassist/MethodMockTransformer.java +++ b/powermock-core/src/main/java/org/powermock/core/transformers/javassist/MethodMockTransformer.java @@ -18,13 +18,14 @@ package org.powermock.core.transformers.javassist; +import org.powermock.core.MockGateway; +import org.powermock.core.transformers.TransformStrategy; + 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; diff --git a/powermock-core/src/main/java/org/powermock/core/transformers/javassist/MethodSizeMockTransformer.java b/powermock-core/src/main/java/org/powermock/core/transformers/javassist/MethodSizeMockTransformer.java index 5342ca3b2..c1de781db 100644 --- a/powermock-core/src/main/java/org/powermock/core/transformers/javassist/MethodSizeMockTransformer.java +++ b/powermock-core/src/main/java/org/powermock/core/transformers/javassist/MethodSizeMockTransformer.java @@ -18,12 +18,13 @@ package org.powermock.core.transformers.javassist; +import org.powermock.core.transformers.TransformStrategy; + 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. @@ -44,6 +45,7 @@ public MethodSizeMockTransformer(final TransformStrategy strategy) { super(strategy); } + @Override public CtClass transform(final CtClass clazz) throws CannotCompileException, NotFoundException { for (CtMethod method : clazz.getDeclaredMethods()) { if (isMethodSizeExceeded(method)) { diff --git a/powermock-core/src/main/java/org/powermock/core/transformers/javassist/PackagePrivateClassesMockTransformer.java b/powermock-core/src/main/java/org/powermock/core/transformers/javassist/PackagePrivateClassesMockTransformer.java index 38e77156c..4075cdb91 100644 --- a/powermock-core/src/main/java/org/powermock/core/transformers/javassist/PackagePrivateClassesMockTransformer.java +++ b/powermock-core/src/main/java/org/powermock/core/transformers/javassist/PackagePrivateClassesMockTransformer.java @@ -18,10 +18,11 @@ package org.powermock.core.transformers.javassist; +import org.powermock.core.transformers.TransformStrategy; + import javassist.CtClass; import javassist.Modifier; import javassist.NotFoundException; -import org.powermock.core.transformers.TransformStrategy; import static org.powermock.core.transformers.TransformStrategy.INST_REDEFINE; diff --git a/powermock-core/src/main/java/org/powermock/core/transformers/javassist/StaticFinalFieldsMockTransformer.java b/powermock-core/src/main/java/org/powermock/core/transformers/javassist/StaticFinalFieldsMockTransformer.java index 5abcaed67..42affb8ef 100644 --- a/powermock-core/src/main/java/org/powermock/core/transformers/javassist/StaticFinalFieldsMockTransformer.java +++ b/powermock-core/src/main/java/org/powermock/core/transformers/javassist/StaticFinalFieldsMockTransformer.java @@ -18,10 +18,11 @@ package org.powermock.core.transformers.javassist; +import org.powermock.core.transformers.TransformStrategy; + import javassist.CtClass; import javassist.CtField; import javassist.Modifier; -import org.powermock.core.transformers.TransformStrategy; import static org.powermock.core.transformers.TransformStrategy.INST_REDEFINE; @@ -35,6 +36,7 @@ public StaticFinalFieldsMockTransformer(final TransformStrategy strategy) { super(strategy); } + @Override public CtClass transform(final CtClass clazz) { if (clazz.isInterface()) { return clazz; diff --git a/powermock-core/src/main/java/org/powermock/core/transformers/javassist/StaticFinalNativeMethodMockTransformer.java b/powermock-core/src/main/java/org/powermock/core/transformers/javassist/StaticFinalNativeMethodMockTransformer.java index fde1bbb29..dfa17291a 100644 --- a/powermock-core/src/main/java/org/powermock/core/transformers/javassist/StaticFinalNativeMethodMockTransformer.java +++ b/powermock-core/src/main/java/org/powermock/core/transformers/javassist/StaticFinalNativeMethodMockTransformer.java @@ -18,11 +18,12 @@ package org.powermock.core.transformers.javassist; +import org.powermock.core.transformers.TransformStrategy; + import javassist.CannotCompileException; import javassist.CtClass; import javassist.CtMethod; import javassist.NotFoundException; -import org.powermock.core.transformers.TransformStrategy; public class StaticFinalNativeMethodMockTransformer extends MethodMockTransformer { diff --git a/powermock-core/src/main/java/org/powermock/core/transformers/javassist/SuppressStaticInitializerMockTransformer.java b/powermock-core/src/main/java/org/powermock/core/transformers/javassist/SuppressStaticInitializerMockTransformer.java index 35e00239a..5a4485ca0 100644 --- a/powermock-core/src/main/java/org/powermock/core/transformers/javassist/SuppressStaticInitializerMockTransformer.java +++ b/powermock-core/src/main/java/org/powermock/core/transformers/javassist/SuppressStaticInitializerMockTransformer.java @@ -18,11 +18,12 @@ package org.powermock.core.transformers.javassist; +import org.powermock.core.MockGateway; +import org.powermock.core.transformers.TransformStrategy; + 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; diff --git a/powermock-core/src/main/java/org/powermock/core/transformers/javassist/support/JavaAssistClassWrapperFactory.java b/powermock-core/src/main/java/org/powermock/core/transformers/javassist/support/JavaAssistClassWrapperFactory.java index 76cc5a4e1..cf9cfa7f3 100644 --- a/powermock-core/src/main/java/org/powermock/core/transformers/javassist/support/JavaAssistClassWrapperFactory.java +++ b/powermock-core/src/main/java/org/powermock/core/transformers/javassist/support/JavaAssistClassWrapperFactory.java @@ -18,10 +18,11 @@ package org.powermock.core.transformers.javassist.support; -import javassist.CtClass; import org.powermock.core.transformers.ClassWrapper; import org.powermock.core.transformers.ClassWrapperFactory; +import javassist.CtClass; + public class JavaAssistClassWrapperFactory implements ClassWrapperFactory { @Override public ClassWrapper wrap(CtClass ctClass) { diff --git a/powermock-core/src/main/java/org/powermock/core/transformers/javassist/support/PowerMockExpressionEditor.java b/powermock-core/src/main/java/org/powermock/core/transformers/javassist/support/PowerMockExpressionEditor.java index 876b3bcc4..de91808b6 100644 --- a/powermock-core/src/main/java/org/powermock/core/transformers/javassist/support/PowerMockExpressionEditor.java +++ b/powermock-core/src/main/java/org/powermock/core/transformers/javassist/support/PowerMockExpressionEditor.java @@ -18,6 +18,10 @@ package org.powermock.core.transformers.javassist.support; +import org.powermock.core.IndicateReloadClass; +import org.powermock.core.MockGateway; +import org.powermock.core.transformers.TransformStrategy; + import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; @@ -32,9 +36,6 @@ 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; diff --git a/powermock-core/src/main/java/org/powermock/core/transformers/javassist/support/Primitives.java b/powermock-core/src/main/java/org/powermock/core/transformers/javassist/support/Primitives.java index 0c49011e3..99317617a 100644 --- a/powermock-core/src/main/java/org/powermock/core/transformers/javassist/support/Primitives.java +++ b/powermock-core/src/main/java/org/powermock/core/transformers/javassist/support/Primitives.java @@ -15,12 +15,12 @@ */ package org.powermock.core.transformers.javassist.support; -import javassist.CtPrimitiveType; - import java.util.Collections; import java.util.IdentityHashMap; import java.util.Map; +import javassist.CtPrimitiveType; + import static javassist.CtClass.booleanType; import static javassist.CtClass.byteType; import static javassist.CtClass.charType; @@ -41,7 +41,7 @@ public class Primitives { lookupMappings(); private static Map> lookupMappings() { - Map> mappings = new IdentityHashMap>(10); + Map> mappings = new IdentityHashMap<>(10); for (Object[] each : new Object[][]{ {booleanType, boolean.class}, {byteType, byte.class}, diff --git a/powermock-core/src/main/java/org/powermock/core/transformers/javassist/testclass/ForMethodsJavaAssistTestClassTransformer.java b/powermock-core/src/main/java/org/powermock/core/transformers/javassist/testclass/ForMethodsJavaAssistTestClassTransformer.java index afd8e6140..04fe49fa9 100644 --- a/powermock-core/src/main/java/org/powermock/core/transformers/javassist/testclass/ForMethodsJavaAssistTestClassTransformer.java +++ b/powermock-core/src/main/java/org/powermock/core/transformers/javassist/testclass/ForMethodsJavaAssistTestClassTransformer.java @@ -1,6 +1,5 @@ package org.powermock.core.transformers.javassist.testclass; -import javassist.CtMethod; import org.powermock.core.transformers.MethodSignatureWriter; import java.lang.annotation.Annotation; @@ -8,6 +7,8 @@ import java.util.Collection; import java.util.HashSet; +import javassist.CtMethod; + public class ForMethodsJavaAssistTestClassTransformer extends JavaAssistTestClassTransformer { private final Collection testMethodsThatRunOnOtherClassLoaders; @@ -29,7 +30,7 @@ public ForMethodsJavaAssistTestClassTransformer(final Class testClass, protected boolean mustHaveTestAnnotationRemoved(CtMethod method) throws Exception { if (null == methodsThatRunOnOtherClassLoaders) { /* This lazy initialization is necessary - see above */ - methodsThatRunOnOtherClassLoaders = new HashSet(); + methodsThatRunOnOtherClassLoaders = new HashSet<>(); for (Method m : testMethodsThatRunOnOtherClassLoaders) { methodsThatRunOnOtherClassLoaders.add(signatureOf(m)); } diff --git a/powermock-core/src/main/java/org/powermock/core/transformers/javassist/testclass/FromAllMethodsExceptJavaAssistTestClassTransformer.java b/powermock-core/src/main/java/org/powermock/core/transformers/javassist/testclass/FromAllMethodsExceptJavaAssistTestClassTransformer.java index 29f6ecd4a..99f182c58 100644 --- a/powermock-core/src/main/java/org/powermock/core/transformers/javassist/testclass/FromAllMethodsExceptJavaAssistTestClassTransformer.java +++ b/powermock-core/src/main/java/org/powermock/core/transformers/javassist/testclass/FromAllMethodsExceptJavaAssistTestClassTransformer.java @@ -1,11 +1,12 @@ 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 javassist.CtMethod; + public class FromAllMethodsExceptJavaAssistTestClassTransformer extends JavaAssistTestClassTransformer { private final String targetMethodSignature; diff --git a/powermock-core/src/main/java/org/powermock/core/transformers/javassist/testclass/JavaAssistTestClassTransformer.java b/powermock-core/src/main/java/org/powermock/core/transformers/javassist/testclass/JavaAssistTestClassTransformer.java index 13f776640..e7b3596c3 100644 --- a/powermock-core/src/main/java/org/powermock/core/transformers/javassist/testclass/JavaAssistTestClassTransformer.java +++ b/powermock-core/src/main/java/org/powermock/core/transformers/javassist/testclass/JavaAssistTestClassTransformer.java @@ -16,14 +16,6 @@ */ 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; @@ -34,6 +26,15 @@ import java.lang.annotation.Annotation; import java.lang.reflect.Array; +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; + public abstract class JavaAssistTestClassTransformer extends TestClassTransformer { JavaAssistTestClassTransformer(Class testClass, diff --git a/powermock-core/src/main/java/org/powermock/core/transformers/support/DefaultMockTransformerChain.java b/powermock-core/src/main/java/org/powermock/core/transformers/support/DefaultMockTransformerChain.java index bbf59ffe7..6b49f650d 100644 --- a/powermock-core/src/main/java/org/powermock/core/transformers/support/DefaultMockTransformerChain.java +++ b/powermock-core/src/main/java/org/powermock/core/transformers/support/DefaultMockTransformerChain.java @@ -18,7 +18,6 @@ package org.powermock.core.transformers.support; - import org.powermock.core.transformers.ClassWrapper; import org.powermock.core.transformers.MockTransformer; import org.powermock.core.transformers.MockTransformerChain; @@ -47,7 +46,7 @@ public ClassWrapper transform(final ClassWrapper clazz) throws Excepti @Override public Collection filter(final FilterPredicate predicate) { - final ArrayList filtered = new ArrayList(); + final ArrayList filtered = new ArrayList<>(); for (MockTransformer transformer : transformers) { if (predicate.test(transformer)) { @@ -72,7 +71,7 @@ public static class MockTransformerChainBuilder { private final List transformers; private MockTransformerChainBuilder() { - transformers = new ArrayList(); + transformers = new ArrayList<>(); } public MockTransformerChainBuilder append(MockTransformer transformer) { diff --git a/powermock-core/src/main/java/org/powermock/core/transformers/support/FilterPredicates.java b/powermock-core/src/main/java/org/powermock/core/transformers/support/FilterPredicates.java index 3c90472de..cccd47e0b 100644 --- a/powermock-core/src/main/java/org/powermock/core/transformers/support/FilterPredicates.java +++ b/powermock-core/src/main/java/org/powermock/core/transformers/support/FilterPredicates.java @@ -1,16 +1,10 @@ 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()); - } - }; + return mockTransformer -> klass.isAssignableFrom(mockTransformer.getClass()); } } diff --git a/powermock-core/src/main/java/org/powermock/mockpolicies/impl/MockPolicyClassLoadingSettingsImpl.java b/powermock-core/src/main/java/org/powermock/mockpolicies/impl/MockPolicyClassLoadingSettingsImpl.java index 4b25068e5..a06ce9055 100644 --- a/powermock-core/src/main/java/org/powermock/mockpolicies/impl/MockPolicyClassLoadingSettingsImpl.java +++ b/powermock-core/src/main/java/org/powermock/mockpolicies/impl/MockPolicyClassLoadingSettingsImpl.java @@ -30,8 +30,8 @@ public class MockPolicyClassLoadingSettingsImpl implements MockPolicyClassLoadin private Set staticInitializersToSuppress; public MockPolicyClassLoadingSettingsImpl() { - fullyQualifiedNamesOfClassesToLoadByMockClassloader = new LinkedHashSet(); - staticInitializersToSuppress = new LinkedHashSet(); + fullyQualifiedNamesOfClassesToLoadByMockClassloader = new LinkedHashSet<>(); + staticInitializersToSuppress = new LinkedHashSet<>(); } @Override @@ -39,7 +39,7 @@ public String[] getFullyQualifiedNamesOfClassesToLoadByMockClassloader() { if (fullyQualifiedNamesOfClassesToLoadByMockClassloader == null) { return new String[0]; } - return fullyQualifiedNamesOfClassesToLoadByMockClassloader.toArray(new String[fullyQualifiedNamesOfClassesToLoadByMockClassloader.size()]); + return fullyQualifiedNamesOfClassesToLoadByMockClassloader.toArray(new String[0]); } @Override @@ -47,7 +47,7 @@ public String[] getStaticInitializersToSuppress() { if (staticInitializersToSuppress == null) { return new String[0]; } - return staticInitializersToSuppress.toArray(new String[staticInitializersToSuppress.size()]); + return staticInitializersToSuppress.toArray(new String[0]); } @Override diff --git a/powermock-core/src/main/java/org/powermock/mockpolicies/impl/MockPolicyInterceptionSettingsImpl.java b/powermock-core/src/main/java/org/powermock/mockpolicies/impl/MockPolicyInterceptionSettingsImpl.java index 12d76fd3a..5a2532971 100644 --- a/powermock-core/src/main/java/org/powermock/mockpolicies/impl/MockPolicyInterceptionSettingsImpl.java +++ b/powermock-core/src/main/java/org/powermock/mockpolicies/impl/MockPolicyInterceptionSettingsImpl.java @@ -34,11 +34,11 @@ public class MockPolicyInterceptionSettingsImpl implements MockPolicyInterceptio private Map proxies; public MockPolicyInterceptionSettingsImpl() { - fieldsToSuppress = new LinkedHashSet(); - methodsToSuppress = new LinkedHashSet(); - substituteReturnValues = new HashMap(); - proxies = new HashMap(); - fieldsTypesToSuppress = new LinkedHashSet(); + fieldsToSuppress = new LinkedHashSet<>(); + methodsToSuppress = new LinkedHashSet<>(); + substituteReturnValues = new HashMap<>(); + proxies = new HashMap<>(); + fieldsTypesToSuppress = new LinkedHashSet<>(); } @Override @@ -60,12 +60,12 @@ public void setFieldTypesToSuppress(String[] fieldTypes) { @Override public Field[] getFieldsToSuppress() { - return fieldsToSuppress.toArray(new Field[fieldsToSuppress.size()]); + return fieldsToSuppress.toArray(new Field[0]); } @Override public Method[] getMethodsToSuppress() { - return methodsToSuppress.toArray(new Method[methodsToSuppress.size()]); + return methodsToSuppress.toArray(new Method[0]); } @Override @@ -119,7 +119,7 @@ public void setMethodsToStub(Map substituteReturnValues) { @Override public String[] getFieldTypesToSuppress() { - return fieldsTypesToSuppress.toArray(new String[fieldsTypesToSuppress.size()]); + return fieldsTypesToSuppress.toArray(new String[0]); } @Override diff --git a/powermock-core/src/main/java/org/powermock/tests/utils/impl/AbstractCommonTestSuiteChunkerImpl.java b/powermock-core/src/main/java/org/powermock/tests/utils/impl/AbstractCommonTestSuiteChunkerImpl.java index d9adfe2a8..8f91278ea 100644 --- a/powermock-core/src/main/java/org/powermock/tests/utils/impl/AbstractCommonTestSuiteChunkerImpl.java +++ b/powermock-core/src/main/java/org/powermock/tests/utils/impl/AbstractCommonTestSuiteChunkerImpl.java @@ -29,12 +29,12 @@ public abstract class AbstractCommonTestSuiteChunkerImpl implements TestSuiteChu * Maps between a specific class and a map of test methods loaded by a * specific mock class loader. */ - private final List internalSuites = new LinkedList(); + 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 LinkedHashMap> testAtDelegateMapper = new LinkedHashMap<>(); final Class[] testClasses; private int currentTestIndex = NOT_INITIALIZED; @@ -56,14 +56,16 @@ public int getChunkSize() { return getTestChunks().size(); } + @Override public List getTestChunks() { - List allChunks = new LinkedList(); + List allChunks = new LinkedList<>(); for (TestCaseEntry entry : internalSuites) { allChunks.addAll(entry.getTestChunks()); } return allChunks; } + @Override public List getTestChunksEntries(Class testClass) { for (TestCaseEntry entry : internalSuites) { if (entry.getTestClass().equals(testClass)) { @@ -73,6 +75,7 @@ public List getTestChunksEntries(Class testClass) { return null; } + @Override public TestChunk getTestChunk(Method method) { for (TestChunk testChunk : getTestChunks()) { if (testChunk.isMethodToBeExecutedByThisClassloader(method)) { @@ -82,17 +85,17 @@ public TestChunk getTestChunk(Method method) { return null; } - private void chunkClass(final Class testClass) throws Exception { + private void chunkClass(final Class testClass) { - List testMethodsForOtherClassLoaders = new ArrayList(); + List testMethodsForOtherClassLoaders = new ArrayList<>(); final ClassLoader defaultMockLoader = createDefaultMockLoader(testClass, testMethodsForOtherClassLoaders); - List currentClassloaderMethods = new LinkedList(); + List currentClassloaderMethods = new LinkedList<>(); TestChunk defaultTestChunk = new TestChunkImpl(defaultMockLoader, currentClassloaderMethods); // Put the first suite in the map of internal suites. - List testChunks = new LinkedList(); + List testChunks = new LinkedList<>(); testChunks.add(defaultTestChunk); internalSuites.add(new TestCaseEntry(testClass, testChunks)); @@ -132,7 +135,7 @@ private void putMethodToChunk(TestCaseEntry testCaseEntry, Class testClass, M if (shouldExecuteTestForMethod(method)) { currentTestIndex++; if (hasChunkAnnotation(method)) { - LinkedList methodsInThisChunk = new LinkedList(); + LinkedList methodsInThisChunk = new LinkedList<>(); methodsInThisChunk.add(method); final ClassLoader mockClassloader = createClassLoaderForMethod(testClass, method); @@ -148,13 +151,8 @@ private void putMethodToChunk(TestCaseEntry testCaseEntry, Class testClass, M * 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); + testAtDelegateMapper.computeIfAbsent(currentDelegateIndex, k -> new LinkedList<>()).add( + currentTestIndex); } } } @@ -203,7 +201,7 @@ private boolean hasChunkAnnotation(Method method) { } private void updatedIndexes() { - final List testIndexesForThisClassloader = new LinkedList(); + final List testIndexesForThisClassloader = new LinkedList<>(); testIndexesForThisClassloader.add(currentTestIndex); testAtDelegateMapper.put(internalSuites.size(), testIndexesForThisClassloader); } diff --git a/powermock-core/src/main/java/org/powermock/tests/utils/impl/AbstractTestClassExtractor.java b/powermock-core/src/main/java/org/powermock/tests/utils/impl/AbstractTestClassExtractor.java index 19fb58f88..94928c76d 100644 --- a/powermock-core/src/main/java/org/powermock/tests/utils/impl/AbstractTestClassExtractor.java +++ b/powermock-core/src/main/java/org/powermock/tests/utils/impl/AbstractTestClassExtractor.java @@ -44,13 +44,13 @@ protected AbstractTestClassExtractor(){ */ @Override public final String[] getTestClasses(AnnotatedElement element) { - final Set classesToPrepareForTest = new HashSet(); + final Set classesToPrepareForTest = new HashSet<>(); if (element instanceof Class) { extractClassesFromTestClass((Class) element, classesToPrepareForTest); } else { extractClassesAndAddThemToList(element, classesToPrepareForTest); } - return classesToPrepareForTest.toArray(new String[classesToPrepareForTest.size()]); + return classesToPrepareForTest.toArray(new String[0]); } private void extractClassesFromTestClass(final Class element, Set classesToPrepareForTest) { @@ -65,7 +65,7 @@ private void extractClassesFromTestClass(final Class element, Set cla } private Collection lookOverMethods(Class classToInvestigate) { - Set classesToPrepareForTest = new HashSet(); + Set classesToPrepareForTest = new HashSet<>(); for (Method method : classToInvestigate.getMethods()) { extractClassesAndAddThemToList(method, classesToPrepareForTest); } diff --git a/powermock-core/src/main/java/org/powermock/tests/utils/impl/AbstractTestSuiteChunkerImpl.java b/powermock-core/src/main/java/org/powermock/tests/utils/impl/AbstractTestSuiteChunkerImpl.java index c2c0561d4..2e6821c81 100644 --- a/powermock-core/src/main/java/org/powermock/tests/utils/impl/AbstractTestSuiteChunkerImpl.java +++ b/powermock-core/src/main/java/org/powermock/tests/utils/impl/AbstractTestSuiteChunkerImpl.java @@ -46,10 +46,10 @@ public abstract class AbstractTestSuiteChunkerImpl extends AbstractCommonTest * The classes listed in this set has been chunked and its delegates has * been created. */ - protected final Set> delegatesCreatedForTheseClasses = new LinkedHashSet>(); + protected final Set> delegatesCreatedForTheseClasses = new LinkedHashSet<>(); // A list of junit delegates. - protected final List delegates = new ArrayList(); + protected final List delegates = new ArrayList<>(); protected volatile int testCount = NOT_INITIALIZED; @@ -100,6 +100,7 @@ protected Object getPowerMockTestListenersLoadedByASpecificClassLoader(Class } } + @Override public final void createTestDelegators(Class testClass, List chunks) throws Exception { for (TestChunk chunk : chunks) { ClassLoader classLoader = chunk.getClassLoader(); diff --git a/powermock-core/src/main/java/org/powermock/tests/utils/impl/PowerMockIgnorePackagesExtractorImpl.java b/powermock-core/src/main/java/org/powermock/tests/utils/impl/PowerMockIgnorePackagesExtractorImpl.java index 75f546de4..3e86bf573 100644 --- a/powermock-core/src/main/java/org/powermock/tests/utils/impl/PowerMockIgnorePackagesExtractorImpl.java +++ b/powermock-core/src/main/java/org/powermock/tests/utils/impl/PowerMockIgnorePackagesExtractorImpl.java @@ -40,10 +40,10 @@ public String[] getPackagesToIgnore(AnnotatedElement element) { useGlobal = annotation.globalIgnore(); } - Set ignoredPackages = new HashSet(); + Set ignoredPackages = new HashSet<>(); useGlobal &= extractPackageToIgnore(element, ignoredPackages); - final String[] packageToIgnore = ignoredPackages.toArray(new String[ignoredPackages.size()]); + final String[] packageToIgnore = ignoredPackages.toArray(new String[0]); if (useGlobal) { return getPackageToIgnoreWithGlobal(packageToIgnore); } else { @@ -77,7 +77,7 @@ private boolean extractPackageToIgnore(final AnnotatedElement element, final Set } private boolean addValuesFromSuperclass(final Class element, final Set ignoredPackages) { - final Collection> superclasses = new ArrayList>(); + final Collection> superclasses = new ArrayList<>(); Collections.addAll(superclasses, element.getSuperclass()); Collections.addAll(superclasses, element.getInterfaces()); diff --git a/powermock-core/src/main/java/org/powermock/tests/utils/impl/PrepareForTestExtractorImpl.java b/powermock-core/src/main/java/org/powermock/tests/utils/impl/PrepareForTestExtractorImpl.java index 98c2475c2..1d2984582 100644 --- a/powermock-core/src/main/java/org/powermock/tests/utils/impl/PrepareForTestExtractorImpl.java +++ b/powermock-core/src/main/java/org/powermock/tests/utils/impl/PrepareForTestExtractorImpl.java @@ -44,7 +44,7 @@ public PrepareForTestExtractorImpl(boolean includeMethods) { @Override protected String[] getClassesToModify(AnnotatedElement element) { - Set all = new LinkedHashSet(); + Set all = new LinkedHashSet<>(); addTestCase(all, element); PrepareForTest prepareForTestAnnotation = element.getAnnotation(PrepareForTest.class); PrepareOnlyThisForTest prepareOnlyThisForTestAnnotation = element.getAnnotation(PrepareOnlyThisForTest.class); @@ -77,7 +77,7 @@ protected String[] getClassesToModify(AnnotatedElement element) { addFullyQualifiedNames(all, prepareOnlyThisForTestAnnotation); } - return all.toArray(new String[all.size()]); + return all.toArray(new String[0]); } diff --git a/powermock-core/src/main/java/org/powermock/tests/utils/impl/StaticConstructorSuppressExtractorImpl.java b/powermock-core/src/main/java/org/powermock/tests/utils/impl/StaticConstructorSuppressExtractorImpl.java index a4c2372e6..1b48c8d96 100644 --- a/powermock-core/src/main/java/org/powermock/tests/utils/impl/StaticConstructorSuppressExtractorImpl.java +++ b/powermock-core/src/main/java/org/powermock/tests/utils/impl/StaticConstructorSuppressExtractorImpl.java @@ -32,7 +32,7 @@ public class StaticConstructorSuppressExtractorImpl extends AbstractTestClassExt @Override public String[] getClassesToModify(AnnotatedElement element) { - List all = new LinkedList(); + List all = new LinkedList<>(); final SuppressStaticInitializationFor suppressAnnotation = element.getAnnotation(SuppressStaticInitializationFor.class); @@ -48,6 +48,6 @@ public String[] getClassesToModify(AnnotatedElement element) { } } - return all.toArray(new String[all.size()]); + return all.toArray(new String[0]); } } diff --git a/powermock-core/src/main/java/org/powermock/tests/utils/impl/TestChunkImpl.java b/powermock-core/src/main/java/org/powermock/tests/utils/impl/TestChunkImpl.java index fcce1bec8..4a9c1a0e4 100644 --- a/powermock-core/src/main/java/org/powermock/tests/utils/impl/TestChunkImpl.java +++ b/powermock-core/src/main/java/org/powermock/tests/utils/impl/TestChunkImpl.java @@ -26,23 +26,23 @@ */ public class TestChunkImpl implements TestChunk { - private final ClassLoader classLoader; - private final List testMethodsToBeExecutedByThisClassloader; + private final ClassLoader classLoader; + private final List testMethodsToBeExecutedByThisClassloader; public TestChunkImpl(ClassLoader classLoader, List testMethodsToBeExecutedByThisClassloader) { - this.classLoader = classLoader; - this.testMethodsToBeExecutedByThisClassloader = testMethodsToBeExecutedByThisClassloader; + this.classLoader = classLoader; + this.testMethodsToBeExecutedByThisClassloader = testMethodsToBeExecutedByThisClassloader; } - @Override - public ClassLoader getClassLoader() { - return classLoader; - } + @Override + public ClassLoader getClassLoader() { + return classLoader; + } - @Override - public List getTestMethodsToBeExecutedByThisClassloader() { - return testMethodsToBeExecutedByThisClassloader; - } + @Override + public List getTestMethodsToBeExecutedByThisClassloader() { + return testMethodsToBeExecutedByThisClassloader; + } @Override public boolean isMethodToBeExecutedByThisClassloader(Method method) { @@ -50,13 +50,13 @@ public boolean isMethodToBeExecutedByThisClassloader(Method 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(); - } + 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(); + } } diff --git a/powermock-core/src/main/java/org/powermock/utils/ArrayUtil.java b/powermock-core/src/main/java/org/powermock/utils/ArrayUtil.java index 75d9e216f..37a038ded 100644 --- a/powermock-core/src/main/java/org/powermock/utils/ArrayUtil.java +++ b/powermock-core/src/main/java/org/powermock/utils/ArrayUtil.java @@ -68,11 +68,11 @@ public static String[] mergeArrays(final String[] firstArray, final String[] sec return firstArray; } - Set globalIgnore = new HashSet(); + Set globalIgnore = new HashSet<>(); globalIgnore.addAll(asList(firstArray)); globalIgnore.addAll(asList(secondArray)); - return globalIgnore.toArray(new String[globalIgnore.size()]); + return globalIgnore.toArray(new String[0]); } } diff --git a/powermock-core/src/main/java/org/powermock/utils/IOUtils.java b/powermock-core/src/main/java/org/powermock/utils/IOUtils.java index f4f752f72..ef00031d3 100644 --- a/powermock-core/src/main/java/org/powermock/utils/IOUtils.java +++ b/powermock-core/src/main/java/org/powermock/utils/IOUtils.java @@ -28,23 +28,12 @@ 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); + try (InputStream is = new FileInputStream(source); OutputStream 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(); - } } } diff --git a/powermock-core/src/main/java/org/powermock/utils/JavaVersion.java b/powermock-core/src/main/java/org/powermock/utils/JavaVersion.java deleted file mode 100644 index 66dfbffc1..000000000 --- a/powermock-core/src/main/java/org/powermock/utils/JavaVersion.java +++ /dev/null @@ -1,232 +0,0 @@ -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; - } -} diff --git a/powermock-core/src/test/java/org/powermock/configuration/support/ConfigurationBuilderTest.java b/powermock-core/src/test/java/org/powermock/configuration/support/ConfigurationBuilderTest.java index f5226b21b..d998c429c 100644 --- a/powermock-core/src/test/java/org/powermock/configuration/support/ConfigurationBuilderTest.java +++ b/powermock-core/src/test/java/org/powermock/configuration/support/ConfigurationBuilderTest.java @@ -23,7 +23,7 @@ import org.powermock.configuration.MockitoConfiguration; import org.powermock.configuration.PowerMockConfiguration; -import static org.assertj.core.api.Java6Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.powermock.configuration.support.ConfigurationBuilder.createConfigurationFor; public class ConfigurationBuilderTest { diff --git a/powermock-core/src/test/java/org/powermock/configuration/support/ConfigurationFactoryImplTest.java b/powermock-core/src/test/java/org/powermock/configuration/support/ConfigurationFactoryImplTest.java index 6d6723b60..8d4daf739 100644 --- a/powermock-core/src/test/java/org/powermock/configuration/support/ConfigurationFactoryImplTest.java +++ b/powermock-core/src/test/java/org/powermock/configuration/support/ConfigurationFactoryImplTest.java @@ -28,7 +28,7 @@ import org.powermock.configuration.PowerMockConfiguration; import org.powermock.core.classloader.ByteCodeFramework; -import static org.assertj.core.api.Java6Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; @RunWith(Enclosed.class) public class ConfigurationFactoryImplTest { diff --git a/powermock-core/src/test/java/org/powermock/core/classloader/MockClassLoaderBuilderTest.java b/powermock-core/src/test/java/org/powermock/core/classloader/MockClassLoaderBuilderTest.java index f4b211a8b..a88f08715 100644 --- a/powermock-core/src/test/java/org/powermock/core/classloader/MockClassLoaderBuilderTest.java +++ b/powermock-core/src/test/java/org/powermock/core/classloader/MockClassLoaderBuilderTest.java @@ -1,14 +1,10 @@ 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; @@ -16,6 +12,8 @@ import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; +import javassist.CtClass; + import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -61,15 +59,9 @@ public void should_set_test_class_to_TestClassAwareTransformers() { @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); + assertThatThrownBy(() -> MockClassLoaderBuilder.create(ByteCodeFramework.Javassist).build()) + .as("Internal exception has been thrown.") + .isExactlyInstanceOf(PowerMockInternalException.class); } private void assertThatJavassistMockTransformerChainCreated(final MockClassLoader classLoader) { @@ -80,12 +72,7 @@ private void assertThatJavassistMockTransformerChainCreated(final MockClassLoade 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(), + mockTransformerChain.filter(mockTransformer -> true).iterator().next().getClass(), "transform", ClassWrapper.class ); diff --git a/powermock-core/src/test/java/org/powermock/core/classloader/MockClassLoaderConfigurationTest.java b/powermock-core/src/test/java/org/powermock/core/classloader/MockClassLoaderConfigurationTest.java index dcc789516..f8ac63f69 100644 --- a/powermock-core/src/test/java/org/powermock/core/classloader/MockClassLoaderConfigurationTest.java +++ b/powermock-core/src/test/java/org/powermock/core/classloader/MockClassLoaderConfigurationTest.java @@ -18,11 +18,10 @@ package org.powermock.core.classloader; - import org.junit.Before; import org.junit.Test; -import static org.assertj.core.api.Java6Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; public class MockClassLoaderConfigurationTest { diff --git a/powermock-core/src/test/java/org/powermock/core/classloader/MockClassLoaderFactoryTest.java b/powermock-core/src/test/java/org/powermock/core/classloader/MockClassLoaderFactoryTest.java index 19cb438fc..b991dfb7f 100644 --- a/powermock-core/src/test/java/org/powermock/core/classloader/MockClassLoaderFactoryTest.java +++ b/powermock-core/src/test/java/org/powermock/core/classloader/MockClassLoaderFactoryTest.java @@ -1,6 +1,5 @@ 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; @@ -16,16 +15,16 @@ 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; +import powermock.test.support.MainMockTransformerTestSupport.SupportClasses; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.powermock.core.test.ContainsCondition.contains; @RunWith(Enclosed.class) public class MockClassLoaderFactoryTest { @@ -57,7 +56,7 @@ public static class AnnotationOnMethodLevelCases extends BasePrepareForTestCases @Parameters(name = "Test parameter: {0}") public static Collection parameters() { - final ArrayList parameters = new ArrayList(); + 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"}); @@ -92,7 +91,7 @@ public void should_extract_classes_to_modify_method_level_annotation_if_exist() public static class DifferentByteCodeFrameworkCases { @Parameters(name = "Test parameter: {0}") public static Collection parameters() { - final ArrayList parameters = new ArrayList(); + final ArrayList parameters = new ArrayList<>(); parameters.add(new Object[]{JavassistTestClass.class, JavassistMockClassLoader.class}); @@ -156,12 +155,7 @@ public void setUp() { 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.") + assertThatThrownBy(() -> objectUnderTest.createForMethod(method)).as("Exception is thrown.") .isExactlyInstanceOf(IllegalArgumentException.class); } @@ -172,7 +166,7 @@ public abstract static class BasePrepareForTestCases { @Parameters(name = "Test parameter: {0}") public static Collection parameters() { - final ArrayList parameters = new ArrayList(); + final ArrayList parameters = new ArrayList<>(); parameters.add(new Object[]{JavassistTestClass.class, "powermock.test.support.MainMockTransformerTestSupport$SupportClasses"}); parameters.add(new Object[]{SuppressStaticInitializationForTestClass.class, "SupportClasses.FinalInnerClass"}); diff --git a/powermock-core/src/test/java/org/powermock/core/classloader/MockClassLoaderTest.java b/powermock-core/src/test/java/org/powermock/core/classloader/MockClassLoaderTest.java index f1c390852..ff6d74662 100644 --- a/powermock-core/src/test/java/org/powermock/core/classloader/MockClassLoaderTest.java +++ b/powermock-core/src/test/java/org/powermock/core/classloader/MockClassLoaderTest.java @@ -15,10 +15,6 @@ */ package org.powermock.core.classloader; -import javassist.ByteArrayClassPath; -import javassist.ClassPool; -import javassist.CtClass; -import javassist.CtMethod; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; @@ -38,8 +34,13 @@ import java.util.Enumeration; import java.util.List; -import static org.assertj.core.api.Java6Assertions.assertThat; +import javassist.ByteArrayClassPath; +import javassist.ClassPool; +import javassist.CtClass; +import javassist.CtMethod; + import static java.util.Arrays.asList; +import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertFalse; import static org.junit.Assume.assumeThat; @@ -299,6 +300,7 @@ private void assertClassIsLoaded(final Class clazz, final MockClassLoader moc // helper class for canFindDynamicClassFromAdjustedClasspath() public static class MyClassPathAdjuster implements ClassPathAdjuster { + @Override public void adjustClassPath(ClassPool classPool) { classPool.appendClassPath(new ByteArrayClassPath(DynamicClassHolder.clazz.getName(), DynamicClassHolder.classBytes)); } @@ -323,10 +325,12 @@ static class DynamicClassHolder { } public static class TestUseClassPathAdjuster implements UseClassPathAdjuster { + @Override public Class annotationType() { return UseClassPathAdjuster.class; } + @Override public Class value() { return MyClassPathAdjuster.class; } diff --git a/powermock-core/src/test/java/org/powermock/core/test/ClassLoaderTestHelper.java b/powermock-core/src/test/java/org/powermock/core/test/ClassLoaderTestHelper.java index e7cc26a78..5c515ddb4 100644 --- a/powermock-core/src/test/java/org/powermock/core/test/ClassLoaderTestHelper.java +++ b/powermock-core/src/test/java/org/powermock/core/test/ClassLoaderTestHelper.java @@ -18,8 +18,6 @@ package org.powermock.core.test; -import javassist.ClassPool; -import javassist.Loader; import org.powermock.core.classloader.MockClassLoader; import org.powermock.core.transformers.MockTransformerChain; @@ -27,6 +25,9 @@ import java.util.HashMap; import java.util.Map; +import javassist.ClassPool; +import javassist.Loader; + import static org.junit.Assert.assertNotNull; public class ClassLoaderTestHelper { @@ -34,7 +35,7 @@ public class ClassLoaderTestHelper { public static Map> cache; static { - cache = new HashMap>(); + cache = new HashMap<>(); } public static Class loadWithMockClassLoader(final String className, final MockTransformerChain mockTransformerChain, @@ -68,7 +69,7 @@ private static MockClassLoader getMockClassLoader(final MockTransformerChain moc if (classloaders != null){ loader = classloaders.get(mockTransformerChain); }else{ - classloaders = new HashMap(); + classloaders = new HashMap<>(); cache.put(mockClassloaderFactory, classloaders); } diff --git a/powermock-core/src/test/java/org/powermock/core/testlisteners/GlobalNotificationBuildSupportTest.java b/powermock-core/src/test/java/org/powermock/core/testlisteners/GlobalNotificationBuildSupportTest.java index 37c9236d5..acaa47582 100644 --- a/powermock-core/src/test/java/org/powermock/core/testlisteners/GlobalNotificationBuildSupportTest.java +++ b/powermock-core/src/test/java/org/powermock/core/testlisteners/GlobalNotificationBuildSupportTest.java @@ -20,6 +20,7 @@ import org.powermock.core.testlisteners.GlobalNotificationBuildSupport.Callback; import java.util.Collection; +import java.util.Collections; import java.util.concurrent.ConcurrentHashMap; import static org.junit.Assert.assertEquals; @@ -119,12 +120,12 @@ public void normalClassCreation() { */ @Test public void removeAllFromConcurrentHashMap() { - ConcurrentHashMap map = new ConcurrentHashMap(); + 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); + Collection valueToRemove = Collections.singleton(value); map.values().removeAll(valueToRemove); assertEquals("Size of concurrent hashmap after removal of values", 0, map.size()); diff --git a/powermock-core/src/test/java/org/powermock/core/transformers/AbstractBaseMockTransformerTest.java b/powermock-core/src/test/java/org/powermock/core/transformers/AbstractBaseMockTransformerTest.java index c95ac6002..f6ddafbad 100644 --- a/powermock-core/src/test/java/org/powermock/core/transformers/AbstractBaseMockTransformerTest.java +++ b/powermock-core/src/test/java/org/powermock/core/transformers/AbstractBaseMockTransformerTest.java @@ -18,7 +18,6 @@ package org.powermock.core.transformers; -import javassist.CtClass; import org.junit.Before; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @@ -29,6 +28,8 @@ import org.powermock.core.transformers.mock.MockGatewaySpy; import org.powermock.core.transformers.support.FilterPredicates; +import javassist.CtClass; + import static org.junit.Assume.assumeTrue; @RunWith(Parameterized.class) diff --git a/powermock-core/src/test/java/org/powermock/core/transformers/ClassFinalModifierMockTransformerTest.java b/powermock-core/src/test/java/org/powermock/core/transformers/ClassFinalModifierMockTransformerTest.java index 3fb2f8850..981426913 100644 --- a/powermock-core/src/test/java/org/powermock/core/transformers/ClassFinalModifierMockTransformerTest.java +++ b/powermock-core/src/test/java/org/powermock/core/transformers/ClassFinalModifierMockTransformerTest.java @@ -18,20 +18,19 @@ 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 org.powermock.core.transformers.javassist.ClassFinalModifierMockTransformer; -import java.lang.reflect.Modifier; import java.util.ArrayList; -import java.util.Collection; + +import powermock.test.support.MainMockTransformerTestSupport.SomeInterface; +import powermock.test.support.MainMockTransformerTestSupport.SupportClasses; 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.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.not; import static org.junit.Assert.assertFalse; @@ -41,11 +40,9 @@ public class ClassFinalModifierMockTransformerTest extends AbstractBaseMockTrans @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; + + return new ArrayList<>( + MockTransformerTestHelper.createTransformerTestData(ClassFinalModifierMockTransformer.class)); } public ClassFinalModifierMockTransformerTest( @@ -63,7 +60,7 @@ public void should_remove_final_modifier_from_static_final_inner_classes_strateg Class clazz = loadWithMockClassLoader(SupportClasses.StaticFinalInnerClass.class.getName()); - assertFalse(Modifier.isFinal(clazz.getModifiers())); + assertFalse(isFinal(clazz.getModifiers())); } @Test @@ -82,7 +79,7 @@ public void should_remove_final_modifier_from_final_inner_classes() throws Excep assumeThat(strategy, not(equalTo(TransformStrategy.INST_REDEFINE))); Class clazz = loadWithMockClassLoader(SupportClasses.FinalInnerClass.class.getName()); - assertFalse(Modifier.isFinal(clazz.getModifiers())); + assertFalse(isFinal(clazz.getModifiers())); } @Test @@ -91,7 +88,7 @@ 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())); + assertFalse(isFinal(clazz.getModifiers())); } @Test @@ -100,18 +97,13 @@ public void should_remove_final_modifier_from_private_static_final_inner_classes assumeThat(strategy, not(equalTo(TransformStrategy.INST_REDEFINE))); Class clazz = loadWithMockClassLoader(SupportClasses.class.getName() + "$PrivateStaticFinalInnerClass"); - assertFalse(Modifier.isFinal(clazz.getModifiers())); + assertFalse(isFinal(clazz.getModifiers())); } @Test - public void should_ignore_interfaces() throws Exception { + public void should_ignore_interfaces() { - Throwable throwable = catchThrowable(new ThrowingCallable() { - @Override - public void call() throws Throwable { - loadWithMockClassLoader(SomeInterface.class.getName()); - } - }); + Throwable throwable = catchThrowable(() -> loadWithMockClassLoader(SomeInterface.class.getName())); assertThat(throwable).isNull(); } diff --git a/powermock-core/src/test/java/org/powermock/core/transformers/ConstructorCallMockTransformerTest.java b/powermock-core/src/test/java/org/powermock/core/transformers/ConstructorCallMockTransformerTest.java index 2588d7c10..aab9c68bb 100644 --- a/powermock-core/src/test/java/org/powermock/core/transformers/ConstructorCallMockTransformerTest.java +++ b/powermock-core/src/test/java/org/powermock/core/transformers/ConstructorCallMockTransformerTest.java @@ -18,7 +18,6 @@ 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; @@ -27,6 +26,10 @@ import org.powermock.core.transformers.javassist.InstrumentMockTransformer; import org.powermock.core.transformers.mock.MockGatewaySpy; import org.powermock.core.transformers.mock.MockGatewaySpy.MethodCall; + +import java.lang.reflect.Constructor; +import java.util.ArrayList; + import powermock.test.support.MainMockTransformerTestSupport.ConstructorCall.SupperClassThrowsException; import powermock.test.support.MainMockTransformerTestSupport.ParameterImpl; import powermock.test.support.MainMockTransformerTestSupport.ParameterInterface; @@ -42,13 +45,9 @@ 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.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assume.assumeThat; import static org.powermock.core.MockGateway.PROCEED; @@ -59,11 +58,9 @@ public class ConstructorCallMockTransformerTest extends AbstractBaseMockTransfor @Parameterized.Parameters(name = "strategy: {0}, transformerType: {2}") public static Iterable data() { - Collection data = new ArrayList(); - - data.addAll(createTransformerTestDataWithMockGateway(MockGatewaySpy.class, InstrumentMockTransformer.class)); - - return data; + + return new ArrayList<>( + createTransformerTestDataWithMockGateway(MockGatewaySpy.class, InstrumentMockTransformer.class)); } public ConstructorCallMockTransformerTest(final TransformStrategy strategy, @@ -86,15 +83,9 @@ public void should_not_change_constructors_of_test_class() throws Exception { 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); + assertThatThrownBy(() -> modifiedClass.getConstructor(IndicateReloadClass.class)) + .withFailMessage("A public defer-constructor is added.") + .isExactlyInstanceOf(NoSuchMethodException.class); } @Test @@ -109,15 +100,9 @@ public void should_not_change_constructors_of_nested_test_classes() throws Excep 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); + assertThatThrownBy(() -> modifiedClass.getConstructor(IndicateReloadClass.class)) + .withFailMessage("A public defer-constructor is added.") + .isExactlyInstanceOf(NoSuchMethodException.class); } @Test @@ -192,14 +177,11 @@ public void should_suppress_call_to_super_constructor_if_getaway_return_SUPPRESS 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(); - } + Throwable throwable = catchThrowable(() -> { + try { + constructor.newInstance("name", "field", 100); + } catch (Exception e) { + throw e.getCause() == null ? e : e.getCause(); } }); @@ -218,14 +200,11 @@ public void should_not_suppress_call_to_super_constructor_if_getaway_return_PROC 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(); - } + Throwable throwable = catchThrowable(() -> { + try { + constructor.newInstance("name", "field", 100); + } catch (Exception e) { + throw e.getCause() == null ? e : e.getCause(); } }); @@ -286,12 +265,7 @@ public void should_provide_correct_constructor_param_and_arguments_when_cast_req 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(); - } - }) + .extracting((Extractor, Object>) Class::getName) .containsExactly(ParameterImpl.class.getName()); } diff --git a/powermock-core/src/test/java/org/powermock/core/transformers/ConstructorModifiersMockTransformerTest.java b/powermock-core/src/test/java/org/powermock/core/transformers/ConstructorModifiersMockTransformerTest.java index 10e085f76..c82648fbb 100644 --- a/powermock-core/src/test/java/org/powermock/core/transformers/ConstructorModifiersMockTransformerTest.java +++ b/powermock-core/src/test/java/org/powermock/core/transformers/ConstructorModifiersMockTransformerTest.java @@ -22,18 +22,16 @@ import org.junit.runners.Parameterized; import org.powermock.core.test.MockClassLoaderFactory; import org.powermock.core.transformers.javassist.ConstructorsMockTransformer; + +import java.lang.reflect.Modifier; +import java.util.ArrayList; + 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.assertj.core.api.Assertions.assertThat; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.not; import static org.junit.Assume.assumeThat; @@ -42,11 +40,9 @@ public class ConstructorModifiersMockTransformerTest extends AbstractBaseMockTra @Parameterized.Parameters(name = "strategy: {0}, transformerType: {2}") public static Iterable data() { - Collection data = new ArrayList(); - - data.addAll(MockTransformerTestHelper.createTransformerTestData(ConstructorsMockTransformer.class)); - - return data; + + return new ArrayList<>( + MockTransformerTestHelper.createTransformerTestData(ConstructorsMockTransformer.class)); } public ConstructorModifiersMockTransformerTest(final TransformStrategy strategy, @@ -111,16 +107,11 @@ public void should_not_change_constructors_of_nested_test_classes() throws Excep 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()); + .as("All constructor has same modifiers") + .hasSameSizeAs(clazz.getConstructors()) + .usingElementComparator((o1, o2) -> o1.getModifiers() == o2.getModifiers() ? o1.getParameterTypes().length + - o2.getParameterTypes().length : o1.getModifiers() - o2.getModifiers()) + .contains(clazz.getConstructors()); } } \ No newline at end of file diff --git a/powermock-core/src/test/java/org/powermock/core/transformers/InstrumentMockTransformerTest.java b/powermock-core/src/test/java/org/powermock/core/transformers/InstrumentMockTransformerTest.java index 1c0754aa8..752b81933 100644 --- a/powermock-core/src/test/java/org/powermock/core/transformers/InstrumentMockTransformerTest.java +++ b/powermock-core/src/test/java/org/powermock/core/transformers/InstrumentMockTransformerTest.java @@ -18,6 +18,14 @@ 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.InstrumentMockTransformer; +import org.powermock.core.transformers.mock.MockGatewaySpy; + +import java.lang.reflect.Field; + import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; @@ -25,16 +33,9 @@ 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.assertj.core.api.Assertions.assertThat; import static org.powermock.core.test.ClassLoaderTestHelper.runTestWithNewClassLoader; public class InstrumentMockTransformerTest extends AbstractBaseMockTransformerTest { diff --git a/powermock-core/src/test/java/org/powermock/core/transformers/MethodSizeMockTransformerTest.java b/powermock-core/src/test/java/org/powermock/core/transformers/MethodSizeMockTransformerTest.java index b10b1dbf2..dfb8bbb92 100644 --- a/powermock-core/src/test/java/org/powermock/core/transformers/MethodSizeMockTransformerTest.java +++ b/powermock-core/src/test/java/org/powermock/core/transformers/MethodSizeMockTransformerTest.java @@ -18,19 +18,19 @@ 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 powermock.test.support.ClassWithLargeMethods; + +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowable; import static org.junit.Assert.assertNotNull; @@ -39,12 +39,12 @@ public class MethodSizeMockTransformerTest extends AbstractBaseMockTransformerTe @Parameterized.Parameters(name = "strategy: {0}, transformer: {1}") public static Iterable data() { - List data = new ArrayList(); + List data = new ArrayList<>(); for (TransformStrategy strategy : TransformStrategy.values()) { data.add(new Object[]{ strategy, - new JavassistMockTransformerChainFactory().createDefaultChain(Collections.emptyList()), + new JavassistMockTransformerChainFactory().createDefaultChain(Collections.emptyList()), new MockClassLoaderFactory(JavassistMockClassLoader.class) }); } @@ -71,12 +71,7 @@ public void should_load_class_with_method_lower_than_jvm_limit() throws Exceptio 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); - } - }); + Throwable throwable = catchThrowable(() -> clazz.getMethod("init").invoke(clazz)); assertThat(throwable) .as("Overridden method should throw exception") diff --git a/powermock-core/src/test/java/org/powermock/core/transformers/MethodsMockTransformerTest.java b/powermock-core/src/test/java/org/powermock/core/transformers/MethodsMockTransformerTest.java index 6ac75783b..8c9244309 100644 --- a/powermock-core/src/test/java/org/powermock/core/transformers/MethodsMockTransformerTest.java +++ b/powermock-core/src/test/java/org/powermock/core/transformers/MethodsMockTransformerTest.java @@ -18,15 +18,6 @@ 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; @@ -35,18 +26,26 @@ import org.powermock.core.transformers.mock.MockGatewaySpy; import org.powermock.core.transformers.support.DefaultMockTransformerChain; import org.powermock.reflect.internal.WhiteboxImpl; + +import java.lang.reflect.Method; +import java.util.ArrayList; + +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 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.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; import static org.powermock.core.transformers.mock.MockGatewaySpy.ConditionBuilder.registered; import static org.powermock.core.transformers.mock.MockGatewaySpy.methodCalls; @@ -54,11 +53,10 @@ 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; + + return new ArrayList<>( + MockTransformerTestHelper.createOneTransformerTestData(MockGatewaySpy.class, + StaticFinalNativeMethodMockTransformer.class)); } public MethodsMockTransformerTest(final TransformStrategy strategy, final MockTransformer transformer, @@ -77,7 +75,7 @@ public void should_skip_call_to_void_private_method_if_getaway_return_not_PROCEE WhiteboxImpl.invokeMethod(instance, "voidPrivateMethod", "name"); - assertThat(WhiteboxImpl.getInternalState(instance, "lname")) + assertThat((String) WhiteboxImpl.getInternalState(instance, "lname")) .as("Field name is not set") .isNull(); @@ -96,7 +94,7 @@ public void should_skip_call_to_void_public_method_if_getaway_return_not_PROCEED WhiteboxImpl.invokeMethod(instance, "voidMethod", "name", "field", 100d); - assertThat(WhiteboxImpl.getInternalState(instance, "field")) + assertThat((Object) WhiteboxImpl.getInternalState(instance, "field")) .as("Field name is not set") .isNull(); @@ -117,7 +115,7 @@ public void should_skip_call_to_final_void_public_method_if_getaway_return_not_P WhiteboxImpl.invokeMethod(instance, "finalVoidMethod", "name", "field", 100d); - assertThat(WhiteboxImpl.getInternalState(instance, "field")) + assertThat((Object) WhiteboxImpl.getInternalState(instance, "field")) .as("Field name is not set") .isNull(); @@ -138,7 +136,7 @@ public void should_invoke_real_final_void_public_method_if_getaway_return_PROCEE final String fieldValue = RandomString.make(10); WhiteboxImpl.invokeMethod(instance, "finalVoidMethod", "name", fieldValue, 100d); - assertThat(WhiteboxImpl.getInternalState(instance, "field")) + assertThat((Object) WhiteboxImpl.getInternalState(instance, "field")) .as("Field name is not set") .isEqualTo(fieldValue); @@ -244,14 +242,10 @@ public void should_return_real_method_return_value_for_final_non_void_methods_if } @Test - public void should_ignore_abstract_methods() throws Exception { + public void should_ignore_abstract_methods() { - final Throwable throwable = catchThrowable(new ThrowingCallable() { - @Override - public void call() throws Throwable { - loadWithMockClassLoader(AbstractMethodTestClass.class.getName()); - } - }); + final Throwable throwable = catchThrowable( + () -> loadWithMockClassLoader(AbstractMethodTestClass.class.getName())); assertThat(throwable) .as("Abstract class is transformed") @@ -315,7 +309,7 @@ public void should_ignore_call_to_synthetic_non_bridge_methods() throws Throwabl assertThat(methodCalls()) .isNot(registered().forMethod(SYNTHETIC_METHOD_NAME)); - assertThat(WhiteboxImpl.getInternalState(clazz, "syntheticMethodIsCalled")) + assertThat((Object) WhiteboxImpl.getInternalState(clazz, "syntheticMethodIsCalled")) .isEqualTo(true); } diff --git a/powermock-core/src/test/java/org/powermock/core/transformers/MockTransformerChainTest.java b/powermock-core/src/test/java/org/powermock/core/transformers/MockTransformerChainTest.java index f62a5608b..7e60583ef 100644 --- a/powermock-core/src/test/java/org/powermock/core/transformers/MockTransformerChainTest.java +++ b/powermock-core/src/test/java/org/powermock/core/transformers/MockTransformerChainTest.java @@ -22,7 +22,7 @@ import org.powermock.core.transformers.support.DefaultMockTransformerChain; import org.powermock.core.transformers.support.FilterPredicates; -import static org.assertj.core.api.Java6Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; public class MockTransformerChainTest { diff --git a/powermock-core/src/test/java/org/powermock/core/transformers/MockTransformerTestHelper.java b/powermock-core/src/test/java/org/powermock/core/transformers/MockTransformerTestHelper.java index b5487adb6..1dfa5ca3b 100644 --- a/powermock-core/src/test/java/org/powermock/core/transformers/MockTransformerTestHelper.java +++ b/powermock-core/src/test/java/org/powermock/core/transformers/MockTransformerTestHelper.java @@ -38,7 +38,7 @@ static Collection createTransformerTestData(final Class... transfor } static Collection createTransformerTestDataWithMockGateway(final Class mockGateway, final Class... transformerClass) { - List data = new ArrayList(); + List data = new ArrayList<>(); for (TransformStrategy strategy : TransformStrategy.values()) { List transformerChains = createTransformers(mockGateway, strategy, transformerClass); @@ -60,7 +60,7 @@ static Collection createOneTransformerTestData(final Class transfor } static Collection createOneTransformerTestData(final Class mockGateway, final Class transformerClass) { - List data = new ArrayList(); + List data = new ArrayList<>(); for (TransformStrategy strategy : TransformStrategy.values()) { MockTransformer transformer = getInstance(mockGateway, strategy, transformerClass); @@ -83,7 +83,7 @@ private static MockClassLoaderFactory createClassLoaderFactory(final Class tr } private static List createTransformers(final Class mockGateway, final TransformStrategy strategy, final Class... classes) { - List transformers = new ArrayList(); + List transformers = new ArrayList<>(); for (Class transformerClass : classes) { MockTransformer transformer = getInstance(mockGateway, strategy, transformerClass); diff --git a/powermock-core/src/test/java/org/powermock/core/transformers/NativeMethodsMockTransformerTest.java b/powermock-core/src/test/java/org/powermock/core/transformers/NativeMethodsMockTransformerTest.java index 9ef1ea78e..e2c394668 100644 --- a/powermock-core/src/test/java/org/powermock/core/transformers/NativeMethodsMockTransformerTest.java +++ b/powermock-core/src/test/java/org/powermock/core/transformers/NativeMethodsMockTransformerTest.java @@ -18,8 +18,6 @@ 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; @@ -27,15 +25,16 @@ import org.powermock.core.transformers.mock.MockGatewaySpy; import org.powermock.core.transformers.support.DefaultMockTransformerChain; import org.powermock.reflect.internal.WhiteboxImpl; + +import java.util.ArrayList; + +import net.bytebuddy.utility.RandomString; 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.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.powermock.core.transformers.mock.MockGatewaySpy.ConditionBuilder.registered; import static org.powermock.core.transformers.mock.MockGatewaySpy.methodCalls; @@ -43,11 +42,10 @@ public class NativeMethodsMockTransformerTest extends AbstractBaseMockTransforme @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; + + return new ArrayList<>( + MockTransformerTestHelper.createOneTransformerTestData(MockGatewaySpy.class, + StaticFinalNativeMethodMockTransformer.class)); } public NativeMethodsMockTransformerTest(final TransformStrategy strategy, final MockTransformer transformer, @@ -103,12 +101,9 @@ public void should_throw_UnsupportedOperationException_for_native_instance_if_it final String name = "name"; - assertThatThrownBy(new ThrowingCallable() { - @Override - public void call() throws Throwable { - final Object instance = WhiteboxImpl.newInstance(clazz); - WhiteboxImpl.invokeMethod(instance, "nativeReturnMethod", name); - } + assertThatThrownBy(() -> { + final Object instance = WhiteboxImpl.newInstance(clazz); + WhiteboxImpl.invokeMethod(instance, "nativeReturnMethod", name); }) .isExactlyInstanceOf(UnsupportedOperationException.class); } @@ -121,12 +116,7 @@ public void should_throw_UnsupportedOperationException_for_native_static_if_it_i final String name = "name"; - assertThatThrownBy(new ThrowingCallable() { - @Override - public void call() throws Throwable { - WhiteboxImpl.invokeMethod(clazz, "nativeStaticReturnMethod", name); - } - }) + assertThatThrownBy(() -> WhiteboxImpl.invokeMethod(clazz, "nativeStaticReturnMethod", name)) .isExactlyInstanceOf(UnsupportedOperationException.class); } @@ -152,12 +142,9 @@ public void should_throw_UnsupportedOperationException_for_native_method_of_pare final String name = "name"; - assertThatThrownBy(new ThrowingCallable() { - @Override - public void call() throws Throwable { - final Object instance = WhiteboxImpl.newInstance(clazz); - WhiteboxImpl.invokeMethod(instance, "nativeReturnMethod", name); - } + assertThatThrownBy(() -> { + final Object instance = WhiteboxImpl.newInstance(clazz); + WhiteboxImpl.invokeMethod(instance, "nativeReturnMethod", name); }) .isExactlyInstanceOf(UnsupportedOperationException.class); } diff --git a/powermock-core/src/test/java/org/powermock/core/transformers/StaticFinalFieldsMockTransformerTest.java b/powermock-core/src/test/java/org/powermock/core/transformers/StaticFinalFieldsMockTransformerTest.java index fe9f526f4..49f0c9ae5 100644 --- a/powermock-core/src/test/java/org/powermock/core/transformers/StaticFinalFieldsMockTransformerTest.java +++ b/powermock-core/src/test/java/org/powermock/core/transformers/StaticFinalFieldsMockTransformerTest.java @@ -23,15 +23,15 @@ 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 powermock.test.support.MainMockTransformerTestSupport.SupportClasses; 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.assertj.core.api.Assertions.assertThat; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.not; import static org.junit.Assume.assumeThat; @@ -40,11 +40,9 @@ public class StaticFinalFieldsMockTransformerTest extends AbstractBaseMockTransf @Parameterized.Parameters(name = "strategy: {0}, transformerType: {2}") public static Iterable data() { - Collection data = new ArrayList(); - - data.addAll(MockTransformerTestHelper.createTransformerTestData(StaticFinalFieldsMockTransformer.class)); - - return data; + + return new ArrayList<>( + MockTransformerTestHelper.createTransformerTestData(StaticFinalFieldsMockTransformer.class)); } public StaticFinalFieldsMockTransformerTest(final TransformStrategy strategy, diff --git a/powermock-core/src/test/java/org/powermock/core/transformers/StaticMethodsMockTransformerTest.java b/powermock-core/src/test/java/org/powermock/core/transformers/StaticMethodsMockTransformerTest.java index eff6f2b03..d5adbb6be 100644 --- a/powermock-core/src/test/java/org/powermock/core/transformers/StaticMethodsMockTransformerTest.java +++ b/powermock-core/src/test/java/org/powermock/core/transformers/StaticMethodsMockTransformerTest.java @@ -26,12 +26,12 @@ 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 powermock.test.support.MainMockTransformerTestSupport.StaticVoidMethodsTestClass; + +import static org.assertj.core.api.Assertions.assertThat; import static org.powermock.core.transformers.mock.MockGatewaySpy.ConditionBuilder.registered; import static org.powermock.core.transformers.mock.MockGatewaySpy.methodCalls; @@ -39,11 +39,10 @@ public class StaticMethodsMockTransformerTest extends AbstractBaseMockTransforme @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; + + return new ArrayList<>( + MockTransformerTestHelper.createOneTransformerTestData(MockGatewaySpy.class, + StaticFinalNativeMethodMockTransformer.class)); } public StaticMethodsMockTransformerTest(final TransformStrategy strategy, final MockTransformer transformer, @@ -60,7 +59,7 @@ public void should_skip_call_to_void_static_public_method_if_getaway_return_not_ WhiteboxImpl.invokeMethod(clazz, "voidMethod", "name", "field", 100d); - assertThat(WhiteboxImpl.getInternalState(clazz, "field")) + assertThat((Object) WhiteboxImpl.getInternalState(clazz, "field")) .as("Field name is not set") .isNull(); @@ -78,7 +77,7 @@ public void should_continue_executing_void_static_public_method_if_getaway_retur final String expectedFieldValue = "field"; WhiteboxImpl.invokeMethod(clazz, "voidMethod", "name", expectedFieldValue, 100d); - assertThat(WhiteboxImpl.getInternalState(clazz, "field")) + assertThat((Object) WhiteboxImpl.getInternalState(clazz, "field")) .as("Field name is not set") .isEqualTo(expectedFieldValue); diff --git a/powermock-core/src/test/java/org/powermock/core/transformers/SuppressStaticInitializerMockTransformerTest.java b/powermock-core/src/test/java/org/powermock/core/transformers/SuppressStaticInitializerMockTransformerTest.java index 1cfd6ef42..8b172dda7 100644 --- a/powermock-core/src/test/java/org/powermock/core/transformers/SuppressStaticInitializerMockTransformerTest.java +++ b/powermock-core/src/test/java/org/powermock/core/transformers/SuppressStaticInitializerMockTransformerTest.java @@ -18,7 +18,6 @@ package org.powermock.core.transformers; - import org.junit.Before; import org.junit.Test; import org.junit.runners.Parameterized; @@ -26,12 +25,12 @@ 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 powermock.test.support.MainMockTransformerTestSupport.StaticInitialization; + +import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.not; import static org.junit.Assume.assumeThat; @@ -41,11 +40,9 @@ public class SuppressStaticInitializerMockTransformerTest extends AbstractBaseMo @Parameterized.Parameters(name = "strategy: {0}, transformerType: {2}") public static Iterable data() { - Collection data = new ArrayList(); - - data.addAll(MockTransformerTestHelper.createTransformerTestData(SuppressStaticInitializerMockTransformer.class)); - - return data; + + return new ArrayList<>( + MockTransformerTestHelper.createTransformerTestData(SuppressStaticInitializerMockTransformer.class)); } public SuppressStaticInitializerMockTransformerTest( @@ -56,6 +53,7 @@ public SuppressStaticInitializerMockTransformerTest( super(strategy, mockTransformerChain, mockClassloaderFactory); } + @Override @Before public void setUp() throws Exception { super.setUp(); diff --git a/powermock-core/src/test/java/org/powermock/core/transformers/TestClassTransformerTest.java b/powermock-core/src/test/java/org/powermock/core/transformers/TestClassTransformerTest.java index cd93cc743..a654e7058 100644 --- a/powermock-core/src/test/java/org/powermock/core/transformers/TestClassTransformerTest.java +++ b/powermock-core/src/test/java/org/powermock/core/transformers/TestClassTransformerTest.java @@ -16,7 +16,6 @@ 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; @@ -27,9 +26,6 @@ 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; @@ -37,11 +33,15 @@ import java.util.Collections; import java.util.List; +import powermock.test.support.MainMockTransformerTestSupport.SupportClasses; +import powermock.test.support.TestWithTwoTestMethods; +import powermock.test.support.TestWithTwoTestMethods.NestedTestWithTwoTestMethods; + 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.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertEquals; import static org.junit.Assume.assumeTrue; @@ -57,7 +57,7 @@ public class TestClassTransformerTest { @Parameterized.Parameters(name = "{0}-{1}") public static List values() { - final List values = new ArrayList(); + final List values = new ArrayList<>(); for (ByteCodeFramework byteCodeFramework : ByteCodeFramework.values()) { for (MockClassLoaderCase eachFactoryAlternative : MockClassLoaderCase.values()) { @@ -85,14 +85,7 @@ public void should_make_defer_constructor_non_public_for_inner_classes() throws .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.") + assertThatThrownBy(() -> clazz.getConstructor(IndicateReloadClass.class)).withFailMessage("A public defer-constructor still presents.") .isExactlyInstanceOf(NoSuchMethodException.class); assertThat(clazz.getConstructors()) @@ -217,7 +210,7 @@ MockClassLoader createMockClassLoaderThatPrepare(Class prepare4test, final By final MockTransformer testClassTransformer = TestClassTransformerBuilder .forTestClass(testClass) .removesTestMethodAnnotation(Test.class) - .fromMethods(new ArrayList(methodsToRemoveAnnotations)); + .fromMethods(new ArrayList<>(methodsToRemoveAnnotations)); return MockClassLoaderBuilder.create(bytecodeFramework) .forTestClass(testClass) diff --git a/powermock-core/src/test/java/org/powermock/core/transformers/javassist/TestPrimitives.java b/powermock-core/src/test/java/org/powermock/core/transformers/javassist/TestPrimitives.java index b70c3dcc2..32ada3fa2 100644 --- a/powermock-core/src/test/java/org/powermock/core/transformers/javassist/TestPrimitives.java +++ b/powermock-core/src/test/java/org/powermock/core/transformers/javassist/TestPrimitives.java @@ -15,17 +15,19 @@ */ 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; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.List; + +import javassist.CtClass; +import javassist.CtPrimitiveType; + @RunWith(Parameterized.class) public class TestPrimitives { @@ -37,7 +39,7 @@ public TestPrimitives(CtPrimitiveType ctType) { @Parameterized.Parameters(name = "{0}") public static List values() throws Exception { - List valuesList = new ArrayList(); + List valuesList = new ArrayList<>(); for (Field f : CtClass.class.getFields()) { if (CtClass.class.isAssignableFrom(f.getType())) { valuesList.add(new Object[] {f.get(null)}); diff --git a/powermock-core/src/test/java/org/powermock/core/transformers/mock/MockGatewaySpy.java b/powermock-core/src/test/java/org/powermock/core/transformers/mock/MockGatewaySpy.java index e8fb03a6a..b25e45fea 100644 --- a/powermock-core/src/test/java/org/powermock/core/transformers/mock/MockGatewaySpy.java +++ b/powermock-core/src/test/java/org/powermock/core/transformers/mock/MockGatewaySpy.java @@ -14,11 +14,11 @@ public class MockGatewaySpy { private static final String ANY = "$*$"; - private static Map returnOnMethodCall = new HashMap(); + 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(); + 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(); @@ -87,11 +87,11 @@ public static List constructorCalls() { } public static void returnOnMethodCall(final Object expected) { - MockGatewaySpy.returnOnMethodCall.put(ANY, expected); + returnOnMethodCall.put(ANY, expected); } public static void returnOnMethodCall(final String methodName, final Object expected) { - MockGatewaySpy.returnOnMethodCall.put(methodName, expected); + returnOnMethodCall.put(methodName, expected); } public static void clear() { @@ -110,7 +110,7 @@ public static class MethodCall { @Override public String toString() { - final StringBuffer sb = new StringBuffer("MethodCall{\n"); + final StringBuilder sb = new StringBuilder("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('\''); diff --git a/powermock-core/src/test/java/org/powermock/tests/utils/impl/PowerMockIgnorePackagesExtractorImplTest.java b/powermock-core/src/test/java/org/powermock/tests/utils/impl/PowerMockIgnorePackagesExtractorImplTest.java index 90c47489d..03e1fbfb4 100644 --- a/powermock-core/src/test/java/org/powermock/tests/utils/impl/PowerMockIgnorePackagesExtractorImplTest.java +++ b/powermock-core/src/test/java/org/powermock/tests/utils/impl/PowerMockIgnorePackagesExtractorImplTest.java @@ -24,7 +24,7 @@ import org.powermock.configuration.PowerMockConfiguration; import org.powermock.core.classloader.annotations.PowerMockIgnore; -import static org.assertj.core.api.Java6Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; @SuppressWarnings("unchecked") public class PowerMockIgnorePackagesExtractorImplTest { diff --git a/powermock-core/src/test/java/org/powermock/tests/utils/impl/PrepareForTestExtractorImplTest.java b/powermock-core/src/test/java/org/powermock/tests/utils/impl/PrepareForTestExtractorImplTest.java index 6267b8212..4b45a104f 100644 --- a/powermock-core/src/test/java/org/powermock/tests/utils/impl/PrepareForTestExtractorImplTest.java +++ b/powermock-core/src/test/java/org/powermock/tests/utils/impl/PrepareForTestExtractorImplTest.java @@ -42,7 +42,7 @@ public class PrepareForTestExtractorImplTest { @Test public void assertThatInterfacesWorks() throws Exception { final PrepareForTestExtractorImpl tested = new PrepareForTestExtractorImpl(); - final Set hashSet = new HashSet(); + final Set hashSet = new HashSet<>(); Whitebox.invokeMethod(tested, "addClassHierarchy", hashSet, Serializable.class); assertEquals(1, hashSet.size()); assertEquals(Serializable.class.getName(), hashSet.iterator().next()); diff --git a/powermock-core/src/test/java/org/powermock/utils/JavaVersionTest.java b/powermock-core/src/test/java/org/powermock/utils/JavaVersionTest.java deleted file mode 100644 index 9f9a99810..000000000 --- a/powermock-core/src/test/java/org/powermock/utils/JavaVersionTest.java +++ /dev/null @@ -1,16 +0,0 @@ -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(); - } - -} \ No newline at end of file diff --git a/powermock-core/src/test/java/org/powermock/utils/NumberUtilsTest.java b/powermock-core/src/test/java/org/powermock/utils/NumberUtilsTest.java index c62de2db3..f7d8e84f0 100644 --- a/powermock-core/src/test/java/org/powermock/utils/NumberUtilsTest.java +++ b/powermock-core/src/test/java/org/powermock/utils/NumberUtilsTest.java @@ -3,7 +3,7 @@ import org.assertj.core.data.Offset; import org.junit.Test; -import static org.assertj.core.api.Java6Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; public class NumberUtilsTest { diff --git a/powermock-core/src/test/java/powermock/test/support/MainMockTransformerTestSupport.java b/powermock-core/src/test/java/powermock/test/support/MainMockTransformerTestSupport.java index 245de1868..a4d8ab04a 100644 --- a/powermock-core/src/test/java/powermock/test/support/MainMockTransformerTestSupport.java +++ b/powermock-core/src/test/java/powermock/test/support/MainMockTransformerTestSupport.java @@ -17,6 +17,7 @@ package powermock.test.support; import org.powermock.core.classloader.MockClassLoaderConfiguration; + import powermock.test.support.MainMockTransformerTestSupport.ConstructorCall.SupperClassThrowsException; /** diff --git a/powermock-modules/powermock-module-javaagent/src/main/java/com/sun/tools/attach/VirtualMachine.java b/powermock-modules/powermock-module-javaagent/src/main/java/com/sun/tools/attach/VirtualMachine.java index 04808e1dd..359b30af2 100644 --- a/powermock-modules/powermock-module-javaagent/src/main/java/com/sun/tools/attach/VirtualMachine.java +++ b/powermock-modules/powermock-module-javaagent/src/main/java/com/sun/tools/attach/VirtualMachine.java @@ -24,13 +24,13 @@ */ 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; +import com.sun.tools.attach.spi.AttachProvider; + /** *

* A Java virtual machine. @@ -48,7 +48,7 @@ * 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 + * 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} @@ -62,7 +62,7 @@ * href="../../../../../../../../technotes/guides/jvmti/index.html">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. + * {@link 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. @@ -113,10 +113,10 @@ protected VirtualMachine(AttachProvider provider, String id) * Return a list of Java virtual machines. *

*

- * This method returns a list of Java {@link com.sun.tools.attach.VirtualMachineDescriptor} + * This method returns a list of Java {@link 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 + * invoking the {@link AttachProvider#listVirtualMachines + * listVirtualMachines} method of all installed {@link AttachProvider * attach providers}. If there are no Java virtual machines known to any provider then an empty * list is returned. *

@@ -124,7 +124,7 @@ protected VirtualMachine(AttachProvider provider, String id) */ public static List list() { - List l = new ArrayList(); + List l = new ArrayList<>(); List providers = AttachProvider.providers(); for (AttachProvider provider : providers) { @@ -140,27 +140,27 @@ public static List list() *

*

* This method obtains the list of attach providers by invoking the - * {@link com.sun.tools.attach.spi.AttachProvider#providers() AttachProvider.providers()} method. + * {@link 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) + * AttachProvider#attachVirtualMachine(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} + * {@link 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() + * {@link 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} + * {@link AttachPermission AttachPermission} * ("attachVirtualMachine"), or another permission * required by the implementation. * @throws IOException If an I/O error occurs @@ -185,10 +185,10 @@ public static VirtualMachine attach(String id) throws AttachNotSupportedExceptio /** * Attaches to a Java virtual machine. *

- * This method first invokes the {@link com.sun.tools.attach.VirtualMachineDescriptor#provider() + * This method first invokes the {@link 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) + * AttachProvider#attachVirtualMachine(VirtualMachineDescriptor) * attachVirtualMachine} to attach to the target VM. * * @param vmd The virtual machine descriptor. @@ -197,7 +197,7 @@ public static VirtualMachine attach(String id) throws AttachNotSupportedExceptio * * @throws SecurityException * If a security manager has been installed and it denies - * {@link com.sun.tools.attach.AttachPermission AttachPermission} + * {@link AttachPermission AttachPermission} * ("attachVirtualMachine"), or another permission * required by the implementation. * @@ -219,7 +219,7 @@ public static VirtualMachine attach(VirtualMachineDescriptor 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 + * operations on that virtual machine will cause an {@link 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 @@ -270,10 +270,10 @@ public final String id() * 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 + * an error then an {@link 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} + * AgentInitializationException#returnValue() returnValue} * method on the exception. * * @param agentLibrary The name of the agent library. @@ -284,7 +284,7 @@ public final String id() * @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() + * @see AgentInitializationException#returnValue() */ public abstract void loadAgentLibrary(String agentLibrary, String options) throws AgentLoadException, AgentInitializationException, IOException; @@ -331,10 +331,10 @@ public void loadAgentLibrary(String agentLibrary) * 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 + * an error then an {@link 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} + * AgentInitializationException#returnValue() returnValue} * method on the exception. * * @param agentPath The full path of the agent library. @@ -345,7 +345,7 @@ public void loadAgentLibrary(String agentLibrary) * @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() + * @see AgentInitializationException#returnValue() */ public abstract void loadAgentPath(String agentPath, String options) throws AgentLoadException, AgentInitializationException, IOException; @@ -425,7 +425,7 @@ public void loadAgent(String agent) * 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} + * method {@link 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. *

@@ -437,7 +437,7 @@ public void loadAgent(String agent) * * @return The system properties * @throws IOException If an I/O error occurs - * @see java.lang.System#getProperties + * @see System#getProperties * @see #loadAgentLibrary * @see #loadAgent */ diff --git a/powermock-modules/powermock-module-javaagent/src/main/java/com/sun/tools/attach/VirtualMachineDescriptor.java b/powermock-modules/powermock-module-javaagent/src/main/java/com/sun/tools/attach/VirtualMachineDescriptor.java index db29e2991..bf837cdea 100644 --- a/powermock-modules/powermock-module-javaagent/src/main/java/com/sun/tools/attach/VirtualMachineDescriptor.java +++ b/powermock-modules/powermock-module-javaagent/src/main/java/com/sun/tools/attach/VirtualMachineDescriptor.java @@ -32,7 +32,7 @@ *

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 + * 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 @@ -50,7 +50,7 @@ * 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}. + * AttachProvider attach providers}. * * @since 1.6 */ @@ -96,7 +96,7 @@ public VirtualMachineDescriptor(AttachProvider provider, String id, String displ * three-argument constructor as follows: *

*

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

@@ -187,10 +187,7 @@ public boolean equals(Object ob) if (other.provider() != this.provider()) { return false; } - if (!other.id().equals(this.id())) { - return false; - } - return true; + return other.id().equals(this.id()); } /** diff --git a/powermock-modules/powermock-module-javaagent/src/main/java/com/sun/tools/attach/spi/AttachProvider.java b/powermock-modules/powermock-module-javaagent/src/main/java/com/sun/tools/attach/spi/AttachProvider.java index b5d956a3d..7751ef2f4 100644 --- a/powermock-modules/powermock-module-javaagent/src/main/java/com/sun/tools/attach/spi/AttachProvider.java +++ b/powermock-modules/powermock-module-javaagent/src/main/java/com/sun/tools/attach/spi/AttachProvider.java @@ -24,16 +24,16 @@ */ 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; +import com.sun.tools.attach.AttachNotSupportedException; +import com.sun.tools.attach.VirtualMachine; +import com.sun.tools.attach.VirtualMachineDescriptor; + /** *

* Attach provider class for attaching to a Java virtual machine. @@ -105,7 +105,7 @@ protected AttachProvider() {} *

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} + * 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 @@ -135,9 +135,9 @@ public abstract VirtualMachine attachVirtualMachine(String id) *

*

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

@@ -149,7 +149,7 @@ public abstract VirtualMachine attachVirtualMachine(String id) * ("attachVirtualMachine"), or other permission * required by the implementation. * @throws AttachNotSupportedException If the descriptor's {@link - * com.sun.tools.attach.VirtualMachineDescriptor#provider() provider()} method + * 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 @@ -169,7 +169,7 @@ public VirtualMachine attachVirtualMachine(VirtualMachineDescriptor vmd) * Lists the Java virtual machines known to this provider. *

*

- * This method returns a list of {@link com.sun.tools.attach.VirtualMachineDescriptor} elements. + * This method returns a list of {@link 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) @@ -189,7 +189,7 @@ public VirtualMachine attachVirtualMachine(VirtualMachineDescriptor vmd) *

    *
  • 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 + * to be, the {@link ClassLoader#getSystemClassLoader system * class loader}).

  • *
  • The JAR file contains a provider configuration named * com.sun.tools.attach.spi.AttachProvider in the resource directory @@ -215,7 +215,7 @@ public VirtualMachine attachVirtualMachine(VirtualMachineDescriptor vmd) public static List providers() { synchronized (lock) { if (providers == null) { - providers = new ArrayList(); + providers = new ArrayList<>(); ServiceLoader providerLoader = ServiceLoader.load(AttachProvider.class, AttachProvider.class.getClassLoader()); diff --git a/powermock-modules/powermock-module-javaagent/src/main/java/org/powermock/modules/agent/AbstractClassTransformer.java b/powermock-modules/powermock-module-javaagent/src/main/java/org/powermock/modules/agent/AbstractClassTransformer.java index 8a699c24d..d98266d30 100644 --- a/powermock-modules/powermock-module-javaagent/src/main/java/org/powermock/modules/agent/AbstractClassTransformer.java +++ b/powermock-modules/powermock-module-javaagent/src/main/java/org/powermock/modules/agent/AbstractClassTransformer.java @@ -24,8 +24,8 @@ public abstract class AbstractClassTransformer { - private static final List ALWAYS_IGNORED = new LinkedList(); - private final List USER_IGNORED = Collections.synchronizedList(new LinkedList()); + private static final List ALWAYS_IGNORED = new LinkedList<>(); + private final List USER_IGNORED = Collections.synchronizedList(new LinkedList<>()); static { ALWAYS_IGNORED.add("org.powermock.*"); @@ -57,7 +57,7 @@ protected boolean shouldIgnore(String className) { } private List merge(List userIgnored) { - List list = new LinkedList(AbstractClassTransformer.ALWAYS_IGNORED); + List list = new LinkedList<>(ALWAYS_IGNORED); list.addAll(userIgnored); return Collections.unmodifiableList(list); } diff --git a/powermock-modules/powermock-module-javaagent/src/main/java/org/powermock/modules/agent/AgentInitialization.java b/powermock-modules/powermock-module-javaagent/src/main/java/org/powermock/modules/agent/AgentInitialization.java index 55c643723..d55655aa3 100644 --- a/powermock-modules/powermock-module-javaagent/src/main/java/org/powermock/modules/agent/AgentInitialization.java +++ b/powermock-modules/powermock-module-javaagent/src/main/java/org/powermock/modules/agent/AgentInitialization.java @@ -33,20 +33,9 @@ final class AgentInitialization { private static final Pattern JAR_REGEX = Pattern.compile(".*powermock-module-javaagent[-]?[.\\d+]*[-]?[A-Z]*.jar"); - void initializeAccordingToJDKVersion() { + void initialize() { 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."); - } + new AgentLoader(jarFilePath).loadAgent(); } private String discoverPathToJarFile() diff --git a/powermock-modules/powermock-module-javaagent/src/main/java/org/powermock/modules/agent/AgentLoader.java b/powermock-modules/powermock-module-javaagent/src/main/java/org/powermock/modules/agent/AgentLoader.java index 6b96bc575..89ae74ceb 100644 --- a/powermock-modules/powermock-module-javaagent/src/main/java/org/powermock/modules/agent/AgentLoader.java +++ b/powermock-modules/powermock-module-javaagent/src/main/java/org/powermock/modules/agent/AgentLoader.java @@ -23,23 +23,24 @@ */ package org.powermock.modules.agent; +import org.powermock.reflect.Whitebox; + +import java.io.File; +import java.io.IOException; +import java.lang.management.ManagementFactory; +import java.util.List; + 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 @@ -134,9 +135,7 @@ private VirtualMachine getVirtualMachineImplementationFromEmbeddedOnes() { private VirtualMachine attachToThisVM() { try { return VirtualMachine.attach(pid); - } catch (AttachNotSupportedException e) { - throw new RuntimeException(e); - } catch (IOException e) { + } catch (AttachNotSupportedException | IOException e) { throw new RuntimeException(e); } } @@ -145,11 +144,7 @@ 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) { + } catch (AgentLoadException | AgentInitializationException | IOException e) { throw new RuntimeException(e); } } diff --git a/powermock-modules/powermock-module-javaagent/src/main/java/org/powermock/modules/agent/DefinalizingClassTransformer.java b/powermock-modules/powermock-module-javaagent/src/main/java/org/powermock/modules/agent/DefinalizingClassTransformer.java index e8eef7ab1..9877b4fa2 100644 --- a/powermock-modules/powermock-module-javaagent/src/main/java/org/powermock/modules/agent/DefinalizingClassTransformer.java +++ b/powermock-modules/powermock-module-javaagent/src/main/java/org/powermock/modules/agent/DefinalizingClassTransformer.java @@ -16,15 +16,16 @@ 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; +import net.bytebuddy.jar.asm.ClassReader; +import net.bytebuddy.jar.asm.ClassWriter; + public class DefinalizingClassTransformer extends AbstractClassTransformer implements ClassFileTransformer { private static final int NO_FLAGS_OR_OPTIONS = 0; + @Override public byte[] transform(ClassLoader loader, String className, Class classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) { if (loader == null || shouldIgnore(className)) { return null; diff --git a/powermock-modules/powermock-module-javaagent/src/main/java/org/powermock/modules/agent/PowerMockAgent.java b/powermock-modules/powermock-module-javaagent/src/main/java/org/powermock/modules/agent/PowerMockAgent.java index 0b55c6802..c6960c368 100644 --- a/powermock-modules/powermock-module-javaagent/src/main/java/org/powermock/modules/agent/PowerMockAgent.java +++ b/powermock-modules/powermock-module-javaagent/src/main/java/org/powermock/modules/agent/PowerMockAgent.java @@ -23,8 +23,6 @@ */ package org.powermock.modules.agent; -import org.powermock.utils.JavaVersion; - import java.io.IOException; import java.lang.instrument.Instrumentation; @@ -35,11 +33,7 @@ * * @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); +public final class PowerMockAgent { private static final PowerMockClassTransformer classTransformer = new PowerMockClassTransformer(); @@ -80,7 +74,7 @@ public static Instrumentation instrumentation() { public static void verifyInitialization() { if (instrumentation == null) { - new AgentInitialization().initializeAccordingToJDKVersion(); + new AgentInitialization().initialize(); } } @@ -88,7 +82,7 @@ public static boolean initializeIfNeeded() { if (instrumentation == null) { try { - new AgentInitialization().initializeAccordingToJDKVersion(); + new AgentInitialization().initialize(); return true; } catch (RuntimeException e) { @@ -99,10 +93,4 @@ public static boolean initializeIfNeeded() return false; } - - public static void initializeIfPossible() { - if (jdk6OrLater) { - initializeIfNeeded(); - } - } } diff --git a/powermock-modules/powermock-module-javaagent/src/main/java/org/powermock/modules/agent/PowerMockClassTransformer.java b/powermock-modules/powermock-module-javaagent/src/main/java/org/powermock/modules/agent/PowerMockClassTransformer.java index 092cf5d9e..89686ef39 100644 --- a/powermock-modules/powermock-module-javaagent/src/main/java/org/powermock/modules/agent/PowerMockClassTransformer.java +++ b/powermock-modules/powermock-module-javaagent/src/main/java/org/powermock/modules/agent/PowerMockClassTransformer.java @@ -17,8 +17,6 @@ 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; @@ -36,6 +34,9 @@ import java.util.HashSet; import java.util.Set; +import javassist.ClassPool; +import javassist.CtClass; + class PowerMockClassTransformer extends AbstractClassTransformer implements ClassFileTransformer { private static final MockTransformerChain MOCK_TRANSFORMER_CHAIN = new JavassistMockTransformerChainFactory() @@ -50,13 +51,14 @@ class PowerMockClassTransformer extends AbstractClassTransformer implements Clas } public void setClassesToTransform(Collection classesToTransform) { - this.classesToTransform = new HashSet(classesToTransform); + this.classesToTransform = new HashSet<>(classesToTransform); } public void setJavaAgentClassRegister(JavaAgentClassRegister javaAgentClassRegister) { this.javaAgentClassRegister = javaAgentClassRegister; } + @Override public byte[] transform( ClassLoader loader, String className, Class classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer @@ -95,12 +97,9 @@ public byte[] transform( private CtClass getCtClass(final byte[] classfileBuffer) throws IOException { final CtClass ctClass; - - ByteArrayInputStream is = new ByteArrayInputStream(classfileBuffer); - try { + + try (ByteArrayInputStream is = new ByteArrayInputStream(classfileBuffer)) { ctClass = ClassPool.getDefault().makeClass(is); - } finally { - is.close(); } return ctClass; } diff --git a/powermock-modules/powermock-module-javaagent/src/main/java/org/powermock/modules/agent/support/JavaAgentClassRegisterImpl.java b/powermock-modules/powermock-module-javaagent/src/main/java/org/powermock/modules/agent/support/JavaAgentClassRegisterImpl.java index 09b22c1cd..06c50abd1 100644 --- a/powermock-modules/powermock-module-javaagent/src/main/java/org/powermock/modules/agent/support/JavaAgentClassRegisterImpl.java +++ b/powermock-modules/powermock-module-javaagent/src/main/java/org/powermock/modules/agent/support/JavaAgentClassRegisterImpl.java @@ -32,7 +32,7 @@ public class JavaAgentClassRegisterImpl implements JavaAgentClassRegister { private final Map> modifiedClasses; public JavaAgentClassRegisterImpl() { - modifiedClasses = new HashMap>(); + modifiedClasses = new HashMap<>(); } @Override @@ -42,15 +42,7 @@ public boolean isModifiedByAgent(ClassLoader classLoader, String 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); - + modifiedClasses.computeIfAbsent(loader, k -> new HashSet<>()).add(className); } @Override diff --git a/powermock-modules/powermock-module-javaagent/src/main/java/sun/tools/attach/BsdVirtualMachine.java b/powermock-modules/powermock-module-javaagent/src/main/java/sun/tools/attach/BsdVirtualMachine.java index 2b43f7c8c..68435b0e5 100644 --- a/powermock-modules/powermock-module-javaagent/src/main/java/sun/tools/attach/BsdVirtualMachine.java +++ b/powermock-modules/powermock-module-javaagent/src/main/java/sun/tools/attach/BsdVirtualMachine.java @@ -24,13 +24,14 @@ */ 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; +import java.nio.charset.StandardCharsets; + +import com.sun.tools.attach.AgentLoadException; +import com.sun.tools.attach.AttachNotSupportedException; +import com.sun.tools.attach.spi.AttachProvider; /* * Bsd implementation of HotSpotVirtualMachine @@ -226,7 +227,7 @@ public SocketInputStream(int s) { @Override public synchronized int read() throws IOException { - byte b[] = new byte[1]; + byte[] b = new byte[1]; int n = this.read(b, 0, 1); if (n == 1) { return b[0] & 0xff; @@ -266,15 +267,11 @@ private String findSocketFile(int pid) { */ 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; + b = s.getBytes(StandardCharsets.UTF_8); + write(fd, b, 0, b.length); } - byte b[] = new byte[1]; + byte[] b = new byte[1]; b[0] = 0; write(fd, b, 0, 1); } @@ -292,9 +289,9 @@ private void writeString(int fd, String s) 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 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 write(int fd, byte[] buf, int off, int bufLen) throws IOException; static native void createAttachFile(String path); diff --git a/powermock-modules/powermock-module-javaagent/src/main/java/sun/tools/attach/HotSpotVirtualMachine.java b/powermock-modules/powermock-module-javaagent/src/main/java/sun/tools/attach/HotSpotVirtualMachine.java index 5835e0e3e..54ff8fbd7 100644 --- a/powermock-modules/powermock-module-javaagent/src/main/java/sun/tools/attach/HotSpotVirtualMachine.java +++ b/powermock-modules/powermock-module-javaagent/src/main/java/sun/tools/attach/HotSpotVirtualMachine.java @@ -25,15 +25,15 @@ package sun.tools.attach; +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + 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. */ @@ -54,18 +54,11 @@ public abstract class HotSpotVirtualMachine extends VirtualMachine { private void loadAgentLibrary(String agentLibrary, boolean isAbsolute, String options) throws AgentLoadException, AgentInitializationException, IOException { - InputStream in = execute("load", - agentLibrary, - isAbsolute ? "true" : "false", - options); - try { + try (InputStream in = execute("load", agentLibrary, isAbsolute ? "true" : "false", options)) { int result = readInt(in); if (result != 0) { throw new AgentInitializationException("Agent_OnAttach failed", result); } - } finally { - in.close(); - } } @@ -235,7 +228,7 @@ int readInt(InputStream in) throws IOException { // read to \n or EOF int n; - byte buf[] = new byte[1]; + byte[] buf = new byte[1]; do { n = in.read(buf, 0, 1); if (n > 0) { @@ -279,8 +272,7 @@ final long attachTimeout() { String s = System.getProperty("sun.tools.attach.attachTimeout"); attachTimeout = Long.parseLong(s); - } catch (SecurityException se) { - } catch (NumberFormatException ne) { + } catch (SecurityException | NumberFormatException se) { } if (attachTimeout <= 0) { attachTimeout = defaultAttachTimeout; diff --git a/powermock-modules/powermock-module-javaagent/src/main/java/sun/tools/attach/LinuxVirtualMachine.java b/powermock-modules/powermock-module-javaagent/src/main/java/sun/tools/attach/LinuxVirtualMachine.java index 485e84967..b02e6947b 100644 --- a/powermock-modules/powermock-module-javaagent/src/main/java/sun/tools/attach/LinuxVirtualMachine.java +++ b/powermock-modules/powermock-module-javaagent/src/main/java/sun/tools/attach/LinuxVirtualMachine.java @@ -24,13 +24,14 @@ */ 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; +import java.nio.charset.StandardCharsets; + +import com.sun.tools.attach.AgentLoadException; +import com.sun.tools.attach.AttachNotSupportedException; +import com.sun.tools.attach.spi.AttachProvider; /* * Linux implementation of HotSpotVirtualMachine @@ -242,7 +243,7 @@ public SocketInputStream(int s) { @Override public synchronized int read() throws IOException { - byte b[] = new byte[1]; + byte[] b = new byte[1]; int n = this.read(b, 0, 1); if (n == 1) { return b[0] & 0xff; @@ -300,15 +301,11 @@ private File createAttachFile(int pid) throws IOException { */ 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; + b = s.getBytes(StandardCharsets.UTF_8); + write(fd, b, 0, b.length); } - byte b[] = new byte[1]; + byte[] b = new byte[1]; b[0] = 0; write(fd, b, 0, 1); } @@ -332,9 +329,9 @@ private void writeString(int fd, String s) 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 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 write(int fd, byte[] buf, int off, int bufLen) throws IOException; static { System.loadLibrary("attach"); diff --git a/powermock-modules/powermock-module-javaagent/src/main/java/sun/tools/attach/SolarisVirtualMachine.java b/powermock-modules/powermock-module-javaagent/src/main/java/sun/tools/attach/SolarisVirtualMachine.java index f2fcdd722..760ac4248 100644 --- a/powermock-modules/powermock-module-javaagent/src/main/java/sun/tools/attach/SolarisVirtualMachine.java +++ b/powermock-modules/powermock-module-javaagent/src/main/java/sun/tools/attach/SolarisVirtualMachine.java @@ -24,15 +24,15 @@ */ 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; +import com.sun.tools.attach.AgentLoadException; +import com.sun.tools.attach.AttachNotSupportedException; +import com.sun.tools.attach.spi.AttachProvider; + /* * Solaris implementation of HotSpotVirtualMachine. */ @@ -170,7 +170,7 @@ public SocketInputStream(int s) { @Override public synchronized int read() throws IOException { - byte b[] = new byte[1]; + byte[] b = new byte[1]; int n = this.read(b, 0, 1); if (n == 1) { return b[0] & 0xff; @@ -198,7 +198,7 @@ public void close() throws IOException { // The door is attached to .java_pid in the temporary directory. private int openDoor(int pid) throws IOException { - String path = tmpdir + "/.java_pid" + pid;; + String path = tmpdir + "/.java_pid" + pid; fd = open(path); // Check that the file owner/permission to avoid attaching to @@ -235,7 +235,7 @@ private File createAttachFile(int pid) 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 int read(int fd, byte[] buf, int off, int buflen) throws IOException; static native void checkPermissions(String path) throws IOException; diff --git a/powermock-modules/powermock-module-javaagent/src/main/java/sun/tools/attach/WindowsVirtualMachine.java b/powermock-modules/powermock-module-javaagent/src/main/java/sun/tools/attach/WindowsVirtualMachine.java index b48df46fd..2ee6ff377 100644 --- a/powermock-modules/powermock-module-javaagent/src/main/java/sun/tools/attach/WindowsVirtualMachine.java +++ b/powermock-modules/powermock-module-javaagent/src/main/java/sun/tools/attach/WindowsVirtualMachine.java @@ -24,14 +24,14 @@ */ 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; +import com.sun.tools.attach.AgentLoadException; +import com.sun.tools.attach.AttachNotSupportedException; +import com.sun.tools.attach.spi.AttachProvider; + public class WindowsVirtualMachine extends HotSpotVirtualMachine { // the enqueue code stub (copied into each target VM) @@ -132,7 +132,7 @@ public PipedInputStream(long hPipe) { @Override public synchronized int read() throws IOException { - byte b[] = new byte[1]; + byte[] b = new byte[1]; int n = this.read(b, 0, 1); if (n == 1) { return b[0] & 0xff; @@ -149,13 +149,13 @@ public synchronized int read(byte[] bs, int off, int len) throws IOException { } else if (len == 0) return 0; - return WindowsVirtualMachine.readPipe(hPipe, bs, off, len); + return readPipe(hPipe, bs, off, len); } @Override public void close() throws IOException { if (hPipe != -1) { - WindowsVirtualMachine.closePipe(hPipe); + closePipe(hPipe); hPipe = -1; } } @@ -178,7 +178,7 @@ public void close() 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 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; diff --git a/powermock-modules/powermock-module-junit4-common/src/main/java/org/powermock/modules/junit4/common/internal/impl/JUnit4TestMethodChecker.java b/powermock-modules/powermock-module-junit4-common/src/main/java/org/powermock/modules/junit4/common/internal/impl/JUnit4TestMethodChecker.java index c20ea1c15..5d0175df0 100644 --- a/powermock-modules/powermock-module-junit4-common/src/main/java/org/powermock/modules/junit4/common/internal/impl/JUnit4TestMethodChecker.java +++ b/powermock-modules/powermock-module-junit4-common/src/main/java/org/powermock/modules/junit4/common/internal/impl/JUnit4TestMethodChecker.java @@ -17,11 +17,9 @@ 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; /** * diff --git a/powermock-modules/powermock-module-junit4-common/src/main/java/org/powermock/modules/junit4/common/internal/impl/JUnit4TestSuiteChunkerImpl.java b/powermock-modules/powermock-module-junit4-common/src/main/java/org/powermock/modules/junit4/common/internal/impl/JUnit4TestSuiteChunkerImpl.java index fa210b5b3..e4bd16adc 100644 --- a/powermock-modules/powermock-module-junit4-common/src/main/java/org/powermock/modules/junit4/common/internal/impl/JUnit4TestSuiteChunkerImpl.java +++ b/powermock-modules/powermock-module-junit4-common/src/main/java/org/powermock/modules/junit4/common/internal/impl/JUnit4TestSuiteChunkerImpl.java @@ -93,12 +93,12 @@ public void run(RunNotifier notifier) { final PowerMockTestListener[] powerMockTestListeners = (PowerMockTestListener[]) getPowerMockTestListenersLoadedByASpecificClassLoader( testClass, this.getClass().getClassLoader()); - final Set allMethods = new LinkedHashSet(); + final Set allMethods = new LinkedHashSet<>(); for (TestChunk testChunk : getTestChunks()) { allMethods.addAll(testChunk.getTestMethodsToBeExecutedByThisClassloader()); } - final Method[] allMethodsAsArray = allMethods.toArray(new Method[allMethods.size()]); + final Method[] allMethodsAsArray = allMethods.toArray(new Method[0]); final PowerMockTestNotifier powerMockTestNotifier = new PowerMockTestNotifierImpl(powerMockTestListeners); powerMockTestNotifier.notifyBeforeTestSuiteStarted(testClass, allMethodsAsArray); @@ -146,7 +146,7 @@ protected Class testMethodAnnotation() { protected PowerMockJUnitRunnerDelegate createDelegatorFromClassloader(ClassLoader classLoader, Class testClass, final List methodsToTest) throws Exception { - Set methodNames = new HashSet(); + Set methodNames = new HashSet<>(); for (Method method : methodsToTest) { methodNames.add(method.getName()); } @@ -163,7 +163,7 @@ protected PowerMockJUnitRunnerDelegate createDelegatorFromClassloader(ClassLoade Constructor con = delegateClass.getConstructor(Class.class, String[].class, powerMockTestListenerArrayType); return (PowerMockJUnitRunnerDelegate) con.newInstance( - testClassLoadedByMockedClassLoader, methodNames.toArray(new String[methodNames.size()]), + testClassLoadedByMockedClassLoader, methodNames.toArray(new String[0]), getPowerMockTestListenersLoadedByASpecificClassLoader(testClass, classLoader)); } diff --git a/powermock-modules/powermock-module-junit4-rule-agent/src/main/java/org/powermock/modules/junit4/rule/PowerMockRule.java b/powermock-modules/powermock-module-junit4-rule-agent/src/main/java/org/powermock/modules/junit4/rule/PowerMockRule.java index 5b368104b..c0b93e1e2 100644 --- a/powermock-modules/powermock-module-junit4-rule-agent/src/main/java/org/powermock/modules/junit4/rule/PowerMockRule.java +++ b/powermock-modules/powermock-module-junit4-rule-agent/src/main/java/org/powermock/modules/junit4/rule/PowerMockRule.java @@ -37,7 +37,7 @@ public class PowerMockRule implements MethodRule { 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(); + PowerMockAgent.initializeIfNeeded(); } @Override diff --git a/powermock-modules/powermock-module-junit4/src/main/java/org/powermock/modules/junit4/PowerMockRunnerDelegate.java b/powermock-modules/powermock-module-junit4/src/main/java/org/powermock/modules/junit4/PowerMockRunnerDelegate.java index 4db2363bb..a96f6b8b7 100644 --- a/powermock-modules/powermock-module-junit4/src/main/java/org/powermock/modules/junit4/PowerMockRunnerDelegate.java +++ b/powermock-modules/powermock-module-junit4/src/main/java/org/powermock/modules/junit4/PowerMockRunnerDelegate.java @@ -29,6 +29,8 @@ import java.lang.annotation.Target; import java.lang.reflect.Method; +import junit.framework.Test; + @Target(ElementType.TYPE) @Documented @Retention(RetentionPolicy.RUNTIME) @@ -37,7 +39,7 @@ Class value() default DefaultJUnitRunner.class; - public final class DefaultJUnitRunner extends Runner { + final class DefaultJUnitRunner extends Runner { private final Runner wrappedDefaultRunner; @@ -49,7 +51,7 @@ private static Runner createDefaultRunner(Class testClass) throws Throwable { try { Method suiteMethod = testClass.getMethod("suite"); - if (junit.framework.Test.class.isAssignableFrom(suiteMethod.getReturnType())) { + if (Test.class.isAssignableFrom(suiteMethod.getReturnType())) { return new AllTests(testClass); } else { /* Continue below ... */ diff --git a/powermock-modules/powermock-module-junit4/src/main/java/org/powermock/modules/junit4/internal/impl/DelegatingPowerMockRunner.java b/powermock-modules/powermock-module-junit4/src/main/java/org/powermock/modules/junit4/internal/impl/DelegatingPowerMockRunner.java index 576726e28..d78629a2a 100644 --- a/powermock-modules/powermock-module-junit4/src/main/java/org/powermock/modules/junit4/internal/impl/DelegatingPowerMockRunner.java +++ b/powermock-modules/powermock-module-junit4/src/main/java/org/powermock/modules/junit4/internal/impl/DelegatingPowerMockRunner.java @@ -29,7 +29,6 @@ import org.powermock.core.testlisteners.GlobalNotificationBuildSupport; import org.powermock.modules.junit4.PowerMockRunnerDelegate; 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; @@ -70,7 +69,7 @@ public DelegatingPowerMockRunner( private static Method[] determineTestMethods( Class testClass, String[] testMethodNames) { - List testMethods = new ArrayList(); + List testMethods = new ArrayList<>(); for (Method m : testClass.getMethods()) { if (m.isAnnotationPresent(Test.class) || m.isAnnotationPresent(Theory.class)) { testMethods.add(m); @@ -85,7 +84,7 @@ private static Method[] determineTestMethods( } } } - return testMethods.toArray(new Method[testMethods.size()]); + return testMethods.toArray(new Method[0]); } private static Runner createDelegate(final Class testClass) @@ -94,30 +93,24 @@ private static Runner createDelegate(final Class testClass) * 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)) { - try { - return Whitebox.invokeConstructor(testClass.getAnnotation(PowerMockRunnerDelegate.class).value(), - new Class[] { Class.class, RunnerBuilder.class }, - new Object[] { - testClass, new AllDefaultPossibilitiesBuilder(false) - }); - } catch (ConstructorNotFoundException ignoredWorkAroundFailure) { - } + return withContextClassLoader(testClass.getClassLoader(), () -> { + try { + Class clazz = testClass.isAnnotationPresent(PowerMockRunnerDelegate.class) + ? testClass.getAnnotation(PowerMockRunnerDelegate.class).value() + : PowerMockRunnerDelegate.DefaultJUnitRunner.class; + return Whitebox.invokeConstructor(clazz, new Class[] { Class.class }, new Object[] { testClass }); + } catch (ConstructorNotFoundException rootProblem) { + if (testClass.isAnnotationPresent(PowerMockRunnerDelegate.class)) { + try { + return Whitebox.invokeConstructor(testClass.getAnnotation(PowerMockRunnerDelegate.class).value(), + new Class[] { Class.class, RunnerBuilder.class }, + new Object[] { + testClass, new AllDefaultPossibilitiesBuilder(false) + }); + } catch (ConstructorNotFoundException ignoredWorkAroundFailure) { } - throw rootProblem; } + throw rootProblem; } }); } @@ -137,21 +130,18 @@ private static T withContextClassLoader( @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; + withContextClassLoader(testClassLoader, (Callable) () -> { + 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); diff --git a/powermock-modules/powermock-module-junit4/src/main/java/org/powermock/modules/junit4/internal/impl/NotificationBuilder.java b/powermock-modules/powermock-module-junit4/src/main/java/org/powermock/modules/junit4/internal/impl/NotificationBuilder.java index 033acbafc..2be96bbd5 100644 --- a/powermock-modules/powermock-module-junit4/src/main/java/org/powermock/modules/junit4/internal/impl/NotificationBuilder.java +++ b/powermock-modules/powermock-module-junit4/src/main/java/org/powermock/modules/junit4/internal/impl/NotificationBuilder.java @@ -43,7 +43,7 @@ enum DetectedTestRunBehaviour { TEST_INSTANCE_CREATED_FIRST, ALL_TESTINSTANCES_ARE_CREATED_FIRST, TEST_INSTANCES_ARE_REUSED, - INCONSISTENT_BEHAVIOUR; + INCONSISTENT_BEHAVIOUR } private static final Pattern methodDisplayNameRgx = @@ -65,14 +65,13 @@ enum DetectedTestRunBehaviour { @Override public List get(Object key) { if (!containsKey(key)) { - put(key, new LinkedList()); + put(key, new LinkedList<>()); } return super.get(key); } }; - private final Map ongoingTestRuns = - new IdentityHashMap(); + private final Map ongoingTestRuns = new IdentityHashMap<>(); private class OngoingTestRun implements TestMethodResult { final Description testDescription; diff --git a/powermock-modules/powermock-module-junit4/src/main/java/org/powermock/modules/junit4/internal/impl/PowerMockJUnit4RunnerDelegateImpl.java b/powermock-modules/powermock-module-junit4/src/main/java/org/powermock/modules/junit4/internal/impl/PowerMockJUnit4RunnerDelegateImpl.java index 4b0f996c7..f62e923f5 100644 --- a/powermock-modules/powermock-module-junit4/src/main/java/org/powermock/modules/junit4/internal/impl/PowerMockJUnit4RunnerDelegateImpl.java +++ b/powermock-modules/powermock-module-junit4/src/main/java/org/powermock/modules/junit4/internal/impl/PowerMockJUnit4RunnerDelegateImpl.java @@ -15,8 +15,6 @@ */ package org.powermock.modules.junit4.internal.impl; -import junit.framework.TestCase; -import junit.framework.TestSuite; import org.junit.Before; import org.junit.Rule; import org.junit.internal.runners.ClassRoadie; @@ -56,13 +54,13 @@ import java.lang.reflect.Field; 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; import java.util.Set; +import junit.framework.TestCase; +import junit.framework.TestSuite; + /** *

    * A JUnit4 test runner that only runs a specified set of test methods in a test @@ -113,7 +111,7 @@ protected final List getTestMethods(Class klass, String[] methodsToRu throw new RuntimeException(e); } } else { - List foundMethods = new LinkedList(); + List foundMethods = new LinkedList<>(); Method[] methods = klass.getMethods(); for (Method method : methods) { for (String methodName : methodsToRun) { @@ -136,12 +134,7 @@ protected final void validate() throws InitializationError { @Override public void run(final RunNotifier notifier) { - new ClassRoadie(notifier, testClass, getDescription(), new Runnable() { - @Override - public void run() { - runMethods(notifier); - } - }).runProtected(); + new ClassRoadie(notifier, testClass, getDescription(), () -> runMethods(notifier)).runProtected(); } protected void runMethods(final RunNotifier notifier) { @@ -255,23 +248,14 @@ protected Annotation[] testAnnotations(Method method) { @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(); - } + testMethods.removeIf(method -> !filter.shouldRun(methodDescription(method))); 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)); - } - }); + testMethods.sort((o1, o2) -> sorter.compare(methodDescription(o1), methodDescription(o2))); } protected TestClass getTestWrappedClass() { diff --git a/powermock-modules/powermock-module-junit4/src/main/java/org/powermock/modules/junit4/internal/impl/PowerMockRunNotifier.java b/powermock-modules/powermock-module-junit4/src/main/java/org/powermock/modules/junit4/internal/impl/PowerMockRunNotifier.java index 312a5c723..0741f5e65 100644 --- a/powermock-modules/powermock-module-junit4/src/main/java/org/powermock/modules/junit4/internal/impl/PowerMockRunNotifier.java +++ b/powermock-modules/powermock-module-junit4/src/main/java/org/powermock/modules/junit4/internal/impl/PowerMockRunNotifier.java @@ -45,8 +45,7 @@ class PowerMockRunNotifier extends RunNotifier private final RunNotifier junitRunNotifier; private final PowerMockTestNotifier powerMockTestNotifier; private final Method[] testMethods; - private final LinkedList pendingTestInstancesOnMotherThread = - new LinkedList(); + private final LinkedList pendingTestInstancesOnMotherThread = new LinkedList<>(); private final ThreadLocal notificationBuilder = new ThreadLocal() { @Override diff --git a/powermock-modules/powermock-module-junit4/src/main/java/org/powermock/modules/junit4/internal/impl/testcaseworkaround/PowerMockJUnit4MethodValidator.java b/powermock-modules/powermock-module-junit4/src/main/java/org/powermock/modules/junit4/internal/impl/testcaseworkaround/PowerMockJUnit4MethodValidator.java index 15968681b..8bed5fdd0 100644 --- a/powermock-modules/powermock-module-junit4/src/main/java/org/powermock/modules/junit4/internal/impl/testcaseworkaround/PowerMockJUnit4MethodValidator.java +++ b/powermock-modules/powermock-module-junit4/src/main/java/org/powermock/modules/junit4/internal/impl/testcaseworkaround/PowerMockJUnit4MethodValidator.java @@ -15,7 +15,6 @@ */ package org.powermock.modules.junit4.internal.impl.testcaseworkaround; -import junit.framework.TestCase; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -30,6 +29,8 @@ import java.util.LinkedList; import java.util.List; +import junit.framework.TestCase; + /** * A custom {@link MethodValidator} that makes sure that test methods not * annotated by the Test annotation works in JUnit 4.4 with the custom @@ -121,7 +122,7 @@ private void validateTestMethods(Class annotation, boolean } private List getTestMethodsWithNoAnnotation(Class testClass) { - List potentialTestMethods = new LinkedList(); + List potentialTestMethods = new LinkedList<>(); Method[] methods = testClass.getMethods(); for (Method method : methods) { if (method.getName().startsWith("test")) { diff --git a/powermock-modules/powermock-module-junit4/src/test/java/org/powermock/modules/junit4/internal/impl/PowerMockRunNotifierTest.java b/powermock-modules/powermock-module-junit4/src/test/java/org/powermock/modules/junit4/internal/impl/PowerMockRunNotifierTest.java index 0edde6ae3..2326b8b21 100644 --- a/powermock-modules/powermock-module-junit4/src/test/java/org/powermock/modules/junit4/internal/impl/PowerMockRunNotifierTest.java +++ b/powermock-modules/powermock-module-junit4/src/test/java/org/powermock/modules/junit4/internal/impl/PowerMockRunNotifierTest.java @@ -15,6 +15,7 @@ */ package org.powermock.modules.junit4.internal.impl; +import org.easymock.EasyMock; import org.junit.Test; import org.junit.runner.Description; import org.junit.runner.Result; @@ -23,7 +24,6 @@ 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; @@ -59,7 +59,7 @@ public class PowerMockRunNotifierTest { @Parameterized.Parameters(name = "{0}") public static List runNotifierMethods() { - List methods = new ArrayList(); + List methods = new ArrayList<>(); for (Method m : RunNotifier.class.getMethods()) { if (Object.class != m.getDeclaringClass()) { methods.add(new Object[] {m}); diff --git a/powermock-modules/powermock-module-testng-agent/src/main/java/org/powermock/modules/testng/PowerMockObjectFactory.java b/powermock-modules/powermock-module-testng-agent/src/main/java/org/powermock/modules/testng/PowerMockObjectFactory.java index c3945db04..fa59aa117 100644 --- a/powermock-modules/powermock-module-testng-agent/src/main/java/org/powermock/modules/testng/PowerMockObjectFactory.java +++ b/powermock-modules/powermock-module-testng-agent/src/main/java/org/powermock/modules/testng/PowerMockObjectFactory.java @@ -33,7 +33,7 @@ public class PowerMockObjectFactory implements IObjectFactory { 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(); + PowerMockAgent.initializeIfNeeded(); } private final ObjectFactoryImpl defaultObjectFactory; diff --git a/powermock-modules/powermock-module-testng/src/main/java/org/powermock/modules/testng/internal/PowerMockExpectedExceptionsExtractorImpl.java b/powermock-modules/powermock-module-testng/src/main/java/org/powermock/modules/testng/internal/PowerMockExpectedExceptionsExtractorImpl.java index e01866042..b45a1895c 100644 --- a/powermock-modules/powermock-module-testng/src/main/java/org/powermock/modules/testng/internal/PowerMockExpectedExceptionsExtractorImpl.java +++ b/powermock-modules/powermock-module-testng/src/main/java/org/powermock/modules/testng/internal/PowerMockExpectedExceptionsExtractorImpl.java @@ -26,8 +26,9 @@ public class PowerMockExpectedExceptionsExtractorImpl implements IgnorePackagesExtractor { + @Override public String[] getPackagesToIgnore(AnnotatedElement element) { - List ignoredPackages = new LinkedList(); + List ignoredPackages = new LinkedList<>(); if (element instanceof Class) { Class klazz = (Class) element; for (Method method : klazz.getMethods()) { @@ -48,7 +49,7 @@ public String[] getPackagesToIgnore(AnnotatedElement element) { } } - return ignoredPackages.toArray(new String[ignoredPackages.size()]); + return ignoredPackages.toArray(new String[0]); } } diff --git a/powermock-modules/powermock-module-testng/src/main/java/org/powermock/modules/testng/internal/PowerMockTestNGMethodHandler.java b/powermock-modules/powermock-module-testng/src/main/java/org/powermock/modules/testng/internal/PowerMockTestNGMethodHandler.java index c1d108876..f2e1b9d1a 100644 --- a/powermock-modules/powermock-module-testng/src/main/java/org/powermock/modules/testng/internal/PowerMockTestNGMethodHandler.java +++ b/powermock-modules/powermock-module-testng/src/main/java/org/powermock/modules/testng/internal/PowerMockTestNGMethodHandler.java @@ -15,7 +15,6 @@ */ 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; @@ -26,6 +25,8 @@ import java.lang.reflect.Method; import java.util.Set; +import javassist.util.proxy.MethodHandler; + /* * Javassist handler that takes care of cleaning up {@link MockRepository} state * after each method annotated with {@link Test}. @@ -47,8 +48,7 @@ public PowerMockTestNGMethodHandler(Class testClass) { 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; + return proceed.invoke(self, args); } catch (InvocationTargetException e) { throw e.getTargetException(); } @@ -61,7 +61,7 @@ public Object invoke(Object self, Method thisMethod, Method proceed, Object[] ar } } - private void clearMockFields() throws Exception, IllegalAccessException { + private void clearMockFields() throws Exception { if (annotationEnabler != null) { Set mockFields = Whitebox.getFieldsAnnotatedWith(this, Whitebox .[]> invokeMethod(annotationEnabler, "getMockAnnotations")); diff --git a/powermock-modules/powermock-module-testng/src/main/java/org/powermock/modules/testng/internal/TestClassInstanceFactory.java b/powermock-modules/powermock-module-testng/src/main/java/org/powermock/modules/testng/internal/TestClassInstanceFactory.java index c63ee9a6a..d7a7afc62 100644 --- a/powermock-modules/powermock-module-testng/src/main/java/org/powermock/modules/testng/internal/TestClassInstanceFactory.java +++ b/powermock-modules/powermock-module-testng/src/main/java/org/powermock/modules/testng/internal/TestClassInstanceFactory.java @@ -17,13 +17,14 @@ 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; +import javassist.util.proxy.ProxyFactory; + class TestClassInstanceFactory { private final Constructor constructor; private final Class testClass; diff --git a/powermock-modules/powermock-module-testng/src/main/java/org/powermock/modules/testng/internal/TestNGMethodFilter.java b/powermock-modules/powermock-module-testng/src/main/java/org/powermock/modules/testng/internal/TestNGMethodFilter.java index e93a94a27..da7df7e44 100644 --- a/powermock-modules/powermock-module-testng/src/main/java/org/powermock/modules/testng/internal/TestNGMethodFilter.java +++ b/powermock-modules/powermock-module-testng/src/main/java/org/powermock/modules/testng/internal/TestNGMethodFilter.java @@ -15,10 +15,10 @@ */ package org.powermock.modules.testng.internal; -import javassist.util.proxy.MethodFilter; - import java.lang.reflect.Method; +import javassist.util.proxy.MethodFilter; + /** * Javassist method filter that ignores the toString, equals, finalize and * hashCode method otherwise the test output in Maven looks strange and diff --git a/powermock-reflect/src/main/java/org/powermock/reflect/Whitebox.java b/powermock-reflect/src/main/java/org/powermock/reflect/Whitebox.java index 3feb54a0c..9510d3507 100644 --- a/powermock-reflect/src/main/java/org/powermock/reflect/Whitebox.java +++ b/powermock-reflect/src/main/java/org/powermock/reflect/Whitebox.java @@ -329,7 +329,7 @@ public static T getInternalState(Object object, String fieldName, Class w */ @Deprecated public static T getInternalState(Object object, String fieldName, Class where, Class type) { - return Whitebox.getInternalState(object, fieldName, where); + return getInternalState(object, fieldName, where); } /** diff --git a/powermock-reflect/src/main/java/org/powermock/reflect/internal/CandidateConstructorSearcher.java b/powermock-reflect/src/main/java/org/powermock/reflect/internal/CandidateConstructorSearcher.java index b83d97e6d..42ca6a253 100644 --- a/powermock-reflect/src/main/java/org/powermock/reflect/internal/CandidateConstructorSearcher.java +++ b/powermock-reflect/src/main/java/org/powermock/reflect/internal/CandidateConstructorSearcher.java @@ -61,13 +61,13 @@ private Constructor[] getConstructors() { try { Constructor[] declaredConstructors = classThatContainsTheConstructorToTest.getDeclaredConstructors(); - List> constructors = new ArrayList>(); + List> constructors = new ArrayList<>(); for (Constructor constructor : declaredConstructors) { if (argumentsApplied(constructor)) { constructors.add(constructor); } } - return constructors.toArray(new Constructor[constructors.size()]); + return constructors.toArray(new Constructor[0]); } catch (Exception e) { return new Constructor[0]; } diff --git a/powermock-reflect/src/main/java/org/powermock/reflect/internal/ConstructorFinder.java b/powermock-reflect/src/main/java/org/powermock/reflect/internal/ConstructorFinder.java index 88e83dbb5..ae2525f44 100644 --- a/powermock-reflect/src/main/java/org/powermock/reflect/internal/ConstructorFinder.java +++ b/powermock-reflect/src/main/java/org/powermock/reflect/internal/ConstructorFinder.java @@ -102,7 +102,7 @@ private boolean isNestedClass() { } private Set getDeclaredConstructorsWithoutPowerMockConstructor() { - Set constructors = new HashSet(); + Set constructors = new HashSet<>(); for (java.lang.reflect.Constructor constructor : unmockedType.getDeclaredConstructors()) { if (!isPowerMockConstructor(constructor.getParameterTypes())) { constructors.add(new Constructor(constructor)); diff --git a/powermock-reflect/src/main/java/org/powermock/reflect/internal/ParametersMatcher.java b/powermock-reflect/src/main/java/org/powermock/reflect/internal/ParametersMatcher.java index 541ba9ac8..86420e844 100644 --- a/powermock-reflect/src/main/java/org/powermock/reflect/internal/ParametersMatcher.java +++ b/powermock-reflect/src/main/java/org/powermock/reflect/internal/ParametersMatcher.java @@ -20,10 +20,8 @@ public boolean match() { return true; } return checkArgumentTypesMatchParameterTypes(isVarArgs, parameterTypes, arguments); - } else if (doesParameterTypesMatchForVarArgsInvocation(arguments)) { - return true; } else { - return false; + return doesParameterTypesMatchForVarArgsInvocation(arguments); } } diff --git a/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java b/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java index 2cbb3cb42..f53b4963a 100644 --- a/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java +++ b/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java @@ -42,7 +42,6 @@ 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; @@ -60,6 +59,7 @@ import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; + import sun.misc.Unsafe; /** @@ -77,7 +77,7 @@ public class WhiteboxImpl { * "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(); + private static ConcurrentMap allClassMethodsCache = new ConcurrentHashMap<>(); /** * Convenience method to get a method from a class type without having to @@ -101,7 +101,7 @@ public static Method getMethod(Class type, Class... parameterTypes) { parameterTypes = new Class[0]; } - List foundMethods = new LinkedList(); + List foundMethods = new LinkedList<>(); while (thisType != null) { Method[] methodsToTraverse = null; if (thisType.isInterface()) { @@ -134,7 +134,7 @@ public static Method getMethod(Class type, Class... parameterTypes) { + getOriginalUnmockedType(type).getName() + "."); } else { throwExceptionWhenMultipleMethodMatchesFound("method name", - foundMethods.toArray(new Method[foundMethods.size()])); + foundMethods.toArray(new Method[0])); } // Will never happen return null; @@ -198,9 +198,9 @@ && checkIfParameterTypesAreSame(method.isVarArgs(), parameterTypes, method.getPa */ @SuppressWarnings({"unchecked", "rawtypes"}) public static Field getField(Class type, String fieldName) { - LinkedList> examine = new LinkedList>(); + LinkedList> examine = new LinkedList<>(); examine.add(type); - Set> done = new HashSet>(); + Set> done = new HashSet<>(); while (!examine.isEmpty()) { Class thisType = examine.removeFirst(); done.add(thisType); @@ -211,7 +211,7 @@ public static Field getField(Class type, String fieldName) { return field; } } - Set> potential = new HashSet>(); + Set> potential = new HashSet<>(); final Class clazz = thisType.getSuperclass(); if (clazz != null) { potential.add(thisType.getSuperclass()); @@ -244,12 +244,7 @@ public static T newInstance(Class classToInstantiate) { 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()); - } - }); + (proxy, method, args) -> TypeUtils.getDefaultValue(method.getReturnType())); } else if (classToInstantiate.isArray()) { object = Array.newInstance(classToInstantiate.getComponentType(), 0); } else if (Modifier.isAbstract(modifiers)) { @@ -275,16 +270,15 @@ public Object invoke(Object proxy, Method method, Object[] args) throws Throwabl * @return A . */ public static Constructor getConstructor(Class type, Class... parameterTypes) { - Class unmockedType = WhiteboxImpl.getOriginalUnmockedType(type); + Class unmockedType = getOriginalUnmockedType(type); try { final Constructor constructor = unmockedType.getDeclaredConstructor(parameterTypes); constructor.setAccessible(true); return constructor; - } catch (RuntimeException e) { + } catch (RuntimeException | Error e) { throw e; - } catch (Error e) { - throw e; - } catch (Throwable 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); @@ -519,7 +513,7 @@ private static Set findAllFieldsUsingStrategy(FieldMatcherStrategy strate boolean checkHierarchy, boolean onlyInstanceFields, Class startClass) { assertObjectInGetInternalStateIsNotNull(object); - final Set foundFields = new LinkedHashSet(); + final Set foundFields = new LinkedHashSet<>(); while (startClass != null) { final Field[] declaredFields = startClass.getDeclaredFields(); for (Field field : declaredFields) { @@ -925,7 +919,7 @@ public static Method findMethodOrThrowException(Object tested, Class declarin } } - WhiteboxImpl.throwExceptionIfMethodWasNotFound(getType(tested), methodToExecute, potentialMethodToInvoke, + throwExceptionIfMethodWasNotFound(getType(tested), methodToExecute, potentialMethodToInvoke, arguments); return potentialMethodToInvoke; } @@ -1006,13 +1000,11 @@ public static Method getBestMethodCandidate(Class cls, String methodName, Cla boolean exactParameterTypeMatch) { final Method foundMethod; final Method[] methods = getMethods(cls, methodName, signature, exactParameterTypeMatch); - if (methods.length == 1) { - foundMethod = methods[0]; - } else { + if (methods.length != 1) { // We've found overloaded methods, we need to find the best one to invoke. Arrays.sort(methods, ComparatorFactory.createMethodComparator()); - foundMethod = methods[0]; } + foundMethod = methods[0]; return foundMethod; } @@ -1062,7 +1054,7 @@ public static Constructor findConstructorOrThrowException(Class type) { * @return the constructor[] */ static Constructor[] filterPowerMockConstructor(Constructor[] declaredConstructors) { - Set> constructors = new HashSet>(); + Set> constructors = new HashSet<>(); for (Constructor constructor : declaredConstructors) { final Class[] parameterTypes = constructor.getParameterTypes(); if (parameterTypes.length >= 1 @@ -1073,7 +1065,7 @@ static Constructor[] filterPowerMockConstructor(Constructor[] declaredCons constructors.add(constructor); } } - return constructors.toArray(new Constructor[constructors.size()]); + return constructors.toArray(new Constructor[0]); } /** @@ -1334,7 +1326,7 @@ private static Constructor getBestCandidateConstructor(Class classThat } private static Constructor getPotentialConstructorWrapped(Class classThatContainsTheConstructorToTest, Class[] argumentTypes) { - return new CandidateConstructorSearcher(classThatContainsTheConstructorToTest, argumentTypes) + return new CandidateConstructorSearcher<>(classThatContainsTheConstructorToTest, argumentTypes) .findConstructor(); } @@ -1346,7 +1338,7 @@ private static Constructor getPotentialConstructorPrimitive(Class clas if (!argumentTypesEqualsPrimitiveTypes(argumentTypes, primitiveType)) { - potentialConstructorPrimitive = new CandidateConstructorSearcher(classThatContainsTheConstructorToTest, primitiveType) + potentialConstructorPrimitive = new CandidateConstructorSearcher<>(classThatContainsTheConstructorToTest, primitiveType) .findConstructor(); } } catch (Exception e) { @@ -1489,20 +1481,14 @@ 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(); + 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(); - } - - }); + final Method[] declaredMethods = AccessController.doPrivileged( + (PrivilegedAction) type::getDeclaredMethods); for (Method method : declaredMethods) { if(!"finalize".equals(method.getName())) { method.setAccessible(true); @@ -1512,7 +1498,7 @@ public Method[] run() { Collections.addAll(methods, type.getMethods()); thisType = thisType.getSuperclass(); } - return methods.toArray(new Method[methods.size()]); + return methods.toArray(new Method[0]); } /** @@ -1526,7 +1512,7 @@ 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(); + Set methods = new LinkedHashSet<>(); for (Method method : clazz.getMethods()) { method.setAccessible(true); @@ -1546,7 +1532,7 @@ 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(); + Set fields = new LinkedHashSet<>(); Class thisType = clazz; @@ -1558,7 +1544,7 @@ public static Field[] getAllFields(Class clazz) { } thisType = thisType.getSuperclass(); } - return fields.toArray(new Field[fields.size()]); + return fields.toArray(new Field[0]); } /** @@ -1595,7 +1581,7 @@ public static Method findMethod(Class type, String methodName, Class.. if (methodName == null && parameterTypes == null) { throw new IllegalArgumentException("You must specify a method name or parameter types."); } - List matchingMethodsList = new LinkedList(); + List matchingMethodsList = new LinkedList<>(); for (Method method : getAllMethods(type)) { if (methodName == null || method.getName().equals(methodName)) { if (parameterTypes != null && parameterTypes.length > 0) { @@ -1631,13 +1617,13 @@ public static Method findMethod(Class type, String methodName, Class.. } if (methodToMock == null) { - WhiteboxImpl.throwExceptionWhenMultipleMethodMatchesFound("argument parameter types", - matchingMethodsList.toArray(new Method[matchingMethodsList.size()])); + throwExceptionWhenMultipleMethodMatchesFound("argument parameter types", + matchingMethodsList.toArray(new Method[0])); } } else { // We've found several matching methods. - WhiteboxImpl.throwExceptionWhenMultipleMethodMatchesFound("argument parameter types", - matchingMethodsList.toArray(new Method[matchingMethodsList.size()])); + throwExceptionWhenMultipleMethodMatchesFound("argument parameter types", + matchingMethodsList.toArray(new Method[0])); } } @@ -1742,7 +1728,7 @@ 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(); + final List methodsToMock = new LinkedList<>(); Method[] allMethods = null; if (clazz.isInterface()) { allMethods = getAllPublicMethods(clazz); @@ -1785,7 +1771,7 @@ public static Method[] getMethods(Class clazz, String... methodNames) { */ public static Method[] getMethods(Class clazz, String methodName, Class[] expectedTypes, boolean exactParameterTypeMatch) { - List matchingArgumentTypes = new LinkedList(); + List matchingArgumentTypes = new LinkedList<>(); Method[] methods = getMethods(clazz, methodName); for (Method method : methods) { final Class[] parameterTypes = method.getParameterTypes(); @@ -1802,7 +1788,7 @@ public static Method[] getMethods(Class clazz, String methodName, Class[] "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()]); + return matchingArgumentTypes.toArray(new Method[0]); } /** @@ -1814,7 +1800,7 @@ public static Method[] getMethods(Class clazz, String methodName, Class[] * @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(); + final List fields = new LinkedList<>(); for (Field field : getAllFields(clazz)) { for (String fieldName : fieldNames) { @@ -1824,7 +1810,7 @@ public static Field[] getFields(Class clazz, String... fieldNames) { } } - final Field[] fieldArray = fields.toArray(new Field[fields.size()]); + final Field[] fieldArray = fields.toArray(new Field[0]); if (fieldArray.length == 0) { throw new FieldNotFoundException(String.format( "No fields matching the name(s) %s were found in the class hierarchy of %s.", @@ -1888,7 +1874,7 @@ public static T performMethodInvocation(Object tested, Method methodToInvoke * @return the all method except */ public static Method[] getAllMethodExcept(Class type, String... methodNames) { - List methodsToMock = new LinkedList(); + List methodsToMock = new LinkedList<>(); Method[] methods = getAllMethods(type); iterateMethods: for (Method method : methods) { @@ -1913,7 +1899,7 @@ public static Method[] getAllMethodExcept(Class type, String... methodNam */ public static Method[] getAllMethodsExcept(Class type, String methodNameToExclude, Class[] argumentTypes) { Method[] methods = getAllMethods(type); - List methodList = new ArrayList(); + List methodList = new ArrayList<>(); outer: for (Method method : methods) { if (method.getName().equals(methodNameToExclude)) { @@ -2317,27 +2303,21 @@ private static void setStaticFieldUsingUnsafe(final Field field, final Object ne 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); - } - }}); + AccessController.doPrivileged((PrivilegedAction) () -> { + 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) { + } catch (SecurityException | IllegalArgumentException | IllegalAccessException ex) { throw new RuntimeException(ex); } } @@ -2348,17 +2328,14 @@ private static void setFieldUsingUnsafe(final Field field, final Object object, 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); - } + AccessController.doPrivileged((PrivilegedAction) () -> { + 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 { @@ -2376,8 +2353,7 @@ public Object run() { 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; + return (Unsafe) field1.get(null); } private static void setFieldUsingUnsafe(Object base, Class type, long offset, Object newValue, Unsafe unsafe) { @@ -2468,9 +2444,8 @@ static boolean doesParameterTypesMatchForVarArgsInvocation(boolean isVarArgs, Cl 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 PrimitiveWrapper.hasPrimitiveCounterPart(firstArgumentType) ? PrimitiveWrapper + .getPrimitiveFromWrapperType(firstArgumentType) : firstArgumentType; } return null; } diff --git a/powermock-reflect/src/main/java/org/powermock/reflect/internal/primitivesupport/BoxedWrapper.java b/powermock-reflect/src/main/java/org/powermock/reflect/internal/primitivesupport/BoxedWrapper.java index 0bbac6f60..88603bd90 100644 --- a/powermock-reflect/src/main/java/org/powermock/reflect/internal/primitivesupport/BoxedWrapper.java +++ b/powermock-reflect/src/main/java/org/powermock/reflect/internal/primitivesupport/BoxedWrapper.java @@ -23,7 +23,7 @@ * translating wrapper types to its related primitive type. */ public class BoxedWrapper { - private static final Map, Class> boxedWrapper = new HashMap, Class>(); + private static final Map, Class> boxedWrapper = new HashMap<>(); static { boxedWrapper.put(int.class, Integer.class); diff --git a/powermock-reflect/src/main/java/org/powermock/reflect/internal/primitivesupport/PrimitiveWrapper.java b/powermock-reflect/src/main/java/org/powermock/reflect/internal/primitivesupport/PrimitiveWrapper.java index 8cbf06f05..acc9800f7 100644 --- a/powermock-reflect/src/main/java/org/powermock/reflect/internal/primitivesupport/PrimitiveWrapper.java +++ b/powermock-reflect/src/main/java/org/powermock/reflect/internal/primitivesupport/PrimitiveWrapper.java @@ -23,7 +23,7 @@ * translating wrapper types to its related primitive type. */ public class PrimitiveWrapper { - private static final Map, Class> primitiveWrapper = new HashMap, Class>(); + private static final Map, Class> primitiveWrapper = new HashMap<>(); static { primitiveWrapper.put(Integer.class, int.class); diff --git a/powermock-reflect/src/main/java/org/powermock/reflect/internal/proxy/UnproxiedTypeFactory.java b/powermock-reflect/src/main/java/org/powermock/reflect/internal/proxy/UnproxiedTypeFactory.java index 223fb31a2..5aaee5cec 100644 --- a/powermock-reflect/src/main/java/org/powermock/reflect/internal/proxy/UnproxiedTypeFactory.java +++ b/powermock-reflect/src/main/java/org/powermock/reflect/internal/proxy/UnproxiedTypeFactory.java @@ -36,7 +36,7 @@ UnproxiedType createFromType(Class type) { } private Class[] filterInterfaces(Class[] interfaces) { - List> filtered = new ArrayList>(); + List> filtered = new ArrayList<>(); for (Class anInterface : interfaces) { if(!isMockFrameworkInterface(anInterface)){ @@ -44,7 +44,7 @@ private Class[] filterInterfaces(Class[] interfaces) { } } - return filtered.toArray(new Class[filtered.size()]); + return filtered.toArray(new Class[0]); } private boolean isMockFrameworkInterface(Class anInterface) { diff --git a/powermock-reflect/src/test/java/org/powermock/reflect/WhiteBoxGetFieldTest.java b/powermock-reflect/src/test/java/org/powermock/reflect/WhiteBoxGetFieldTest.java index 6522d588e..2d24da266 100644 --- a/powermock-reflect/src/test/java/org/powermock/reflect/WhiteBoxGetFieldTest.java +++ b/powermock-reflect/src/test/java/org/powermock/reflect/WhiteBoxGetFieldTest.java @@ -20,11 +20,11 @@ import java.lang.reflect.Field; -import static org.assertj.core.api.Java6Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * A test case to demonstrate an issue - * {@link org.powermock.reflect.internal.WhiteboxImpl#getField(Class, String)}. + * {@link 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 diff --git a/powermock-reflect/src/test/java/org/powermock/reflect/WhiteBoxTest.java b/powermock-reflect/src/test/java/org/powermock/reflect/WhiteBoxTest.java index acb31546e..70b913ce4 100644 --- a/powermock-reflect/src/test/java/org/powermock/reflect/WhiteBoxTest.java +++ b/powermock-reflect/src/test/java/org/powermock/reflect/WhiteBoxTest.java @@ -65,7 +65,7 @@ import java.sql.Connection; import java.util.Set; -import static org.assertj.core.api.Java6Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -91,7 +91,7 @@ public void testFindMethod_classContainingMethodWithNoParameters() throws Except } @Test - public void testFindMethod_classContainingOnlyMethodsWithParameters() throws Exception { + public void testFindMethod_classContainingOnlyMethodsWithParameters() { try { WhiteboxImpl.findMethodOrThrowException(ClassWithSeveralMethodsWithSameName.class, "getDouble"); fail("Should throw runtime exception!"); @@ -102,7 +102,7 @@ public void testFindMethod_classContainingOnlyMethodsWithParameters() throws Exc } @Test - public void testFindMethod_noMethodFound() throws Exception { + public void testFindMethod_noMethodFound() { try { WhiteboxImpl.findMethodOrThrowException(ClassWithSeveralMethodsWithSameName.class, "getDouble2"); fail("Should throw runtime exception!"); @@ -114,7 +114,7 @@ public void testFindMethod_noMethodFound() throws Exception { } @Test - public void testGetInternalState_object() throws Exception { + public void testGetInternalState_object() { ClassWithInternalState tested = new ClassWithInternalState(); tested.increaseInteralState(); Object internalState = Whitebox.getInternalState(tested, "internalState"); @@ -124,7 +124,7 @@ public void testGetInternalState_object() throws Exception { @SuppressWarnings("deprecation") @Test - public void testGetInternalState_parmaterizedType() throws Exception { + public void testGetInternalState_parmaterizedType() { ClassWithInternalState tested = new ClassWithInternalState(); tested.increaseInteralState(); int internalState = Whitebox.getInternalState(tested, "internalState", tested.getClass(), int.class); @@ -132,7 +132,7 @@ public void testGetInternalState_parmaterizedType() throws Exception { } @Test - public void testSetInternalState() throws Exception { + public void testSetInternalState() { ClassWithInternalState tested = new ClassWithInternalState(); tested.increaseInteralState(); Whitebox.setInternalState(tested, "anotherInternalState", 2); @@ -140,7 +140,7 @@ public void testSetInternalState() throws Exception { } @Test - public void testSetInternalStateWithMultipleValues() throws Exception { + public void testSetInternalStateWithMultipleValues() { ClassWithInternalState tested = new ClassWithInternalState(); final ClassWithPrivateMethods classWithPrivateMethods = new ClassWithPrivateMethods(); final String stringState = "someStringState"; @@ -150,7 +150,7 @@ public void testSetInternalStateWithMultipleValues() throws Exception { } @Test - public void testSetInternalState_superClass() throws Exception { + public void testSetInternalState_superClass() { ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState(); tested.increaseInteralState(); Whitebox.setInternalState(tested, "anotherInternalState", 2, ClassWithInternalState.class); @@ -158,7 +158,7 @@ public void testSetInternalState_superClass() throws Exception { } @Test - public void testGetInternalState_superClass_object() throws Exception { + public void testGetInternalState_superClass_object() { ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState(); Object internalState = Whitebox.getInternalState(tested, "internalState", ClassWithInternalState.class); assertEquals(0, internalState); @@ -166,7 +166,7 @@ public void testGetInternalState_superClass_object() throws Exception { @SuppressWarnings("deprecation") @Test - public void testGetInternalState_superClass_parameterized() throws Exception { + public void testGetInternalState_superClass_parameterized() { ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState(); int internalState = Whitebox.getInternalState(tested, "internalState", ClassWithInternalState.class, int.class); assertEquals(0, internalState); @@ -179,7 +179,7 @@ public void testInvokePrivateMethod_primtiveType() throws Exception { @Test public void testInvokePrivateMethod_primtiveType_withoutSpecifyingMethodName() throws Exception { - assertTrue((Boolean) Whitebox.invokeMethod(new ClassWithUniquePrivateMethods(), 8.2d, 8.4d)); + assertTrue(Whitebox.invokeMethod(new ClassWithUniquePrivateMethods(), 8.2d, 8.4d)); } /** @@ -198,7 +198,7 @@ public void testInvokePrivateMethod_withoutSpecifyingMethodName_noArguments() th @Test public void testInvokePrivateMethod_withoutSpecifyingMethodName_assertThatNullWorks() throws Exception { - assertTrue(Whitebox.invokeMethod(new ClassWithUniquePrivateMethods(), 8.2d, 8.3d, null) instanceof Object); + assertNotNull(Whitebox.invokeMethod(new ClassWithUniquePrivateMethods(), 8.2d, 8.3d, null)); } /** @@ -216,22 +216,22 @@ public void testInvokePrivateMethod_withoutSpecifyingMethodName_onlyOneArgument( @Test(expected = TooManyMethodsFoundException.class) public void testInvokeStaticPrivateMethod_withoutSpecifyingMethodName_onlyOneArgument() throws Exception { - assertTrue((Boolean) Whitebox.invokeMethod(ClassWithUniquePrivateMethods.class, 8.2d)); + assertTrue(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))); + assertTrue(Whitebox.invokeMethod(new ClassWithPrivateMethods(), "primitiveMethod", 8.2)); } @Test public void testInvokePrivateMethod_wrappedType() throws Exception { - assertTrue((Boolean) Whitebox.invokeMethod(new ClassWithPrivateMethods(), "wrappedMethod", new Double(8.2))); + assertTrue(Whitebox.invokeMethod(new ClassWithPrivateMethods(), "wrappedMethod", 8.2)); } @Test public void testInvokePrivateMethod_wrappedType_primitive() throws Exception { - assertTrue((Boolean) Whitebox.invokeMethod(new ClassWithPrivateMethods(), "wrappedMethod", 8.2)); + assertTrue(Whitebox.invokeMethod(new ClassWithPrivateMethods(), "wrappedMethod", 8.2)); } @Test @@ -243,13 +243,13 @@ public void testMethodWithPrimitiveIntAndString_primitive() throws Exception { @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: ")); + "methodWithPrimitiveIntAndString", 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))); + assertEquals(17, (int) Whitebox.invokeMethod(new ClassWithPrivateMethods(), "methodWithPrimitiveAndWrappedInt", + new Class[]{int.class, Integer.class}, 9, 8)); } @Test @@ -257,17 +257,17 @@ public void testStaticState() { int expected = 123; Whitebox.setInternalState(ClassWithInternalState.class, "staticState", expected); assertEquals(expected, ClassWithInternalState.getStaticState()); - assertEquals(expected, Whitebox.getInternalState(ClassWithInternalState.class, "staticState")); + assertEquals(expected, (int) Whitebox.getInternalState(ClassWithInternalState.class, "staticState")); } @Test public void testStaticFinalPrimitiveState() { Whitebox.setInternalState(ClassWithInternalState.class, "staticFinalIntState", 123); - assertEquals(123, Whitebox.getInternalState(ClassWithInternalState.class, "staticFinalIntState")); + assertEquals(123, (int) Whitebox.getInternalState(ClassWithInternalState.class, "staticFinalIntState")); } @Test - public void testStaticFinalStringState() throws NoSuchFieldException { + public void testStaticFinalStringState() { Whitebox.setInternalState(ClassWithInternalState.class, "staticFinalStringState", "Brand new string"); assertEquals("Brand new string", Whitebox.getInternalState(ClassWithInternalState.class, "staticFinalStringState")); } @@ -299,12 +299,12 @@ public void testInvokeConstructorWithNullParameter() throws Exception { } @Test(expected = IllegalArgumentException.class) - public void testGetInternalWithNullParameter() throws Exception { + public void testGetInternalWithNullParameter() { Whitebox.getInternalState(null, "state"); } @Test(expected = IllegalArgumentException.class) - public void testSetInternalWithNullParameter() throws Exception { + public void testSetInternalWithNullParameter() { Whitebox.setInternalState(null, "state", new Object()); } @@ -330,25 +330,25 @@ public void testInstantiateVarArgsOnlyConstructor_noArguments() throws Exception @Test public void testInvokeVarArgsMethod_multipleValues() throws Exception { ClassWithPrivateMethods tested = new ClassWithPrivateMethods(); - assertEquals(6, Whitebox.invokeMethod(tested, "varArgsMethod", 1, 2, 3)); + assertEquals(6, (int) Whitebox.invokeMethod(tested, "varArgsMethod", 1, 2, 3)); } @Test public void testInvokeVarArgsMethod_noArguments() throws Exception { ClassWithPrivateMethods tested = new ClassWithPrivateMethods(); - assertEquals(0, Whitebox.invokeMethod(tested, "varArgsMethod")); + assertEquals(0, (int) Whitebox.invokeMethod(tested, "varArgsMethod")); } @Test public void testInvokeVarArgsMethod_oneArgument() throws Exception { ClassWithPrivateMethods tested = new ClassWithPrivateMethods(); - assertEquals(4, Whitebox.invokeMethod(tested, "varArgsMethod", 2)); + assertEquals(4, (int) 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)); + assertEquals(1, (int) Whitebox.invokeMethod(tested, "varArgsMethod", new Class[]{int[].class}, 1)); } @Test @@ -366,70 +366,69 @@ public void testInvokePrivateMethodWithAClassArgument() throws Exception { } @Test - public void testSetInternalStateInChildClassWithoutSpecifyingTheChildClass() throws Exception { + public void testSetInternalStateInChildClassWithoutSpecifyingTheChildClass() { final int value = 22; final String fieldName = "internalState"; ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState() { }; Whitebox.setInternalState(tested, fieldName, value); - assertEquals(value, Whitebox.getInternalState(tested, fieldName)); + assertEquals(value, (int) Whitebox.getInternalState(tested, fieldName)); } @Test - public void testSetInternalStateInClassAndMakeSureThatTheChildClassIsNotAffectedEvenThoughItHasAFieldWithTheSameName() - throws Exception { + public void testSetInternalStateInClassAndMakeSureThatTheChildClassIsNotAffectedEvenThoughItHasAFieldWithTheSameName() { 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)); + assertEquals(value, (int) Whitebox.getInternalState(tested, fieldName)); + assertEquals(-1, (int) Whitebox.getInternalState(tested, fieldName, ClassWithInternalState.class)); } @Test(expected = IllegalArgumentException.class) - public void testSetInternalStateWithInvalidArgumentType() throws Exception { + public void testSetInternalStateWithInvalidArgumentType() { final int value = 22; final String fieldName = "internalState"; ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState() { }; Whitebox.setInternalState(tested, fieldName, new Object()); - assertEquals(value, Whitebox.getInternalState(tested, fieldName)); + assertEquals(value, (int) Whitebox.getInternalState(tested, fieldName)); } @Test(expected = IllegalArgumentException.class) - public void testSetInternalStateWithNull() throws Exception { + public void testSetInternalStateWithNull() { final int value = 22; final String fieldName = "internalState"; ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState() { }; Whitebox.setInternalState(tested, fieldName, (Object) null); - assertEquals(value, Whitebox.getInternalState(tested, fieldName)); + assertEquals(value, (int) Whitebox.getInternalState(tested, fieldName)); } @Test - public void testSetAndGetInternalStateBasedOnFieldType() throws Exception { + public void testSetAndGetInternalStateBasedOnFieldType() { 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", + assertEquals(value, (int) Whitebox.getInternalState(tested, "anotherInternalState")); + assertEquals(value, (int) Whitebox.getInternalState(tested, "anotherInternalState", ClassWithChildThatHasInternalState.class)); } @Test - public void testSetAndGetInternalStateAtASpecificPlaceInTheHierarchyBasedOnFieldType() throws Exception { + public void testSetAndGetInternalStateAtASpecificPlaceInTheHierarchyBasedOnFieldType() { 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)); + assertEquals(value, (int) Whitebox.getInternalState(tested, "staticState", ClassWithInternalState.class)); } @Test - public void testSetInternalStateBasedOnObjectType() throws Exception { + public void testSetInternalStateBasedOnObjectType() { final String value = "a string"; ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState(); Whitebox.setInternalState(tested, value); @@ -438,7 +437,7 @@ public void testSetInternalStateBasedOnObjectType() throws Exception { @SuppressWarnings("deprecation") @Test - public void testSetInternalStateBasedOnObjectTypeWhenArgumentIsAPrimitiveType() throws Exception { + public void testSetInternalStateBasedOnObjectTypeWhenArgumentIsAPrimitiveType() { final int value = 22; ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState(); Whitebox.setInternalState(tested, value); @@ -447,7 +446,7 @@ public void testSetInternalStateBasedOnObjectTypeWhenArgumentIsAPrimitiveType() } @Test - public void testSetInternalStateBasedOnObjectTypeWhenArgumentIsAPrimitiveTypeUsingGenerics() throws Exception { + public void testSetInternalStateBasedOnObjectTypeWhenArgumentIsAPrimitiveTypeUsingGenerics() { final int value = 22; ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState(); Whitebox.setInternalState(tested, value); @@ -456,7 +455,7 @@ public void testSetInternalStateBasedOnObjectTypeWhenArgumentIsAPrimitiveTypeUsi } @Test - public void testSetInternalStateBasedOnObjectTypeAtASpecificPlaceInTheClassHierarchy() throws Exception { + public void testSetInternalStateBasedOnObjectTypeAtASpecificPlaceInTheClassHierarchy() { final String value = "a string"; ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState(); Whitebox.setInternalState(tested, (Object) value, ClassWithInternalState.class); @@ -464,8 +463,7 @@ public void testSetInternalStateBasedOnObjectTypeAtASpecificPlaceInTheClassHiera } @Test - public void testSetInternalStateBasedOnObjectTypeAtASpecificPlaceInTheClassHierarchyForPrimitiveType() - throws Exception { + public void testSetInternalStateBasedOnObjectTypeAtASpecificPlaceInTheClassHierarchyForPrimitiveType() { final long value = 31; ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState(); Whitebox.setInternalState(tested, value, ClassWithInternalState.class); @@ -473,8 +471,7 @@ public void testSetInternalStateBasedOnObjectTypeAtASpecificPlaceInTheClassHiera } @Test - public void testSetInternalStateBasedOnObjectTypeAtANonSpecificPlaceInTheClassHierarchyForPrimitiveType() - throws Exception { + public void testSetInternalStateBasedOnObjectTypeAtANonSpecificPlaceInTheClassHierarchyForPrimitiveType() { final long value = 31; ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState(); Whitebox.setInternalState(tested, value); @@ -482,7 +479,7 @@ public void testSetInternalStateBasedOnObjectTypeAtANonSpecificPlaceInTheClassHi } @Test - public void testSetInternalMultipleOfSameTypeOnSpecificPlaceInHierarchy() throws Exception { + public void testSetInternalMultipleOfSameTypeOnSpecificPlaceInHierarchy() { final int value = 31; ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState(); try { @@ -494,7 +491,7 @@ public void testSetInternalMultipleOfSameTypeOnSpecificPlaceInHierarchy() throws } @Test - public void testSetInternalMultipleOfSameType() throws Exception { + public void testSetInternalMultipleOfSameType() { final int value = 31; ClassWithInternalState tested = new ClassWithInternalState(); try { @@ -506,7 +503,7 @@ public void testSetInternalMultipleOfSameType() throws Exception { } @Test - public void testSetInternalStateBasedOnObjectSubClassTypeAtASpecificPlaceInTheClassHierarchy() throws Exception { + public void testSetInternalStateBasedOnObjectSubClassTypeAtASpecificPlaceInTheClassHierarchy() { final ClassWithPrivateMethods value = new ClassWithPrivateMethods() { }; ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState(); @@ -515,7 +512,7 @@ public void testSetInternalStateBasedOnObjectSubClassTypeAtASpecificPlaceInTheCl } @Test - public void testSetInternalStateBasedOnObjectSubClassType() throws Exception { + public void testSetInternalStateBasedOnObjectSubClassType() { final ClassWithPrivateMethods value = new ClassWithPrivateMethods() { }; ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState() { @@ -525,7 +522,7 @@ public void testSetInternalStateBasedOnObjectSubClassType() throws Exception { } @Test - public void testGetAllInstanceFields() throws Exception { + public void testGetAllInstanceFields() { Set allFields = Whitebox.getAllInstanceFields(new ClassWithChildThatHasInternalState()); assertEquals(8, allFields.size()); } @@ -537,19 +534,19 @@ public void testGetAllInstanceFieldsOnClass() { } @Test - public void testGetAllStaticFields_assertNoFieldsFromParent() throws Exception { + public void testGetAllStaticFields_assertNoFieldsFromParent() { Set allFields = Whitebox.getAllStaticFields(ClassWithChildThatHasInternalState.class); assertEquals(0, allFields.size()); } @Test - public void testGetAllStaticFields() throws Exception { + public void testGetAllStaticFields() { Set allFields = Whitebox.getAllStaticFields(ClassWithInternalState.class); assertEquals(4, allFields.size()); } @Test - public void testMethodWithNoMethodName_noMethodFound() throws Exception { + public void testMethodWithNoMethodName_noMethodFound() { try { Whitebox.getMethod(ClassWithInternalState.class, int.class); fail("Should throw MethodNotFoundException"); @@ -561,7 +558,7 @@ public void testMethodWithNoMethodName_noMethodFound() throws Exception { } @Test - public void testMethodWithNoMethodName_tooManyMethodsFound() throws Exception { + public void testMethodWithNoMethodName_tooManyMethodsFound() { try { Whitebox.getMethod(ClassWithSeveralMethodsWithSameName.class); fail("Should throw TooManyMethodsFoundException"); @@ -580,7 +577,7 @@ public void testMethodWithNoMethodName_ok() throws Exception { } @Test - public void testGetTwoMethodsWhenNoneOfThemAreFound() throws Exception { + public void testGetTwoMethodsWhenNoneOfThemAreFound() { try { Whitebox.getMethods(ClassWithSeveralMethodsWithSameName.class, "notFound1", "notFound2"); } catch (MethodNotFoundException e) { @@ -591,7 +588,7 @@ public void testGetTwoMethodsWhenNoneOfThemAreFound() throws Exception { } @Test - public void testGetThreeMethodsWhenNoneOfThemAreFound() throws Exception { + public void testGetThreeMethodsWhenNoneOfThemAreFound() { try { Whitebox.getMethods(ClassWithSeveralMethodsWithSameName.class, "notFound1", "notFound2", "notFound3"); } catch (MethodNotFoundException e) { @@ -621,7 +618,7 @@ public void testInvokeConstructorWithBothNormalAndVarArgsParameter() throws Exce @Test public void testInvokeMethodWithBothNormalAndVarArgsParameter() throws Exception { ClassWithPrivateMethods tested = new ClassWithPrivateMethods(); - assertEquals(4, Whitebox.invokeMethod(tested, "varArgsMethod2", 1, 2, 3)); + assertEquals(4, (int) Whitebox.invokeMethod(tested, "varArgsMethod2", 1, 2, 3)); } @Test @@ -632,7 +629,7 @@ public void testInvokePrivateMethodWithArrayArgument() throws Exception { } @Test - public void testSetInternalStateFromContext_allStatesInSameOneContext() throws Exception { + public void testSetInternalStateFromContext_allStatesInSameOneContext() { ClassWithSimpleInternalState tested = new ClassWithSimpleInternalState(); MyContext context = new MyContext(); Whitebox.setInternalStateFromContext(tested, context); @@ -641,7 +638,7 @@ public void testSetInternalStateFromContext_allStatesInSameOneContext() throws E } @Test - public void testSetInternalStateFromContext_statesInDifferentContext() throws Exception { + public void testSetInternalStateFromContext_statesInDifferentContext() { ClassWithSimpleInternalState tested = new ClassWithSimpleInternalState(); MyIntContext myIntContext = new MyIntContext(); MyStringContext myStringContext = new MyStringContext(); @@ -651,14 +648,14 @@ public void testSetInternalStateFromContext_statesInDifferentContext() throws Ex } @Test - public void testSetInternalStateFromContext_contextIsAClass() throws Exception { + public void testSetInternalStateFromContext_contextIsAClass() { 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 { + public void testSetInternalStateFromContext_contextIsAClassAndAnInstance() { ClassWithSimpleInternalState tested = new ClassWithSimpleInternalState(); MyContext myContext = new MyContext(); Whitebox.setInternalStateFromContext(tested, MyContext.class, myContext); @@ -668,8 +665,7 @@ public void testSetInternalStateFromContext_contextIsAClassAndAnInstance() throw } @Test - public void testSetInternalStateFromContext_contextHasOneInstanceAndOneStaticFieldOfSameType_onlyInstanceContext() - throws Exception { + public void testSetInternalStateFromContext_contextHasOneInstanceAndOneStaticFieldOfSameType_onlyInstanceContext() { ClassWithStaticAndInstanceInternalStateOfSameType.reset(); ClassWithStaticAndInstanceInternalStateOfSameType tested = new ClassWithStaticAndInstanceInternalStateOfSameType(); OneInstanceAndOneStaticFieldOfSameTypeContext context = new OneInstanceAndOneStaticFieldOfSameTypeContext(); @@ -679,8 +675,7 @@ public void testSetInternalStateFromContext_contextHasOneInstanceAndOneStaticFie } @Test - public void testSetInternalStateFromContext_contextHasOneInstanceAndOneStaticFieldOfSameType_onlyStaticContext() - throws Exception { + public void testSetInternalStateFromContext_contextHasOneInstanceAndOneStaticFieldOfSameType_onlyStaticContext() { ClassWithStaticAndInstanceInternalStateOfSameType.reset(); ClassWithStaticAndInstanceInternalStateOfSameType tested = new ClassWithStaticAndInstanceInternalStateOfSameType(); Whitebox.setInternalStateFromContext(tested, OneInstanceAndOneStaticFieldOfSameTypeContext.class); @@ -690,8 +685,7 @@ public void testSetInternalStateFromContext_contextHasOneInstanceAndOneStaticFie } @Test - public void setInternalStateFromInstanceContextCopiesMatchingContextFieldsToTargetObjectByDefault() - throws Exception { + public void setInternalStateFromInstanceContextCopiesMatchingContextFieldsToTargetObjectByDefault() { ClassWithSimpleInternalState tested = new ClassWithSimpleInternalState(); InstanceFieldsNotInTargetContext fieldsNotInTargetContext = new InstanceFieldsNotInTargetContext(); assertThat(tested.getSomeStringState()).isNotEqualTo(fieldsNotInTargetContext.getString()); @@ -701,8 +695,7 @@ public void setInternalStateFromInstanceContextCopiesMatchingContextFieldsToTarg } @Test - public void setInternalStateFromInstanceContextCopiesMatchingContextFieldsToTargetObjectWhenSpecifyingMatchingStrategy() - throws Exception { + public void setInternalStateFromInstanceContextCopiesMatchingContextFieldsToTargetObjectWhenSpecifyingMatchingStrategy() { ClassWithSimpleInternalState tested = new ClassWithSimpleInternalState(); InstanceFieldsNotInTargetContext fieldsNotInTargetContext = new InstanceFieldsNotInTargetContext(); assertThat(tested.getSomeStringState()).isNotEqualTo(fieldsNotInTargetContext.getString()); @@ -711,8 +704,7 @@ public void setInternalStateFromInstanceContextCopiesMatchingContextFieldsToTarg } @Test(expected = FieldNotFoundException.class) - public void setInternalStateFromInstanceContextThrowsExceptionWhenContextContainsFieldsNotDefinedInTargetObjectWhenSpecifyingStrictStrategy() - throws Exception { + public void setInternalStateFromInstanceContextThrowsExceptionWhenContextContainsFieldsNotDefinedInTargetObjectWhenSpecifyingStrictStrategy() { ClassWithSimpleInternalState tested = new ClassWithSimpleInternalState(); InstanceFieldsNotInTargetContext fieldsNotInTargetContext = new InstanceFieldsNotInTargetContext(); assertThat(tested.getSomeStringState()).isNotEqualTo(fieldsNotInTargetContext.getString()); @@ -721,7 +713,7 @@ public void setInternalStateFromInstanceContextThrowsExceptionWhenContextContain } @Test - public void setInternalStateFromClassContextCopiesMatchingContextFieldsToTargetObjectByDefault() throws Exception { + public void setInternalStateFromClassContextCopiesMatchingContextFieldsToTargetObjectByDefault() { long state = ClassWithSimpleInternalState.getLong(); try { assertThat(state).isNotEqualTo(ClassFieldsNotInTargetContext.getLong()); @@ -735,8 +727,7 @@ public void setInternalStateFromClassContextCopiesMatchingContextFieldsToTargetO } @Test - public void setInternalStateFromClassContextCopiesMatchingContextFieldsToTargetObjectWhenSpecifyingMatchingStrategy() - throws Exception { + public void setInternalStateFromClassContextCopiesMatchingContextFieldsToTargetObjectWhenSpecifyingMatchingStrategy() { long state = ClassWithSimpleInternalState.getLong(); try { assertThat(state).isNotEqualTo(ClassFieldsNotInTargetContext.getLong()); @@ -750,8 +741,7 @@ public void setInternalStateFromClassContextCopiesMatchingContextFieldsToTargetO } @Test(expected = FieldNotFoundException.class) - public void setInternalStateFromClassContextThrowsExceptionWhenContextContainsFieldsNotDefinedInTargetObjectWhenSpecifyingStrictStrategy() - throws Exception { + public void setInternalStateFromClassContextThrowsExceptionWhenContextContainsFieldsNotDefinedInTargetObjectWhenSpecifyingStrictStrategy() { long state = ClassWithSimpleInternalState.getLong(); try { assertThat(state).isNotEqualTo(ClassFieldsNotInTargetContext.getLong()); @@ -764,7 +754,7 @@ public void setInternalStateFromClassContextThrowsExceptionWhenContextContainsFi } @Test - public void assertThatErrorMessageIsCorrectWhenNoInstanceFieldFound() throws Exception { + public void assertThatErrorMessageIsCorrectWhenNoInstanceFieldFound() { ClassWithInternalState classWithInternalState = new ClassWithInternalState(); try { Whitebox.setInternalState(classWithInternalState, (byte) 23); @@ -777,7 +767,7 @@ public void assertThatErrorMessageIsCorrectWhenNoInstanceFieldFound() throws Exc } @Test - public void assertThatErrorMessageIsCorrectWhenNoStaticFieldFound() throws Exception { + public void assertThatErrorMessageIsCorrectWhenNoStaticFieldFound() { try { Whitebox.setInternalState(ClassWithInternalState.class, (byte) 23); fail("Should throw a FieldNotFoundException."); @@ -788,15 +778,14 @@ public void assertThatErrorMessageIsCorrectWhenNoStaticFieldFound() throws Excep } @Test - public void assertThatWhiteboxWorksWithGenericsWhenSpecifyingFieldName() throws Exception { + public void assertThatWhiteboxWorksWithGenericsWhenSpecifyingFieldName() { ClassWithInternalState object = new ClassWithInternalState(); Set state = Whitebox.getInternalState(object, "genericState"); assertSame(object.getGenericState(), state); } @Test - public void whiteboxGetMethodWithCorrectMethodNameButWrongParameterTypeReturnsErrorMessageReflectingTheWrongParameter() - throws Exception { + public void whiteboxGetMethodWithCorrectMethodNameButWrongParameterTypeReturnsErrorMessageReflectingTheWrongParameter() { try { Whitebox.getMethod(ClassWithInternalState.class, "methodWithArgument", String.class, InputStream.class); fail("Should throw MethodNotFoundException"); @@ -861,18 +850,18 @@ public void invokeMethodInvokesOverridenMethods() throws Exception { } @Test(expected = IllegalArgumentException.class) - public void newInstanceThrowsIAEWhenClassIsAbstract() throws Exception { + public void newInstanceThrowsIAEWhenClassIsAbstract() { Whitebox.newInstance(AbstractClass.class); } @Test - public void newInstanceReturnsJavaProxyWhenInterface() throws Exception { + public void newInstanceReturnsJavaProxyWhenInterface() { AnInterface instance = Whitebox.newInstance(AnInterface.class); assertTrue(Proxy.isProxyClass(instance.getClass())); } @Test - public void newInstanceCreatesAnEmptyArrayWhenClassIsArray() throws Exception { + public void newInstanceCreatesAnEmptyArrayWhenClassIsArray() { byte[] newInstance = Whitebox.newInstance(byte[].class); assertEquals(0, newInstance.length); } @@ -908,7 +897,8 @@ public void canPassNullPrimitiveArraysToAPrivateStaticMethod() throws Exception @Test public void canPassMultipleNullValuesToStaticMethod() throws Exception { - assertEquals("null null", Whitebox.invokeMethod(ClassWithStaticMethod.class, "anotherStaticMethod", (Object) null, (byte[]) null)); + assertEquals("null null", Whitebox.invokeMethod(ClassWithStaticMethod.class, "anotherStaticMethod", (Object) null, + null)); } diff --git a/powermock-reflect/src/test/java/org/powermock/reflect/context/ClassFieldsNotInTargetContext.java b/powermock-reflect/src/test/java/org/powermock/reflect/context/ClassFieldsNotInTargetContext.java index 9a713862b..5c263681a 100644 --- a/powermock-reflect/src/test/java/org/powermock/reflect/context/ClassFieldsNotInTargetContext.java +++ b/powermock-reflect/src/test/java/org/powermock/reflect/context/ClassFieldsNotInTargetContext.java @@ -26,7 +26,7 @@ public class ClassFieldsNotInTargetContext { private static long something = 42L; - private static Map map = new HashMap(); + private static Map map = new HashMap<>(); public static long getLong() { return something; diff --git a/powermock-reflect/src/test/java/org/powermock/reflect/context/InstanceFieldsNotInTargetContext.java b/powermock-reflect/src/test/java/org/powermock/reflect/context/InstanceFieldsNotInTargetContext.java index a54a6eab3..5c044f6e7 100644 --- a/powermock-reflect/src/test/java/org/powermock/reflect/context/InstanceFieldsNotInTargetContext.java +++ b/powermock-reflect/src/test/java/org/powermock/reflect/context/InstanceFieldsNotInTargetContext.java @@ -26,7 +26,7 @@ public class InstanceFieldsNotInTargetContext { private String something = "something"; - private Map map = new HashMap(); + private Map map = new HashMap<>(); public String getString() { return something; diff --git a/powermock-reflect/src/test/java/org/powermock/reflect/internal/WhiteboxImplTest.java b/powermock-reflect/src/test/java/org/powermock/reflect/internal/WhiteboxImplTest.java index 14b9b2044..2104a981a 100644 --- a/powermock-reflect/src/test/java/org/powermock/reflect/internal/WhiteboxImplTest.java +++ b/powermock-reflect/src/test/java/org/powermock/reflect/internal/WhiteboxImplTest.java @@ -16,14 +16,17 @@ package org.powermock.reflect.internal; import org.junit.Test; -import org.powermock.reflect.testclasses.*; +import org.powermock.reflect.testclasses.Child; +import org.powermock.reflect.testclasses.ClassWithMethodUsingBothPrimitiveTypeAndWrappedTypeArguments; +import org.powermock.reflect.testclasses.ClassWithOverloadedMethods; +import org.powermock.reflect.testclasses.ClassWithStandardMethod; 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.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assume.assumeTrue; @@ -73,10 +76,10 @@ public void getBestCandidateMethodReturnsMatchingMethodWhenOverloading() throws @Test public void defaultMethodsAreFound() throws Exception { - assumeTrue(Float.valueOf(System.getProperty("java.specification.version")) >= 1.8f); + assumeTrue(Float.parseFloat(System.getProperty("java.specification.version")) >= 1.8f); Method[] methods = WhiteboxImpl.getAllMethods(Collection.class); - List methodNames = new ArrayList(); + List methodNames = new ArrayList<>(); for (Method method : methods) { methodNames.add(method.getName()); } diff --git a/powermock-reflect/src/test/java/org/powermock/reflect/internal/proxy/ProxyFrameworksTest.java b/powermock-reflect/src/test/java/org/powermock/reflect/internal/proxy/ProxyFrameworksTest.java index e4f329953..862f35f6c 100644 --- a/powermock-reflect/src/test/java/org/powermock/reflect/internal/proxy/ProxyFrameworksTest.java +++ b/powermock-reflect/src/test/java/org/powermock/reflect/internal/proxy/ProxyFrameworksTest.java @@ -1,12 +1,8 @@ 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; @@ -14,7 +10,11 @@ import java.util.Enumeration; import java.util.List; -import static org.assertj.core.api.Java6Assertions.assertThat; +import net.sf.cglib.proxy.Enhancer; +import net.sf.cglib.proxy.Factory; +import net.sf.cglib.proxy.InvocationHandler; + +import static org.assertj.core.api.Assertions.assertThat; public class ProxyFrameworksTest { @@ -67,7 +67,7 @@ public void should_not_detect_synthetic_classes_as_cglib_proxy() throws Exceptio final ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); final Enumeration resources = classLoader.getResources("org/powermock/reflect/internal/proxy"); - final List urls = new ArrayList(); + final List urls = new ArrayList<>(); while (resources.hasMoreElements()) { urls.add(resources.nextElement()); @@ -75,7 +75,7 @@ public void should_not_detect_synthetic_classes_as_cglib_proxy() throws Exceptio String className = "Some$$SyntheticClass$$Lambda"; byte[] bytes = ClassFactory.create(className); - CustomClassLoader customClassLoader = new CustomClassLoader(urls.toArray(new URL[urls.size()]), classLoader); + CustomClassLoader customClassLoader = new CustomClassLoader(urls.toArray(new URL[0]), classLoader); Class defineClass = customClassLoader.defineClass(className, bytes); @@ -131,23 +131,11 @@ public void should_return_interfaces_if_proxy_create_from_several_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); - } - }); + superclass, (InvocationHandler) (o, method, objects) -> 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); - } - }); + interfaces, (InvocationHandler) (o, method, objects) -> method.invoke(o, objects)); } } @@ -155,13 +143,7 @@ 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); - } - }); + interfaces, (proxy, method, args) -> method.invoke(proxy, args)); } private void assertThatOriginalIsNullAndInterfaces(UnproxiedType unproxiedType, Class[] expectedInterfaces) { diff --git a/powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithInternalState.java b/powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithInternalState.java index bcb8806ac..e35dce7e6 100644 --- a/powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithInternalState.java +++ b/powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithInternalState.java @@ -39,7 +39,7 @@ public class ClassWithInternalState { private String[] stringArray = new String[0]; - private Set genericState = new HashSet(); + private Set genericState = new HashSet<>(); private ClassWithPrivateMethods classWithPrivateMethods; diff --git a/powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithList.java b/powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithList.java index 7b399dba9..1f2e6e32f 100644 --- a/powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithList.java +++ b/powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithList.java @@ -21,6 +21,6 @@ public class ClassWithList { @SuppressWarnings("unused") - private List list = new LinkedList(); + private List list = new LinkedList<>(); } diff --git a/powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithPrivateMethods.java b/powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithPrivateMethods.java index 07337d730..a43d61f1c 100644 --- a/powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithPrivateMethods.java +++ b/powermock-reflect/src/test/java/org/powermock/reflect/testclasses/ClassWithPrivateMethods.java @@ -19,51 +19,51 @@ @SuppressWarnings("unused") public class ClassWithPrivateMethods { - private boolean primitiveMethod(double value) { - return true; - } + private boolean primitiveMethod(double value) { + return true; + } - private boolean wrappedMethod(Double value) { - return true; - } + private boolean wrappedMethod(Double value) { + return true; + } - private String methodWithPrimitiveIntAndString(int myInt, String aString) { - return aString + Integer.toString(myInt); - } + private String methodWithPrimitiveIntAndString(int myInt, String aString) { + return aString + myInt; + } - private int methodWithPrimitiveAndWrappedInt(int myInt, Integer myInt2) { - return myInt + myInt2; - } + 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 String evilConcatOfStrings(String[] strings) { + StringBuilder returnValue = new StringBuilder(); + for (String string : strings) { + returnValue.append(string); + } + return returnValue.toString(); + } - private int varArgsMethod(int... ints) { - int sum = 0; - for (int i : ints) { - sum += i; - } - return sum; - } + private int varArgsMethod(int... ints) { + int sum = 0; + for (int i : ints) { + sum += i; + } + return sum; + } - private ClassWithInternalState methodWithObjectArgument(ClassWithInternalState c) { - return c; - } + private ClassWithInternalState methodWithObjectArgument(ClassWithInternalState c) { + return c; + } - private Class methodWithClassArgument(Class c) { - return c; - } + private Class methodWithClassArgument(Class c) { + return c; + } - private int varArgsMethod(int value) { - return value * 2; - } + private int varArgsMethod(int value) { + return value * 2; + } - private int varArgsMethod2(int value, int... moreValues) { - return value * 2 + moreValues.length; - } + private int varArgsMethod2(int value, int... moreValues) { + return value * 2 + moreValues.length; + } } diff --git a/tests/build.gradle b/tests/build.gradle index 03e8db51e..7fd7d9041 100644 --- a/tests/build.gradle +++ b/tests/build.gradle @@ -16,10 +16,6 @@ configure(subprojects) { project -> } apply from: "${gradleScriptDir}/java-module.gradle" - - test { - jvmArgs "-XX:MaxPermSize=256m" - } } project(":tests:utils"){ diff --git a/tests/easymock/junit4-agent/src/test/java/samples/powermockito/junit4/agent/AnnotationUsageTest.java b/tests/easymock/junit4-agent/src/test/java/samples/powermockito/junit4/agent/AnnotationUsageTest.java index 02ab73068..684ac525c 100644 --- a/tests/easymock/junit4-agent/src/test/java/samples/powermockito/junit4/agent/AnnotationUsageTest.java +++ b/tests/easymock/junit4-agent/src/test/java/samples/powermockito/junit4/agent/AnnotationUsageTest.java @@ -24,11 +24,12 @@ 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 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.replay; diff --git a/tests/easymock/junit4-agent/src/test/java/samples/powermockito/junit4/agent/LargeMethodTest.java b/tests/easymock/junit4-agent/src/test/java/samples/powermockito/junit4/agent/LargeMethodTest.java index 7063a1da9..040597602 100644 --- a/tests/easymock/junit4-agent/src/test/java/samples/powermockito/junit4/agent/LargeMethodTest.java +++ b/tests/easymock/junit4-agent/src/test/java/samples/powermockito/junit4/agent/LargeMethodTest.java @@ -4,14 +4,15 @@ import org.junit.Test; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.rule.PowerMockRule; + import samples.largemethod.MethodExceedingJvmLimit; +import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.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; diff --git a/tests/easymock/junit4/src/test/java/demo/org/powermock/modules/test/junit4/failure/AssertThatJUnit4FailuresWorkTest.java b/tests/easymock/junit4/src/test/java/demo/org/powermock/modules/test/junit4/failure/AssertThatJUnit4FailuresWorkTest.java index 41bef70b4..319a68bc5 100644 --- a/tests/easymock/junit4/src/test/java/demo/org/powermock/modules/test/junit4/failure/AssertThatJUnit4FailuresWorkTest.java +++ b/tests/easymock/junit4/src/test/java/demo/org/powermock/modules/test/junit4/failure/AssertThatJUnit4FailuresWorkTest.java @@ -22,7 +22,6 @@ 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.PowerMockJUnit4RunnerDelegateImpl; import static org.junit.Assert.assertTrue; diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/abstractmocking/AbstractMethodMockingTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/abstractmocking/AbstractMethodMockingTest.java index 4d9ccc898..a9caf9c6c 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/abstractmocking/AbstractMethodMockingTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/abstractmocking/AbstractMethodMockingTest.java @@ -4,10 +4,14 @@ 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.*; +import static org.powermock.api.easymock.PowerMock.createPartialMock; +import static org.powermock.api.easymock.PowerMock.expectPrivate; +import static org.powermock.api.easymock.PowerMock.replay; +import static org.powermock.api.easymock.PowerMock.verify; @RunWith(PowerMockRunner.class) @PrepareForTest(AbstractMethodMocking.class) diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/annotationbased/AnnotationDemoWithSetupMethodTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/annotationbased/AnnotationDemoWithSetupMethodTest.java index 7e376aada..fa6b1b857 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/annotationbased/AnnotationDemoWithSetupMethodTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/annotationbased/AnnotationDemoWithSetupMethodTest.java @@ -3,7 +3,9 @@ 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.PowerMockRunner; + import samples.Service; import samples.annotationbased.AnnotationDemo; @@ -18,7 +20,7 @@ @RunWith(PowerMockRunner.class) public class AnnotationDemoWithSetupMethodTest { - @org.powermock.api.easymock.annotation.Mock + @Mock private Service serviceMock; private AnnotationDemo tested; diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/annotationbased/FinalDemoWithAnnotationInjectionAndFieldDefaulterTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/annotationbased/FinalDemoWithAnnotationInjectionAndFieldDefaulterTest.java index 271234a84..7204f7f8d 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/annotationbased/FinalDemoWithAnnotationInjectionAndFieldDefaulterTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/annotationbased/FinalDemoWithAnnotationInjectionAndFieldDefaulterTest.java @@ -22,6 +22,7 @@ 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; diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/annotationbased/FinalDemoWithAnnotationInjectionTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/annotationbased/FinalDemoWithAnnotationInjectionTest.java index 616933c21..154d110b7 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/annotationbased/FinalDemoWithAnnotationInjectionTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/annotationbased/FinalDemoWithAnnotationInjectionTest.java @@ -20,6 +20,7 @@ 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; diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/annotationbased/FinalDemoWithNiceAnnotationInjectionTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/annotationbased/FinalDemoWithNiceAnnotationInjectionTest.java index 338bd788b..efa764cca 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/annotationbased/FinalDemoWithNiceAnnotationInjectionTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/annotationbased/FinalDemoWithNiceAnnotationInjectionTest.java @@ -20,6 +20,7 @@ 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; diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/annotationbased/FinalDemoWithStrictAnnotationInjectionTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/annotationbased/FinalDemoWithStrictAnnotationInjectionTest.java index 4644f538a..409ee4dbf 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/annotationbased/FinalDemoWithStrictAnnotationInjectionTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/annotationbased/FinalDemoWithStrictAnnotationInjectionTest.java @@ -21,6 +21,7 @@ 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; diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/annotationbased/TestSubjectEasymockAnnotationTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/annotationbased/TestSubjectEasymockAnnotationTest.java index 04ccb7cdc..773200ce4 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/annotationbased/TestSubjectEasymockAnnotationTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/annotationbased/TestSubjectEasymockAnnotationTest.java @@ -5,6 +5,7 @@ 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; diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/annotationbased/TestSubjectPowermockAnnotationTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/annotationbased/TestSubjectPowermockAnnotationTest.java index b8cc9501a..d968d8cce 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/annotationbased/TestSubjectPowermockAnnotationTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/annotationbased/TestSubjectPowermockAnnotationTest.java @@ -7,6 +7,7 @@ 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; diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/classhierarchy/CommonParentTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/classhierarchy/CommonParentTest.java index 8a8b7adc4..450555167 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/classhierarchy/CommonParentTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/classhierarchy/CommonParentTest.java @@ -21,6 +21,7 @@ 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; diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/classwithinnermembers/ClassWithInnerMembersTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/classwithinnermembers/ClassWithInnerMembersTest.java index cc8f3cc35..661aad674 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/classwithinnermembers/ClassWithInnerMembersTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/classwithinnermembers/ClassWithInnerMembersTest.java @@ -20,10 +20,15 @@ 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.*; +import static org.powermock.api.easymock.PowerMock.createMock; +import static org.powermock.api.easymock.PowerMock.expectNew; +import static org.powermock.api.easymock.PowerMock.expectPrivate; +import static org.powermock.api.easymock.PowerMock.replayAll; +import static org.powermock.api.easymock.PowerMock.verifyAll; /** * Test PowerMock's basic support for inner (member) and local classes. diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/constructor/PrivateConstructorInstantiationDemoTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/constructor/PrivateConstructorInstantiationDemoTest.java index 39320bbd1..dbadfea96 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/constructor/PrivateConstructorInstantiationDemoTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/constructor/PrivateConstructorInstantiationDemoTest.java @@ -16,6 +16,7 @@ package samples.junit4.constructor; import org.junit.Test; + import samples.constructor.PrivateConstructorInstantiationDemo; import static org.junit.Assert.assertEquals; diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/constructor/PublicConstructorWithDependencyDemoTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/constructor/PublicConstructorWithDependencyDemoTest.java index c39fb83ed..8bd85162f 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/constructor/PublicConstructorWithDependencyDemoTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/constructor/PublicConstructorWithDependencyDemoTest.java @@ -19,11 +19,14 @@ 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.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.fail; import static org.powermock.api.easymock.PowerMock.createPartialMock; /** diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/constructorargs/ConstructorArgsDemoTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/constructorargs/ConstructorArgsDemoTest.java index 2813772ee..e2c74d8f9 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/constructorargs/ConstructorArgsDemoTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/constructorargs/ConstructorArgsDemoTest.java @@ -21,13 +21,18 @@ 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 samples.constructorargs.ConstructorArgsDemo; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; -import static org.powermock.api.easymock.PowerMock.*; +import static org.powermock.api.easymock.PowerMock.createMock; +import static org.powermock.api.easymock.PowerMock.createPartialMock; +import static org.powermock.api.easymock.PowerMock.expectPrivate; +import static org.powermock.api.easymock.PowerMock.replay; +import static org.powermock.api.easymock.PowerMock.verify; /** * This test demonstrates the ability to invoke a specific constructor after diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/easymock/EasyMockAndPowerMockMixTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/easymock/EasyMockAndPowerMockMixTest.java index dfa07392f..11f1e9659 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/easymock/EasyMockAndPowerMockMixTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/easymock/EasyMockAndPowerMockMixTest.java @@ -4,10 +4,14 @@ 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.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; import static org.junit.Assert.assertEquals; import static org.powermock.reflect.Whitebox.setInternalState; diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/enummocking/EnumMockingTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/enummocking/EnumMockingTest.java index f9873bc10..790b5b83d 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/enummocking/EnumMockingTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/enummocking/EnumMockingTest.java @@ -5,10 +5,13 @@ 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.*; +import static org.powermock.api.easymock.PowerMock.mockStatic; +import static org.powermock.api.easymock.PowerMock.replayAll; +import static org.powermock.api.easymock.PowerMock.verifyAll; @RunWith(PowerMockRunner.class) @PrepareForTest(MyEnum.class) diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/equalswithgetclass/EqualsWithGetClassTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/equalswithgetclass/EqualsWithGetClassTest.java index 23db33462..7851b19c9 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/equalswithgetclass/EqualsWithGetClassTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/equalswithgetclass/EqualsWithGetClassTest.java @@ -20,6 +20,7 @@ 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; diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/expectnew/ExpectNewCases.java b/tests/easymock/junit4/src/test/java/samples/junit4/expectnew/ExpectNewCases.java index 55664d529..a1b2216d9 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/expectnew/ExpectNewCases.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/expectnew/ExpectNewCases.java @@ -3,6 +3,12 @@ import org.junit.Test; import org.powermock.reflect.Whitebox; import org.powermock.reflect.exceptions.ConstructorNotFoundException; + +import java.io.ByteArrayInputStream; +import java.io.DataInputStream; +import java.io.IOException; +import java.io.InputStream; + import samples.Service; import samples.expectnew.CreationException; import samples.expectnew.ExpectNewDemo; @@ -12,12 +18,7 @@ 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.assertj.core.api.Assertions.assertThat; import static org.easymock.EasyMock.aryEq; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.expectLastCall; @@ -467,12 +468,7 @@ public void testNewWithVarArgsConstructorWhenOneArgumentIsOfASubType() throws Ex Service serviceMock = createMock(Service.class); VarArgsConstructorDemo varArgsConstructorDemoMock = createMock(VarArgsConstructorDemo.class); - final Service serviceSubTypeInstance = new Service() { - - public String getServiceMessage() { - return "message"; - } - }; + final Service serviceSubTypeInstance = () -> "message"; expectNew(VarArgsConstructorDemo.class, serviceSubTypeInstance, serviceMock).andReturn(varArgsConstructorDemoMock); expect(varArgsConstructorDemoMock.getAllServices()).andReturn(new Service[] { serviceMock }); diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/expectnew/ExpectNewDemoTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/expectnew/ExpectNewDemoTest.java index 07a3f0300..a6a5bc865 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/expectnew/ExpectNewDemoTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/expectnew/ExpectNewDemoTest.java @@ -18,11 +18,12 @@ 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; +import samples.expectnew.ExpectNewDemo; +import samples.newmocking.MyClass; + /** * Test class to demonstrate new instance mocking using expectNew(..). * diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/expectnew/ExpectNewOfFinalSystemClassTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/expectnew/ExpectNewOfFinalSystemClassTest.java index ad460862b..15aa1227f 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/expectnew/ExpectNewOfFinalSystemClassTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/expectnew/ExpectNewOfFinalSystemClassTest.java @@ -4,11 +4,15 @@ 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.*; +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) diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/expectnew/MockDateTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/expectnew/MockDateTest.java index d6830fbfb..6107947e1 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/expectnew/MockDateTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/expectnew/MockDateTest.java @@ -23,10 +23,11 @@ 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; +import samples.expectnew.ExpectNewDemo; + @RunWith(PowerMockRunner.class) @PrepareForTest( { ExpectNewDemo.class }) public class MockDateTest { @@ -47,7 +48,7 @@ public void testMockDate() throws Exception { @Test public void testMockDateWithEasyMock() throws Exception { Date someDate = new Date(); - MocksControl c = (MocksControl) org.easymock.EasyMock.createControl(); + MocksControl c = (MocksControl) EasyMock.createControl(); Date date = c.createMock(Date.class); EasyMock.expect(date.after(someDate)).andReturn(false); @@ -61,7 +62,7 @@ public void testMockDateWithEasyMock() throws Exception { @Test(expected = IllegalStateException.class) public void testMockDateWithEasyMockFails() { Date someDate = new Date(); - MocksControl c = (MocksControl) org.easymock.EasyMock.createControl(); + MocksControl c = (MocksControl) 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"); diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/expectnew/PrimitiveAndWrapperDemoTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/expectnew/PrimitiveAndWrapperDemoTest.java index aebde496e..c750668e3 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/expectnew/PrimitiveAndWrapperDemoTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/expectnew/PrimitiveAndWrapperDemoTest.java @@ -4,6 +4,7 @@ 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; diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/expectnew/PrimitiveAndWrapperUserTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/expectnew/PrimitiveAndWrapperUserTest.java index 9779cb511..c208c9763 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/expectnew/PrimitiveAndWrapperUserTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/expectnew/PrimitiveAndWrapperUserTest.java @@ -4,12 +4,16 @@ 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.*; +import static org.powermock.api.easymock.PowerMock.createNiceMockAndExpectNew; +import static org.powermock.api.easymock.PowerMock.createStrictMockAndExpectNew; +import static org.powermock.api.easymock.PowerMock.replayAll; +import static org.powermock.api.easymock.PowerMock.verifyAll; /** * Unit test for the {@link PrimitiveAndWrapperUser} class. diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/expectvoid/ExpectVoidDemoTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/expectvoid/ExpectVoidDemoTest.java index 3514a4304..4dd1a417d 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/expectvoid/ExpectVoidDemoTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/expectvoid/ExpectVoidDemoTest.java @@ -21,9 +21,14 @@ 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.*; +import static org.powermock.api.easymock.PowerMock.createPartialMock; +import static org.powermock.api.easymock.PowerMock.expectLastCall; +import static org.powermock.api.easymock.PowerMock.expectPrivate; +import static org.powermock.api.easymock.PowerMock.replay; +import static org.powermock.api.easymock.PowerMock.verify; @RunWith(PowerMockRunner.class) @PrepareForTest(ExpectVoidDemo.class) diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/finalmocking/FinalDemoTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/finalmocking/FinalDemoTest.java index a2ab90b1d..52f0565e8 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/finalmocking/FinalDemoTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/finalmocking/FinalDemoTest.java @@ -19,12 +19,15 @@ 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.*; +import static org.powermock.api.easymock.PowerMock.createMock; +import static org.powermock.api.easymock.PowerMock.replay; +import static org.powermock.api.easymock.PowerMock.verify; /** * Test class to demonstrate non-static final mocking. diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/finalmocking/MockingOfInstanceMethodsInFinalSystemClassTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/finalmocking/MockingOfInstanceMethodsInFinalSystemClassTest.java index 1c813d3d4..291bc920f 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/finalmocking/MockingOfInstanceMethodsInFinalSystemClassTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/finalmocking/MockingOfInstanceMethodsInFinalSystemClassTest.java @@ -22,7 +22,10 @@ import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertEquals; -import static org.powermock.api.easymock.PowerMock.*; +import static org.powermock.api.easymock.PowerMock.createMock; +import static org.powermock.api.easymock.PowerMock.createPartialMock; +import static org.powermock.api.easymock.PowerMock.replayAll; +import static org.powermock.api.easymock.PowerMock.verifyAll; /** * Test class to demonstrate non-static final mocking of instance methods in @@ -32,52 +35,52 @@ @PrepareForTest(MockingOfInstanceMethodsInFinalSystemClassTest.class) public class MockingOfInstanceMethodsInFinalSystemClassTest { - @Test - public void assertThatMockingOfInstanceMethodsInFinalSystemClassesWorks() throws Exception { - Long tested = createMock(Long.class); - expect(tested.longValue()).andReturn(22L); - replayAll(); + @Test + public void assertThatMockingOfInstanceMethodsInFinalSystemClassesWorks() throws Exception { + Long tested = createMock(Long.class); + expect(tested.longValue()).andReturn(22L); + replayAll(); - assertEquals(22L, tested.longValue()); + assertEquals(22L, tested.longValue()); - verifyAll(); - } + verifyAll(); + } - @Test - public void assertThatMockingOfInstanceMethodsInStringWorks() throws Exception { - String tested = createMock(String.class); - expect(tested.charAt(2)).andReturn('A'); - replayAll(); + @Test + public void assertThatMockingOfInstanceMethodsInStringWorks() throws Exception { + String tested = createMock(String.class); + expect(tested.charAt(2)).andReturn('A'); + replayAll(); - assertEquals('A', tested.charAt(2)); + assertEquals('A', tested.charAt(2)); - verifyAll(); - } + verifyAll(); + } - @Test - public void assertThatPartialMockingOfInstanceMethodsInFinalSystemClassesWhenNotInvokingConstructorWorks() - throws Exception { - Long tested = createPartialMock(Long.class, "doubleValue"); - expect(tested.doubleValue()).andReturn(54d); - replayAll(); + @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); + assertEquals(0, tested.longValue()); + assertEquals(54d, tested.doubleValue(), 0.0d); - verifyAll(); - } + verifyAll(); + } - @Test - public void assertThatPartialMockingOfInstanceMethodsInFinalSystemClassesWhenNotInvokingNonDefaultConstructorWorks() - throws Exception { - Long tested = createPartialMock(Long.class, new String[] { "doubleValue" }, 27L); - expect(tested.doubleValue()).andReturn(54d); - replayAll(); + @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); + assertEquals(27L, tested.longValue()); + assertEquals(54d, tested.doubleValue(), 0.0d); - verifyAll(); - } + verifyAll(); + } } diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/finalmocking/NoDuplicateTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/finalmocking/NoDuplicateTest.java index 101550fa5..d3c4e8591 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/finalmocking/NoDuplicateTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/finalmocking/NoDuplicateTest.java @@ -19,12 +19,15 @@ 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.*; +import static org.powermock.api.easymock.PowerMock.createMock; +import static org.powermock.api.easymock.PowerMock.replay; +import static org.powermock.api.easymock.PowerMock.verify; /** * This test demonstrates that the issue at diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/hashcode/PowerMockUsesIdentityHashMapToStoreMocks.java b/tests/easymock/junit4/src/test/java/samples/junit4/hashcode/PowerMockUsesIdentityHashMapToStoreMocks.java index 3a22af7db..0280b6770 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/hashcode/PowerMockUsesIdentityHashMapToStoreMocks.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/hashcode/PowerMockUsesIdentityHashMapToStoreMocks.java @@ -18,6 +18,7 @@ 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; diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/interfacefieldchange/ChangeValueOfStaticFinalFieldInInterfacesDefect.java b/tests/easymock/junit4/src/test/java/samples/junit4/interfacefieldchange/ChangeValueOfStaticFinalFieldInInterfacesDefect.java index 5b13f20b9..9205addda 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/interfacefieldchange/ChangeValueOfStaticFinalFieldInInterfacesDefect.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/interfacefieldchange/ChangeValueOfStaticFinalFieldInInterfacesDefect.java @@ -21,6 +21,7 @@ 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; diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/java/MockClassesInsideJavaPackage.java b/tests/easymock/junit4/src/test/java/samples/junit4/java/MockClassesInsideJavaPackage.java index 1d6f2fc65..9f6b174be 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/java/MockClassesInsideJavaPackage.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/java/MockClassesInsideJavaPackage.java @@ -19,11 +19,14 @@ 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.*; +import static org.powermock.api.easymock.PowerMock.createMock; +import static org.powermock.api.easymock.PowerMock.replayAll; +import static org.powermock.api.easymock.PowerMock.verifyAll; @RunWith(PowerMockRunner.class) @PrepareForTest(ClassInsideJavaPackage.class) diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/largemethod/LargeMethodTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/largemethod/LargeMethodTest.java index 731695e16..8b551d0fd 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/largemethod/LargeMethodTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/largemethod/LargeMethodTest.java @@ -21,14 +21,15 @@ import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; + import samples.largemethod.MethodExceedingJvmLimit; +import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.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; diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/misc/PrivateInnerInterfacesInTestClassTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/misc/PrivateInnerInterfacesInTestClassTest.java index e1c479f68..0b300e01f 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/misc/PrivateInnerInterfacesInTestClassTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/misc/PrivateInnerInterfacesInTestClassTest.java @@ -11,17 +11,13 @@ @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()); - } + @Test + public void privateInterfacesCanBeLoadedAndBytecodeManipulatedByPowerMock() throws Exception { + InnerInterface innerInterface = () -> "ok"; + assertEquals("ok", innerInterface.aMethod()); + } - private interface InnerInterface { - String aMethod(); - } + private interface InnerInterface { + String aMethod(); + } } diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/mockpolicy/MockPolicyUsageExampleTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/mockpolicy/MockPolicyUsageExampleTest.java index aae31e7e4..2bbf40e44 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/mockpolicy/MockPolicyUsageExampleTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/mockpolicy/MockPolicyUsageExampleTest.java @@ -23,11 +23,12 @@ 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 samples.mockpolicy.ResultCalculator; +import samples.mockpolicy.SomeClassWithAMethod; + import static org.junit.Assert.assertEquals; /** diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/mockpolicy/MockPolicyWithExpectationsTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/mockpolicy/MockPolicyWithExpectationsTest.java index d3114425f..ba826a948 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/mockpolicy/MockPolicyWithExpectationsTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/mockpolicy/MockPolicyWithExpectationsTest.java @@ -24,14 +24,17 @@ 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 samples.mockpolicy.ResultCalculator; +import samples.mockpolicy.SimpleClassWithADependency; + import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertEquals; -import static org.powermock.api.easymock.PowerMock.*; +import static org.powermock.api.easymock.PowerMock.createMock; +import static org.powermock.api.easymock.PowerMock.replay; +import static org.powermock.api.easymock.PowerMock.verifyAll; @RunWith(PowerMockRunner.class) @MockPolicy(MockPolicyExpectationsExample.class) diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/mockpolicy/MockPolicyWithInvocationHandlerTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/mockpolicy/MockPolicyWithInvocationHandlerTest.java index c6ba5be87..1efc90671 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/mockpolicy/MockPolicyWithInvocationHandlerTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/mockpolicy/MockPolicyWithInvocationHandlerTest.java @@ -24,12 +24,10 @@ 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; @@ -38,32 +36,28 @@ @MockPolicy(MockPolicyInvocationHandlerExample.class) public class MockPolicyWithInvocationHandlerTest { - @Test + @Test public void mockPolicyWithInvocationHandlerWorks() { - final SimpleClassWithADependency tested = new SimpleClassWithADependency(); - Whitebox.setInternalState(tested, new ResultCalculator(0)); + final SimpleClassWithADependency tested = new SimpleClassWithADependency(); + Whitebox.setInternalState(tested, new ResultCalculator(0)); - assertEquals(1.0, tested.getResult(), 0.0); + assertEquals(1.0, tested.getResult(), 0.0); - verifyAll(); - } + 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; - } - }); - } + @Override + public void applyClassLoadingPolicy(MockPolicyClassLoadingSettings settings) { + settings.addFullyQualifiedNamesOfClassesToLoadByMockClassloader(ResultCalculator.class.getName()); + } + + @Override + public void applyInterceptionPolicy(MockPolicyInterceptionSettings settings) { + settings.proxyMethod(method(ResultCalculator.class, "calculate"), (object, method, args) -> { + final double result = (Double) method.invoke(object, args); + return result + 1.0; + }); + } } diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/mockpolicy/frameworkexample/SimpleFrameworkMockPolicy.java b/tests/easymock/junit4/src/test/java/samples/junit4/mockpolicy/frameworkexample/SimpleFrameworkMockPolicy.java index 6c0107de4..850c9c35e 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/mockpolicy/frameworkexample/SimpleFrameworkMockPolicy.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/mockpolicy/frameworkexample/SimpleFrameworkMockPolicy.java @@ -19,11 +19,12 @@ 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; +import samples.mockpolicy.frameworkexample.NativeResult; +import samples.mockpolicy.frameworkexample.SimpleFramework; + public class SimpleFrameworkMockPolicy implements PowerMockPolicy { public static final String NATIVE_RESULT_VALUE = "result"; diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/mockpolicy/frameworkexample/SimpleFrameworkUserTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/mockpolicy/frameworkexample/SimpleFrameworkUserTest.java index fd629793a..a1bf2bb69 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/mockpolicy/frameworkexample/SimpleFrameworkUserTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/mockpolicy/frameworkexample/SimpleFrameworkUserTest.java @@ -19,6 +19,7 @@ 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; diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/multireplayverify/MultiReplayVerifyTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/multireplayverify/MultiReplayVerifyTest.java index 1557c6b1e..a624f5875 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/multireplayverify/MultiReplayVerifyTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/multireplayverify/MultiReplayVerifyTest.java @@ -4,12 +4,18 @@ 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.*; +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.replayAll; +import static org.powermock.api.easymock.PowerMock.verify; +import static org.powermock.api.easymock.PowerMock.verifyAll; /** * Asserts that it's ok the manually replay a mock and then use replayAll(). The diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/nativemocking/NativeMockingSampleTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/nativemocking/NativeMockingSampleTest.java index 261dd714a..f3be67412 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/nativemocking/NativeMockingSampleTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/nativemocking/NativeMockingSampleTest.java @@ -16,10 +16,14 @@ package samples.junit4.nativemocking; import org.junit.Test; + import samples.nativemocking.NativeMockingSample; import samples.nativemocking.NativeService; -import static org.easymock.EasyMock.*; +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; import static org.junit.Assert.assertEquals; /** diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/newmocking/StupidNewTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/newmocking/StupidNewTest.java index 46730723c..fb9ccd141 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/newmocking/StupidNewTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/newmocking/StupidNewTest.java @@ -19,13 +19,16 @@ 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.*; +import static org.powermock.api.easymock.PowerMock.createMockAndExpectNew; +import static org.powermock.api.easymock.PowerMock.replay; +import static org.powermock.api.easymock.PowerMock.verify; /** * Test class to demonstrate new instance mocking. diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/nice/NiceDemoTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/nice/NiceDemoTest.java index 5794daf82..f7342f132 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/nice/NiceDemoTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/nice/NiceDemoTest.java @@ -3,9 +3,12 @@ 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.*; +import static org.powermock.api.easymock.PowerMock.createNicePartialMock; +import static org.powermock.api.easymock.PowerMock.replay; +import static org.powermock.api.easymock.PowerMock.verify; /** * This is a simple test case for the {@link NiceDemo} class that demonstrates diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/noannotation/NoAnnotationUsageTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/noannotation/NoAnnotationUsageTest.java index bae642aca..4a15ea725 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/noannotation/NoAnnotationUsageTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/noannotation/NoAnnotationUsageTest.java @@ -15,15 +15,20 @@ */ 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 junit.framework.TestCase; import samples.staticandinstance.StaticAndInstanceDemo; import static org.easymock.EasyMock.expect; -import static org.powermock.api.easymock.PowerMock.*; +import static org.powermock.api.easymock.PowerMock.createPartialMock; +import static org.powermock.api.easymock.PowerMock.expectPrivate; +import static org.powermock.api.easymock.PowerMock.mockStaticPartial; +import static org.powermock.api.easymock.PowerMock.replay; +import static org.powermock.api.easymock.PowerMock.verify; /** * Test case that demonstrates the ability to run test cases not annotated with diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/noannotation/SetUpAndTearDownWhenExtendingTestCaseTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/noannotation/SetUpAndTearDownWhenExtendingTestCaseTest.java index 61d74d3a4..b3c3e123b 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/noannotation/SetUpAndTearDownWhenExtendingTestCaseTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/noannotation/SetUpAndTearDownWhenExtendingTestCaseTest.java @@ -1,9 +1,10 @@ package samples.junit4.noannotation; -import junit.framework.TestCase; import org.junit.runner.RunWith; import org.powermock.modules.junit4.PowerMockRunner; +import junit.framework.TestCase; + @RunWith(PowerMockRunner.class) public class SetUpAndTearDownWhenExtendingTestCaseTest extends TestCase { private static final String INITIAL_MESSAGE = ""; diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/noannotation/SetUpIsOnlyCalledOnceWhenExtendingTestCaseTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/noannotation/SetUpIsOnlyCalledOnceWhenExtendingTestCaseTest.java index b5d21a683..a0d009453 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/noannotation/SetUpIsOnlyCalledOnceWhenExtendingTestCaseTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/noannotation/SetUpIsOnlyCalledOnceWhenExtendingTestCaseTest.java @@ -1,8 +1,9 @@ package samples.junit4.noannotation; -import junit.framework.TestCase; import org.junit.Before; +import junit.framework.TestCase; + public class SetUpIsOnlyCalledOnceWhenExtendingTestCaseTest extends TestCase { private int state = 0; diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/noannotation/StringConstructorWorksWhenExtendingTestCase.java b/tests/easymock/junit4/src/test/java/samples/junit4/noannotation/StringConstructorWorksWhenExtendingTestCase.java index ea00e0c44..eb1cc9791 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/noannotation/StringConstructorWorksWhenExtendingTestCase.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/noannotation/StringConstructorWorksWhenExtendingTestCase.java @@ -15,15 +15,18 @@ */ 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 junit.framework.TestCase; import samples.singleton.StaticHelper; import samples.singleton.StaticService; import static org.easymock.EasyMock.expect; -import static org.powermock.api.easymock.PowerMock.*; +import static org.powermock.api.easymock.PowerMock.mockStatic; +import static org.powermock.api.easymock.PowerMock.replay; +import static org.powermock.api.easymock.PowerMock.verify; /** * Demonstrates that the PowerMock JUnit runner works with single-arg string diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/overloading/MethodWithSameNameButDifferentDefinitionTypeTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/overloading/MethodWithSameNameButDifferentDefinitionTypeTest.java index 544ca82f0..529e280b7 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/overloading/MethodWithSameNameButDifferentDefinitionTypeTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/overloading/MethodWithSameNameButDifferentDefinitionTypeTest.java @@ -19,12 +19,18 @@ 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.*; +import static org.powermock.api.easymock.PowerMock.createMock; +import static org.powermock.api.easymock.PowerMock.expectLastCall; +import static org.powermock.api.easymock.PowerMock.expectNew; +import static org.powermock.api.easymock.PowerMock.mockStatic; +import static org.powermock.api.easymock.PowerMock.replayAll; +import static org.powermock.api.easymock.PowerMock.verifyAll; /** * Demonstrates that PowerMock correctly methods that seam to be overloaded but diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/overloading/OverloadingDemoTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/overloading/OverloadingDemoTest.java index 2b6cb8d30..75b90fb93 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/overloading/OverloadingDemoTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/overloading/OverloadingDemoTest.java @@ -19,12 +19,18 @@ 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.*; +import static org.powermock.api.easymock.PowerMock.createMock; +import static org.powermock.api.easymock.PowerMock.expectLastCall; +import static org.powermock.api.easymock.PowerMock.expectNew; +import static org.powermock.api.easymock.PowerMock.mockStatic; +import static org.powermock.api.easymock.PowerMock.replayAll; +import static org.powermock.api.easymock.PowerMock.verifyAll; /** * Demonstrates that PowerMock correctly invoke overloaded methods from the diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/partialmocking/MockSelfDemoTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/partialmocking/MockSelfDemoTest.java index a5d058c5b..3067b2f09 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/partialmocking/MockSelfDemoTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/partialmocking/MockSelfDemoTest.java @@ -21,16 +21,22 @@ 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 samples.partialmocking.MockSelfDemo; +import samples.partialmocking.MockSelfWithNoDefaultConstructorDemo; + 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.*; +import static org.powermock.api.easymock.PowerMock.createPartialMock; +import static org.powermock.api.easymock.PowerMock.createPartialMockAndInvokeDefaultConstructor; +import static org.powermock.api.easymock.PowerMock.createPartialMockForAllMethodsExcept; +import static org.powermock.api.easymock.PowerMock.expectPrivate; +import static org.powermock.api.easymock.PowerMock.replay; +import static org.powermock.api.easymock.PowerMock.verify; @RunWith(PowerMockRunner.class) @PrepareForTest(MockSelfDemo.class) diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/partialmocking/MockSelfDemoWithSubClassTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/partialmocking/MockSelfDemoWithSubClassTest.java index 95ec67a67..ceb6cd981 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/partialmocking/MockSelfDemoWithSubClassTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/partialmocking/MockSelfDemoWithSubClassTest.java @@ -19,11 +19,15 @@ 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.*; +import static org.powermock.api.easymock.PowerMock.createPartialMock; +import static org.powermock.api.easymock.PowerMock.expectPrivate; +import static org.powermock.api.easymock.PowerMock.replay; +import static org.powermock.api.easymock.PowerMock.verify; @RunWith(PowerMockRunner.class) @PrepareForTest(MockSelfDemoWithSubClass.class) diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/partialmocking/PartialMockingWithConstructorTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/partialmocking/PartialMockingWithConstructorTest.java index 2a05399a9..cf01a1e53 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/partialmocking/PartialMockingWithConstructorTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/partialmocking/PartialMockingWithConstructorTest.java @@ -17,9 +17,12 @@ import org.junit.Ignore; import org.junit.Test; + import samples.partialmocking.PartialMockingWithConstructor; -import static org.powermock.api.easymock.PowerMock.*; +import static org.powermock.api.easymock.PowerMock.createPartialMockAndInvokeDefaultConstructor; +import static org.powermock.api.easymock.PowerMock.replay; +import static org.powermock.api.easymock.PowerMock.verify; public class PartialMockingWithConstructorTest { diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/partialmocking/PartialMockingWithConstructorUsingEasyMockTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/partialmocking/PartialMockingWithConstructorUsingEasyMockTest.java index a3c807d24..61d9503da 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/partialmocking/PartialMockingWithConstructorUsingEasyMockTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/partialmocking/PartialMockingWithConstructorUsingEasyMockTest.java @@ -18,43 +18,44 @@ import org.easymock.ConstructorArgs; import org.junit.Ignore; import org.junit.Test; -import samples.partialmocking.PartialMockingWithConstructor; import java.lang.reflect.Method; +import samples.partialmocking.PartialMockingWithConstructor; + 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") + @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 { + @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"); + /* + * 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); + PartialMockingWithConstructor nationPartialMock = createMock(PartialMockingWithConstructor.class, args, touchMethod); - /* - * The following method also causes the same problem. - */ + /* + * The following method also causes the same problem. + */ - // Nation nationPartialMock = - // createPartialMockAndInvokeDefaultConstructor(Nation.class,"touch"); - replay(nationPartialMock); + // Nation nationPartialMock = + // createPartialMockAndInvokeDefaultConstructor(Nation.class,"touch"); + replay(nationPartialMock); - // Uncommenting the following line has no effect on the test result. - // nationPartialMock.initialize(); + // Uncommenting the following line has no effect on the test result. + // nationPartialMock.initialize(); - verify(nationPartialMock); - } + verify(nationPartialMock); + } } diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/powermockignore/PowerMockIgnoreAndPrepareForTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/powermockignore/PowerMockIgnoreAndPrepareForTest.java index db6f5f625..c160e8e50 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/powermockignore/PowerMockIgnoreAndPrepareForTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/powermockignore/PowerMockIgnoreAndPrepareForTest.java @@ -1,16 +1,18 @@ 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 net.bytebuddy.utility.RandomString; import samples.singleton.StaticService; -import static org.assertj.core.api.Java6Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.easymock.EasyMock.expect; -import static org.powermock.api.easymock.PowerMock.*; +import static org.powermock.api.easymock.PowerMock.mockStatic; +import static org.powermock.api.easymock.PowerMock.replay; @RunWith(PowerMockRunner.class) @PowerMockIgnore("samples.*") diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/prepareeverything/ExpectNewDemoUsingThePrepareEverythingAnnotationTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/prepareeverything/ExpectNewDemoUsingThePrepareEverythingAnnotationTest.java index 52b18571d..297cc7981 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/prepareeverything/ExpectNewDemoUsingThePrepareEverythingAnnotationTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/prepareeverything/ExpectNewDemoUsingThePrepareEverythingAnnotationTest.java @@ -21,22 +21,30 @@ 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 samples.Service; +import samples.expectnew.ExpectNewDemo; +import samples.expectnew.ExpectNewServiceUser; +import samples.expectnew.VarArgsConstructorDemo; +import samples.newmocking.MyClass; + +import static org.easymock.EasyMock.aryEq; +import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.expectLastCall; -import static org.junit.Assert.*; +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.*; +import static org.powermock.api.easymock.PowerMock.expectNew; +import static org.powermock.api.easymock.PowerMock.replayAll; +import static org.powermock.api.easymock.PowerMock.verifyAll; /** * Test class to demonstrate new instance mocking using expectNew(..) with the @@ -476,13 +484,7 @@ public void testNewWithVarArgsConstructorWhenOneArgumentIsOfASubType() throws Ex Service serviceMock = createMock(Service.class); VarArgsConstructorDemo varArgsConstructorDemoMock = createMock(VarArgsConstructorDemo.class); - final Service serviceSubTypeInstance = new Service() { - - @Override - public String getServiceMessage() { - return "message"; - } - }; + final Service serviceSubTypeInstance = () -> "message"; expectNew(VarArgsConstructorDemo.class, serviceSubTypeInstance, serviceMock).andReturn(varArgsConstructorDemoMock); expect(varArgsConstructorDemoMock.getAllServices()).andReturn(new Service[] { serviceMock }); diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/privateandfinal/PrivateFinalTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/privateandfinal/PrivateFinalTest.java index 8f395deec..943271b77 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/privateandfinal/PrivateFinalTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/privateandfinal/PrivateFinalTest.java @@ -19,6 +19,7 @@ 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; diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/privatefield/MockSelfPrivateFieldServiceClassTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/privatefield/MockSelfPrivateFieldServiceClassTest.java index 60b69fdb7..724a132d3 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/privatefield/MockSelfPrivateFieldServiceClassTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/privatefield/MockSelfPrivateFieldServiceClassTest.java @@ -19,13 +19,17 @@ 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.api.easymock.PowerMock.createPartialMock; +import static org.powermock.api.easymock.PowerMock.expectPrivate; +import static org.powermock.api.easymock.PowerMock.replay; +import static org.powermock.api.easymock.PowerMock.verify; import static org.powermock.reflect.Whitebox.setInternalState; /** diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/privatefield/SimplePrivateFieldServiceClassTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/privatefield/SimplePrivateFieldServiceClassTest.java index f65d2110c..73f556009 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/privatefield/SimplePrivateFieldServiceClassTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/privatefield/SimplePrivateFieldServiceClassTest.java @@ -16,6 +16,7 @@ package samples.junit4.privatefield; import org.junit.Test; + import samples.Service; import samples.privatefield.SimplePrivateFieldServiceClass; diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/privatemocking/PrivateMethodDemoTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/privatemocking/PrivateMethodDemoTest.java index 14566645e..a7d83202a 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/privatemocking/PrivateMethodDemoTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/privatemocking/PrivateMethodDemoTest.java @@ -21,12 +21,16 @@ 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 samples.privatemocking.PrivateMethodDemo; + import static org.junit.Assert.assertEquals; -import static org.powermock.api.easymock.PowerMock.*; +import static org.powermock.api.easymock.PowerMock.createPartialMock; +import static org.powermock.api.easymock.PowerMock.expectPrivate; +import static org.powermock.api.easymock.PowerMock.replay; +import static org.powermock.api.easymock.PowerMock.verify; /** * Test class to demonstrate private method mocking. @@ -97,8 +101,7 @@ public void testMethodCallingWrappedTestMethod() throws Exception { "aTestMethod", Integer.class); final int expected = 42; - expectPrivate(tested, "aTestMethod", new Class[] { Integer.class }, - new Integer(15)).andReturn(expected); + expectPrivate(tested, "aTestMethod", new Class[] { Integer.class }, 15).andReturn(expected); replay(tested); diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/reflection/ReflectionInstantiatorTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/reflection/ReflectionInstantiatorTest.java index 1eb0d569a..ac536fe88 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/reflection/ReflectionInstantiatorTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/reflection/ReflectionInstantiatorTest.java @@ -19,6 +19,7 @@ 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; diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/replayall/ReplayAllForExpectNewTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/replayall/ReplayAllForExpectNewTest.java index 37118209c..6a2e76e6a 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/replayall/ReplayAllForExpectNewTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/replayall/ReplayAllForExpectNewTest.java @@ -20,16 +20,22 @@ import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; + +import java.io.IOException; + 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.*; +import static org.junit.Assert.assertEquals; +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.replayAll; +import static org.powermock.api.easymock.PowerMock.verifyAll; /** * The purpose of this test is to try-out the replay all functionality in diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/replayall/ReplayAllForStaticMethodsTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/replayall/ReplayAllForStaticMethodsTest.java index 9a272af06..0bcc6703d 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/replayall/ReplayAllForStaticMethodsTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/replayall/ReplayAllForStaticMethodsTest.java @@ -19,11 +19,16 @@ 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.*; +import static org.powermock.api.easymock.PowerMock.createPartialMock; +import static org.powermock.api.easymock.PowerMock.expectPrivate; +import static org.powermock.api.easymock.PowerMock.mockStaticPartial; +import static org.powermock.api.easymock.PowerMock.replayAll; +import static org.powermock.api.easymock.PowerMock.verifyAll; /** * The purpose of this test is to try-out the replay all functionality in diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/resetmock/ResetForStaticMethodsTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/resetmock/ResetForStaticMethodsTest.java index 01674bebd..265e73deb 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/resetmock/ResetForStaticMethodsTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/resetmock/ResetForStaticMethodsTest.java @@ -19,9 +19,14 @@ 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.*; +import static org.powermock.api.easymock.PowerMock.expectLastCall; +import static org.powermock.api.easymock.PowerMock.mockStatic; +import static org.powermock.api.easymock.PowerMock.replay; +import static org.powermock.api.easymock.PowerMock.reset; +import static org.powermock.api.easymock.PowerMock.verify; /** * Asserts that it works to reset mocks for static methods even after verify has diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/resetmock/ResetMockTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/resetmock/ResetMockTest.java index 055c84431..b614fc320 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/resetmock/ResetMockTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/resetmock/ResetMockTest.java @@ -20,12 +20,18 @@ 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.*; +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.reset; +import static org.powermock.api.easymock.PowerMock.resetAll; +import static org.powermock.api.easymock.PowerMock.verifyAll; /** * Tests to verify that the reset functionality works. diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/rules/AssertThatJUnitRulesWorks.java b/tests/easymock/junit4/src/test/java/samples/junit4/rules/AssertThatJUnitRulesWorks.java index 251ef2a6b..04f1fa04e 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/rules/AssertThatJUnitRulesWorks.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/rules/AssertThatJUnitRulesWorks.java @@ -37,7 +37,7 @@ public class AssertThatJUnitRulesWorks { private static Object BEFORE = new Object(); - private List objects = new LinkedList(); + private List objects = new LinkedList<>(); @Rule public MyRule rule = new MyRule(); diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/rules/ExceptionHandlingRuleTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/rules/ExceptionHandlingRuleTest.java index a76ad4619..311ba1fe3 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/rules/ExceptionHandlingRuleTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/rules/ExceptionHandlingRuleTest.java @@ -23,6 +23,7 @@ import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; + import samples.junit4.rules.impl.SimpleEasyMockJUnitRule; import samples.rule.SimpleThingCreator; import samples.rule.SimpleThingImpl; @@ -30,7 +31,9 @@ import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertEquals; -import static org.powermock.api.easymock.PowerMock.*; +import static org.powermock.api.easymock.PowerMock.mockStatic; +import static org.powermock.api.easymock.PowerMock.replay; +import static org.powermock.api.easymock.PowerMock.verify; @RunWith(PowerMockRunner.class) @PrepareForTest(SimpleThingCreator.class) diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/rules/RuleOrderTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/rules/RuleOrderTest.java index ff04b83d8..b62431b66 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/rules/RuleOrderTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/rules/RuleOrderTest.java @@ -22,7 +22,9 @@ import org.junit.runner.RunWith; import org.powermock.modules.junit4.PowerMockRunner; -import static org.hamcrest.CoreMatchers.*; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.not; +import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.assertThat; @RunWith(PowerMockRunner.class) diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/servletmocking/SampleServletTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/servletmocking/SampleServletTest.java index e3fc0ea8f..c2e60a418 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/servletmocking/SampleServletTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/servletmocking/SampleServletTest.java @@ -20,13 +20,16 @@ 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 javax.servlet.http.HttpServletResponse; + +import samples.servletmocking.SampleServlet; import static org.easymock.EasyMock.expect; -import static org.powermock.api.easymock.PowerMock.*; +import static org.powermock.api.easymock.PowerMock.createMock; +import static org.powermock.api.easymock.PowerMock.replay; +import static org.powermock.api.easymock.PowerMock.verify; @RunWith(PowerMockRunner.class) @PrepareForTest(SampleServlet.class) diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/simplereturn/SimpleReturnExampleUserTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/simplereturn/SimpleReturnExampleUserTest.java index 3a6a8b063..eda1f2bed 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/simplereturn/SimpleReturnExampleUserTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/simplereturn/SimpleReturnExampleUserTest.java @@ -4,12 +4,15 @@ 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.*; +import static org.powermock.api.easymock.PowerMock.createMock; +import static org.powermock.api.easymock.PowerMock.replay; +import static org.powermock.api.easymock.PowerMock.verify; @RunWith(PowerMockRunner.class) @PrepareForTest(SimpleReturnExample.class) diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/singleton/LogicAndTestInSameClassTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/singleton/LogicAndTestInSameClassTest.java index d68ba3101..13ff1bc4b 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/singleton/LogicAndTestInSameClassTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/singleton/LogicAndTestInSameClassTest.java @@ -20,11 +20,14 @@ 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.*; +import static org.powermock.api.easymock.PowerMock.mockStatic; +import static org.powermock.api.easymock.PowerMock.replayAll; +import static org.powermock.api.easymock.PowerMock.verifyAll; /** * A simple test that asserts that it's possible execute a test from the same @@ -44,7 +47,7 @@ public void assertThatTestAndInstanceCanBeInSameClass() throws Exception { String expected = "Hello altered World"; expect(StaticService.say("hello")).andReturn("Hello altered World"); replayAll(); - assertEquals(expected, LogicAndTestInSameClassTest.invokeMethod()); + assertEquals(expected, invokeMethod()); verifyAll(); } } diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/singleton/MockStaticTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/singleton/MockStaticTest.java index 587084731..aa98ca3fe 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/singleton/MockStaticTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/singleton/MockStaticTest.java @@ -20,6 +20,7 @@ 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; @@ -27,7 +28,11 @@ 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.*; +import static org.powermock.api.easymock.PowerMock.expectPrivate; +import static org.powermock.api.easymock.PowerMock.mockStatic; +import static org.powermock.api.easymock.PowerMock.mockStaticPartial; +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 diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/singleton/SimpleStaticServiceTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/singleton/SimpleStaticServiceTest.java index 2b7396eb3..e2acb36e7 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/singleton/SimpleStaticServiceTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/singleton/SimpleStaticServiceTest.java @@ -4,12 +4,15 @@ 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.*; +import static org.powermock.api.easymock.PowerMock.mockStatic; +import static org.powermock.api.easymock.PowerMock.replay; +import static org.powermock.api.easymock.PowerMock.verify; @RunWith(PowerMockRunner.class) @PrepareForTest(SimpleStaticService.class) diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/staticandinstance/StaticAndInstanceDemoTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/staticandinstance/StaticAndInstanceDemoTest.java index 9a680908c..532bde4c6 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/staticandinstance/StaticAndInstanceDemoTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/staticandinstance/StaticAndInstanceDemoTest.java @@ -19,11 +19,16 @@ 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.*; +import static org.powermock.api.easymock.PowerMock.createPartialMock; +import static org.powermock.api.easymock.PowerMock.expectPrivate; +import static org.powermock.api.easymock.PowerMock.mockStaticPartial; +import static org.powermock.api.easymock.PowerMock.replay; +import static org.powermock.api.easymock.PowerMock.verify; @RunWith(PowerMockRunner.class) diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/staticandinstance/StaticAndInstanceWithConstructorCodeDemoTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/staticandinstance/StaticAndInstanceWithConstructorCodeDemoTest.java index 5706e6933..601a07bf4 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/staticandinstance/StaticAndInstanceWithConstructorCodeDemoTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/staticandinstance/StaticAndInstanceWithConstructorCodeDemoTest.java @@ -19,12 +19,17 @@ 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.*; +import static org.powermock.api.easymock.PowerMock.createMock; +import static org.powermock.api.easymock.PowerMock.mockStaticPartial; +import static org.powermock.api.easymock.PowerMock.niceReplayAndVerify; +import static org.powermock.api.easymock.PowerMock.replay; +import static org.powermock.api.easymock.PowerMock.verify; /** * The purpose of this test class is to verify that the diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/staticinitializer/AbstractStaticInitializerTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/staticinitializer/AbstractStaticInitializerTest.java index 09e74d736..89d09c0f5 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/staticinitializer/AbstractStaticInitializerTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/staticinitializer/AbstractStaticInitializerTest.java @@ -19,6 +19,7 @@ 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; diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/staticinitializer/EvilStaticInitializerExampleTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/staticinitializer/EvilStaticInitializerExampleTest.java index 0650bd64c..e791f6439 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/staticinitializer/EvilStaticInitializerExampleTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/staticinitializer/EvilStaticInitializerExampleTest.java @@ -19,6 +19,7 @@ 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; diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/staticinitializer/InterfaceStaticInitializerExampleTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/staticinitializer/InterfaceStaticInitializerExampleTest.java index a167ec029..5d81933eb 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/staticinitializer/InterfaceStaticInitializerExampleTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/staticinitializer/InterfaceStaticInitializerExampleTest.java @@ -19,6 +19,7 @@ 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; diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/staticinitializer/StaticInitializerExampleTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/staticinitializer/StaticInitializerExampleTest.java index 68e89acf4..e8b814a5e 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/staticinitializer/StaticInitializerExampleTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/staticinitializer/StaticInitializerExampleTest.java @@ -20,10 +20,11 @@ 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 samples.staticinitializer.StaticInitializerExample; + import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; @@ -34,7 +35,7 @@ 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(); + final HashSet hashSet = new HashSet<>(); Whitebox.setInternalState(StaticInitializerExample.class, "mySet", hashSet); assertSame(hashSet, Whitebox.getInternalState(StaticInitializerExample.class, "mySet")); } diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/strict/StrictDemoTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/strict/StrictDemoTest.java index 090ff4a47..f245552fb 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/strict/StrictDemoTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/strict/StrictDemoTest.java @@ -4,9 +4,14 @@ 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.*; +import static org.powermock.api.easymock.PowerMock.createPartialMock; +import static org.powermock.api.easymock.PowerMock.createStrictPartialMock; +import static org.powermock.api.easymock.PowerMock.expectPrivate; +import static org.powermock.api.easymock.PowerMock.replay; +import static org.powermock.api.easymock.PowerMock.verify; /** * This is a simple test case for the {@link StrictDemo} class that demonstrates diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/stubmethod/StubMethodTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/stubmethod/StubMethodTest.java index 5f3caad58..28fa44d5b 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/stubmethod/StubMethodTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/stubmethod/StubMethodTest.java @@ -21,10 +21,11 @@ import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.reflect.exceptions.MethodNotFoundException; import org.powermock.reflect.exceptions.TooManyMethodsFoundException; + import samples.suppressmethod.SuppressMethod; -import static org.junit.Assert.fail; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; import static org.powermock.api.support.membermodification.MemberMatcher.method; import static org.powermock.api.support.membermodification.MemberModifier.stub; diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/suppressconstructor/CreateUnmockedTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/suppressconstructor/CreateUnmockedTest.java index 1ac5959be..6666f78c8 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/suppressconstructor/CreateUnmockedTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/suppressconstructor/CreateUnmockedTest.java @@ -20,6 +20,7 @@ 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; diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/suppressconstructor/SuppressConstructorDemoTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/suppressconstructor/SuppressConstructorDemoTest.java index 610fac0ce..017da4051 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/suppressconstructor/SuppressConstructorDemoTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/suppressconstructor/SuppressConstructorDemoTest.java @@ -19,17 +19,21 @@ import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; + +import java.lang.reflect.Constructor; + 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.easymock.PowerMock.createPartialMock; +import static org.powermock.api.easymock.PowerMock.expectPrivate; +import static org.powermock.api.easymock.PowerMock.replay; +import static org.powermock.api.easymock.PowerMock.verify; import static org.powermock.api.support.membermodification.MemberMatcher.constructor; import static org.powermock.api.support.membermodification.MemberModifier.suppress; -import java.lang.reflect.Constructor; - /** * This test demonstrates how to tell PowerMock to avoid executing constructor * code for a certain class. This is crucial in certain tests where the diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/suppressconstructor/SuppressConstructorHierarchyDemoTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/suppressconstructor/SuppressConstructorHierarchyDemoTest.java index d0f7615c7..9a41a10f6 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/suppressconstructor/SuppressConstructorHierarchyDemoTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/suppressconstructor/SuppressConstructorHierarchyDemoTest.java @@ -19,10 +19,13 @@ 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.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; @@ -30,45 +33,45 @@ @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 + 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 + @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()); - } - } + @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()); - } + /** + * 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()); + } } diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/suppressconstructor/SuppressNonParentConstructorDemoTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/suppressconstructor/SuppressNonParentConstructorDemoTest.java index c0b38ce15..d29795c98 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/suppressconstructor/SuppressNonParentConstructorDemoTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/suppressconstructor/SuppressNonParentConstructorDemoTest.java @@ -17,6 +17,7 @@ import org.junit.Test; import org.powermock.reflect.Whitebox; + import samples.suppressconstructor.SuppressNonParentConstructorDemo; import static org.junit.Assert.assertEquals; diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/suppressfield/ItemRepositoryTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/suppressfield/ItemRepositoryTest.java index 6f22abe4b..9b8d83923 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/suppressfield/ItemRepositoryTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/suppressfield/ItemRepositoryTest.java @@ -6,6 +6,7 @@ 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; diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/suppressfield/SuppressFieldTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/suppressfield/SuppressFieldTest.java index 3c86c02d1..39a835e9e 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/suppressfield/SuppressFieldTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/suppressfield/SuppressFieldTest.java @@ -5,6 +5,7 @@ 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; diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/suppressmethod/SuppressMethodTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/suppressmethod/SuppressMethodTest.java index 6c5729a20..a4da06e11 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/suppressmethod/SuppressMethodTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/suppressmethod/SuppressMethodTest.java @@ -19,6 +19,7 @@ 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; diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/swing/ReallySimpleSwingDemoTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/swing/ReallySimpleSwingDemoTest.java index 1689843dd..4b3513a74 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/swing/ReallySimpleSwingDemoTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/swing/ReallySimpleSwingDemoTest.java @@ -4,12 +4,16 @@ 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 samples.swing.ReallySimpleSwingDemo; + import static org.junit.Assume.assumeTrue; -import static org.powermock.api.easymock.PowerMock.*; +import static org.powermock.api.easymock.PowerMock.expectLastCall; +import static org.powermock.api.easymock.PowerMock.mockStatic; +import static org.powermock.api.easymock.PowerMock.replayAll; +import static org.powermock.api.easymock.PowerMock.verifyAll; /** * Unit test that makes sure that PowerMock works with Swing components. @@ -21,7 +25,7 @@ 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); + assumeTrue(Float.parseFloat(System.getProperty("java.specification.version")) < 1.8f); final String message = "powermock"; diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/system/FieldMockDefect.java b/tests/easymock/junit4/src/test/java/samples/junit4/system/FieldMockDefect.java index 5d3322029..97b12b298 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/system/FieldMockDefect.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/system/FieldMockDefect.java @@ -9,7 +9,9 @@ import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertEquals; -import static org.powermock.api.easymock.PowerMock.*; +import static org.powermock.api.easymock.PowerMock.createMock; +import static org.powermock.api.easymock.PowerMock.replayAll; +import static org.powermock.api.easymock.PowerMock.verifyAll; /** * diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/system/SystemClassUserTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/system/SystemClassUserTest.java index e4ebd4cc2..8190f8199 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/system/SystemClassUserTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/system/SystemClassUserTest.java @@ -19,7 +19,6 @@ 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; @@ -29,10 +28,19 @@ import java.util.LinkedList; import java.util.List; +import samples.system.SystemClassUser; + import static org.easymock.EasyMock.anyLong; import static org.easymock.EasyMock.expect; -import static org.junit.Assert.*; -import static org.powermock.api.easymock.PowerMock.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.powermock.api.easymock.PowerMock.createMock; +import static org.powermock.api.easymock.PowerMock.expectLastCall; +import static org.powermock.api.easymock.PowerMock.mockStatic; +import static org.powermock.api.easymock.PowerMock.mockStaticPartial; +import static org.powermock.api.easymock.PowerMock.replayAll; +import static org.powermock.api.easymock.PowerMock.verifyAll; /** * Demonstrates PowerMock's ability to mock non-final and final system classes. @@ -109,7 +117,7 @@ public void assertThatPartialMockingOfFinalSystemClassesWorks() throws Exception @Test public void assertThatMockingOfCollectionsWork() throws Exception { - List list = new LinkedList(); + List list = new LinkedList<>(); mockStatic(Collections.class); Collections.shuffle(list); diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/testhierarchy/RunWithHierarchyTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/testhierarchy/RunWithHierarchyTest.java index 5bed3d349..f5148e283 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/testhierarchy/RunWithHierarchyTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/testhierarchy/RunWithHierarchyTest.java @@ -17,6 +17,7 @@ import org.junit.Test; import org.powermock.core.classloader.annotations.PrepareForTest; + import samples.finalmocking.FinalDemo; //@RunWith(PowerMockRunner.class) diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/verify/AssertVerifyWorksTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/verify/AssertVerifyWorksTest.java index 3883da0ed..17ec5f78e 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/verify/AssertVerifyWorksTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/verify/AssertVerifyWorksTest.java @@ -4,11 +4,15 @@ 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.*; +import static org.powermock.api.easymock.PowerMock.mockStatic; +import static org.powermock.api.easymock.PowerMock.mockStaticPartial; +import static org.powermock.api.easymock.PowerMock.replay; +import static org.powermock.api.easymock.PowerMock.verify; /** * This test asserts that the diff --git a/tests/easymock/junit4/src/test/java/samples/junit4/whitebox/PowerMockConstructorFiltrationTest.java b/tests/easymock/junit4/src/test/java/samples/junit4/whitebox/PowerMockConstructorFiltrationTest.java index 1b902eaa4..c7b5c4a20 100644 --- a/tests/easymock/junit4/src/test/java/samples/junit4/whitebox/PowerMockConstructorFiltrationTest.java +++ b/tests/easymock/junit4/src/test/java/samples/junit4/whitebox/PowerMockConstructorFiltrationTest.java @@ -17,10 +17,11 @@ import org.junit.Test; import org.powermock.reflect.internal.WhiteboxImpl; -import samples.whitebox.ClassWithPowerMockGeneratedConstructor; import java.lang.reflect.Constructor; +import samples.whitebox.ClassWithPowerMockGeneratedConstructor; + import static org.junit.Assert.assertEquals; public class PowerMockConstructorFiltrationTest { diff --git a/tests/easymock/junit4/src/test/java/samples/methodhierarchy/MethodInvocationDemoTest.java b/tests/easymock/junit4/src/test/java/samples/methodhierarchy/MethodInvocationDemoTest.java index 4650e9a49..391279058 100644 --- a/tests/easymock/junit4/src/test/java/samples/methodhierarchy/MethodInvocationDemoTest.java +++ b/tests/easymock/junit4/src/test/java/samples/methodhierarchy/MethodInvocationDemoTest.java @@ -24,7 +24,10 @@ import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertEquals; -import static org.powermock.api.easymock.PowerMock.*; +import static org.powermock.api.easymock.PowerMock.createPartialMock; +import static org.powermock.api.easymock.PowerMock.expectPrivate; +import static org.powermock.api.easymock.PowerMock.replay; +import static org.powermock.api.easymock.PowerMock.verify; /** * Test that verifies that it's possible to invoke and create partial mocks of diff --git a/tests/easymock/junit4/src/test/java/samples/packageprivate/PackagePrivateClassTest.java b/tests/easymock/junit4/src/test/java/samples/packageprivate/PackagePrivateClassTest.java index 82626ffde..6239a2b43 100644 --- a/tests/easymock/junit4/src/test/java/samples/packageprivate/PackagePrivateClassTest.java +++ b/tests/easymock/junit4/src/test/java/samples/packageprivate/PackagePrivateClassTest.java @@ -21,7 +21,10 @@ import org.powermock.modules.junit4.PowerMockRunner; import static org.junit.Assert.assertEquals; -import static org.powermock.api.easymock.PowerMock.*; +import static org.powermock.api.easymock.PowerMock.createPartialMock; +import static org.powermock.api.easymock.PowerMock.expectPrivate; +import static org.powermock.api.easymock.PowerMock.replay; +import static org.powermock.api.easymock.PowerMock.verify; /** * Verifies that the issue at diff --git a/tests/easymock/junit4/src/test/java/samples/suppressconstructor/SuppressDefaultConstructorTest.java b/tests/easymock/junit4/src/test/java/samples/suppressconstructor/SuppressDefaultConstructorTest.java index d79f344e4..d914e96b4 100644 --- a/tests/easymock/junit4/src/test/java/samples/suppressconstructor/SuppressDefaultConstructorTest.java +++ b/tests/easymock/junit4/src/test/java/samples/suppressconstructor/SuppressDefaultConstructorTest.java @@ -16,7 +16,6 @@ package samples.suppressconstructor; - import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; diff --git a/tests/easymock/junit410/src/test/java/samples/junit410/expectnew/ExpectNewDemoTest.java b/tests/easymock/junit410/src/test/java/samples/junit410/expectnew/ExpectNewDemoTest.java index 9d6f97618..1751e4e69 100644 --- a/tests/easymock/junit410/src/test/java/samples/junit410/expectnew/ExpectNewDemoTest.java +++ b/tests/easymock/junit410/src/test/java/samples/junit410/expectnew/ExpectNewDemoTest.java @@ -18,12 +18,13 @@ import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; + +import java.io.DataInputStream; + 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(..). * diff --git a/tests/easymock/junit410/src/test/java/samples/junit410/expectnew/ExpectNewOfFinalSystemClassTest.java b/tests/easymock/junit410/src/test/java/samples/junit410/expectnew/ExpectNewOfFinalSystemClassTest.java index 916785bff..76b1de82d 100644 --- a/tests/easymock/junit410/src/test/java/samples/junit410/expectnew/ExpectNewOfFinalSystemClassTest.java +++ b/tests/easymock/junit410/src/test/java/samples/junit410/expectnew/ExpectNewOfFinalSystemClassTest.java @@ -19,11 +19,15 @@ 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.*; +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 }) diff --git a/tests/easymock/junit410/src/test/java/samples/junit410/rules/AssertThatJUnit410RulesWorks.java b/tests/easymock/junit410/src/test/java/samples/junit410/rules/AssertThatJUnit410RulesWorks.java index 8666fa8cb..9bf077b2f 100644 --- a/tests/easymock/junit410/src/test/java/samples/junit410/rules/AssertThatJUnit410RulesWorks.java +++ b/tests/easymock/junit410/src/test/java/samples/junit410/rules/AssertThatJUnit410RulesWorks.java @@ -37,7 +37,7 @@ public class AssertThatJUnit410RulesWorks { private static Object BEFORE = new Object(); - private List objects = new LinkedList(); + private List objects = new LinkedList<>(); @Rule public MyRule rule = new MyRule(); @@ -54,7 +54,8 @@ public void assertThatJUnit410RulesWorks() throws Exception { private class MyRule implements TestRule { - public Statement apply(final Statement base, Description description) { + @Override + public Statement apply(final Statement base, Description description) { return new Statement() { @Override public void evaluate() throws Throwable { diff --git a/tests/easymock/junit410/src/test/java/samples/junit410/rules/ExceptionHandlingRuleTest.java b/tests/easymock/junit410/src/test/java/samples/junit410/rules/ExceptionHandlingRuleTest.java index 31912967a..1e4fae9a2 100644 --- a/tests/easymock/junit410/src/test/java/samples/junit410/rules/ExceptionHandlingRuleTest.java +++ b/tests/easymock/junit410/src/test/java/samples/junit410/rules/ExceptionHandlingRuleTest.java @@ -23,6 +23,7 @@ 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; @@ -30,7 +31,9 @@ import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertEquals; -import static org.powermock.api.easymock.PowerMock.*; +import static org.powermock.api.easymock.PowerMock.mockStatic; +import static org.powermock.api.easymock.PowerMock.replay; +import static org.powermock.api.easymock.PowerMock.verify; @RunWith(PowerMockRunner.class) @PrepareForTest(SimpleThingCreator.class) diff --git a/tests/easymock/junit412/src/test/java/samples/junit412/bug/github755/TwoObjectsAnnotatedTest.java b/tests/easymock/junit412/src/test/java/samples/junit412/bug/github755/TwoObjectsAnnotatedTest.java index 22627d904..4e238a3e3 100644 --- a/tests/easymock/junit412/src/test/java/samples/junit412/bug/github755/TwoObjectsAnnotatedTest.java +++ b/tests/easymock/junit412/src/test/java/samples/junit412/bug/github755/TwoObjectsAnnotatedTest.java @@ -1,14 +1,14 @@ 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; +import static org.assertj.core.api.Assertions.assertThat; @RunWith(PowerMockRunner.class) public class TwoObjectsAnnotatedTest { diff --git a/tests/easymock/junit412/src/test/java/samples/junit412/expectnew/ExpectNewDemoTest.java b/tests/easymock/junit412/src/test/java/samples/junit412/expectnew/ExpectNewDemoTest.java index 2d64cec82..e7f31d5a3 100644 --- a/tests/easymock/junit412/src/test/java/samples/junit412/expectnew/ExpectNewDemoTest.java +++ b/tests/easymock/junit412/src/test/java/samples/junit412/expectnew/ExpectNewDemoTest.java @@ -18,12 +18,13 @@ import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; + +import java.io.DataInputStream; + 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(..). * diff --git a/tests/easymock/junit412/src/test/java/samples/junit412/expectnew/ExpectNewOfFinalSystemClassTest.java b/tests/easymock/junit412/src/test/java/samples/junit412/expectnew/ExpectNewOfFinalSystemClassTest.java index 10d8fcfcc..5df38c2c8 100644 --- a/tests/easymock/junit412/src/test/java/samples/junit412/expectnew/ExpectNewOfFinalSystemClassTest.java +++ b/tests/easymock/junit412/src/test/java/samples/junit412/expectnew/ExpectNewOfFinalSystemClassTest.java @@ -19,6 +19,7 @@ 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; diff --git a/tests/easymock/junit412/src/test/java/samples/junit412/github668/TwoMockFieldsWithDifferentTypesClass.java b/tests/easymock/junit412/src/test/java/samples/junit412/github668/TwoMockFieldsWithDifferentTypesClass.java index dd332b437..30dde3f07 100644 --- a/tests/easymock/junit412/src/test/java/samples/junit412/github668/TwoMockFieldsWithDifferentTypesClass.java +++ b/tests/easymock/junit412/src/test/java/samples/junit412/github668/TwoMockFieldsWithDifferentTypesClass.java @@ -6,6 +6,7 @@ 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; diff --git a/tests/easymock/testng-agent/src/test/java/samples/testng/agent/AnnotationDemoTest.java b/tests/easymock/testng-agent/src/test/java/samples/testng/agent/AnnotationDemoTest.java index 17e8fc020..ac10d1216 100644 --- a/tests/easymock/testng-agent/src/test/java/samples/testng/agent/AnnotationDemoTest.java +++ b/tests/easymock/testng-agent/src/test/java/samples/testng/agent/AnnotationDemoTest.java @@ -5,6 +5,7 @@ import org.powermock.modules.testng.PowerMockTestCase; import org.testng.Assert; import org.testng.annotations.Test; + import samples.Service; import samples.annotationbased.AnnotationDemo; diff --git a/tests/easymock/testng-agent/src/test/java/samples/testng/agent/AnnotationDemoWithBeforeMethodTest.java b/tests/easymock/testng-agent/src/test/java/samples/testng/agent/AnnotationDemoWithBeforeMethodTest.java index 0ab9d9753..3e3b14d31 100644 --- a/tests/easymock/testng-agent/src/test/java/samples/testng/agent/AnnotationDemoWithBeforeMethodTest.java +++ b/tests/easymock/testng-agent/src/test/java/samples/testng/agent/AnnotationDemoWithBeforeMethodTest.java @@ -6,6 +6,7 @@ import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; + import samples.Service; import samples.annotationbased.AnnotationDemo; @@ -19,26 +20,26 @@ */ public class AnnotationDemoWithBeforeMethodTest extends PowerMockTestCase { - @Mock - private Service serviceMock; + @Mock + private Service serviceMock; - private AnnotationDemo tested; + private AnnotationDemo tested; - @BeforeMethod - public void setup() { - tested = new AnnotationDemo(serviceMock); - } + @BeforeMethod + public void setup() { + tested = new AnnotationDemo(serviceMock); + } - @Test + @Test @PrepareForTest - public void assertInjectionWorked() throws Exception { - final String expected = "mock"; - expect(serviceMock.getServiceMessage()).andReturn(expected); + public void assertInjectionWorked() throws Exception { + final String expected = "mock"; + expect(serviceMock.getServiceMessage()).andReturn(expected); - replayAll(); + replayAll(); - Assert.assertEquals(expected, tested.getServiceMessage()); + Assert.assertEquals(expected, tested.getServiceMessage()); - verifyAll(); - } + verifyAll(); + } } diff --git a/tests/easymock/testng-agent/src/test/java/samples/testng/agent/FinalDemoTest.java b/tests/easymock/testng-agent/src/test/java/samples/testng/agent/FinalDemoTest.java index 86593c581..317451aa0 100644 --- a/tests/easymock/testng-agent/src/test/java/samples/testng/agent/FinalDemoTest.java +++ b/tests/easymock/testng-agent/src/test/java/samples/testng/agent/FinalDemoTest.java @@ -17,12 +17,14 @@ 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.powermock.api.easymock.PowerMock.createMock; +import static org.powermock.api.easymock.PowerMock.replay; +import static org.powermock.api.easymock.PowerMock.verify; import static org.testng.Assert.fail; import static org.testng.AssertJUnit.assertEquals; @@ -43,7 +45,7 @@ public void testSay() throws Exception { String actual = tested.say("hello"); verify(tested); - AssertJUnit.assertEquals("Expected and actual did not match", expected, actual); + assertEquals("Expected and actual did not match", expected, actual); // Should still be mocked by now. try { diff --git a/tests/easymock/testng-agent/src/test/java/samples/testng/agent/MockStaticExtendsPowerMockTestCaseTest.java b/tests/easymock/testng-agent/src/test/java/samples/testng/agent/MockStaticExtendsPowerMockTestCaseTest.java index da36db909..63b2047e8 100644 --- a/tests/easymock/testng-agent/src/test/java/samples/testng/agent/MockStaticExtendsPowerMockTestCaseTest.java +++ b/tests/easymock/testng-agent/src/test/java/samples/testng/agent/MockStaticExtendsPowerMockTestCaseTest.java @@ -19,11 +19,14 @@ 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.*; +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 diff --git a/tests/easymock/testng-agent/src/test/java/samples/testng/agent/MockStaticTest.java b/tests/easymock/testng-agent/src/test/java/samples/testng/agent/MockStaticTest.java index 0e7735783..fa7de9ff6 100644 --- a/tests/easymock/testng-agent/src/test/java/samples/testng/agent/MockStaticTest.java +++ b/tests/easymock/testng-agent/src/test/java/samples/testng/agent/MockStaticTest.java @@ -19,6 +19,7 @@ import org.powermock.modules.testng.PowerMockTestCase; import org.testng.Assert; import org.testng.annotations.Test; + import samples.singleton.StaticHelper; import samples.singleton.StaticService; diff --git a/tests/easymock/testng-agent/src/test/java/samples/testng/agent/PartialMockingWithBeforeClassTest.java b/tests/easymock/testng-agent/src/test/java/samples/testng/agent/PartialMockingWithBeforeClassTest.java index 4b7bc5118..13b6a78af 100644 --- a/tests/easymock/testng-agent/src/test/java/samples/testng/agent/PartialMockingWithBeforeClassTest.java +++ b/tests/easymock/testng-agent/src/test/java/samples/testng/agent/PartialMockingWithBeforeClassTest.java @@ -20,6 +20,7 @@ import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; + import samples.privateandfinal.PrivateFinal; import static org.easymock.EasyMock.replay; diff --git a/tests/easymock/testng-agent/src/test/java/samples/testng/agent/PrivateFinalTest.java b/tests/easymock/testng-agent/src/test/java/samples/testng/agent/PrivateFinalTest.java index 8347e93f2..644ef0998 100644 --- a/tests/easymock/testng-agent/src/test/java/samples/testng/agent/PrivateFinalTest.java +++ b/tests/easymock/testng-agent/src/test/java/samples/testng/agent/PrivateFinalTest.java @@ -18,6 +18,7 @@ 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; diff --git a/tests/easymock/testng-agent/src/test/java/samples/testng/agent/SampleServletTest.java b/tests/easymock/testng-agent/src/test/java/samples/testng/agent/SampleServletTest.java index 9ba0a50f1..c0e3c907f 100644 --- a/tests/easymock/testng-agent/src/test/java/samples/testng/agent/SampleServletTest.java +++ b/tests/easymock/testng-agent/src/test/java/samples/testng/agent/SampleServletTest.java @@ -21,13 +21,16 @@ 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 javax.servlet.http.HttpServletResponse; + +import samples.servletmocking.SampleServlet; import static org.easymock.EasyMock.expect; -import static org.powermock.api.easymock.PowerMock.*; +import static org.powermock.api.easymock.PowerMock.createMock; +import static org.powermock.api.easymock.PowerMock.replay; +import static org.powermock.api.easymock.PowerMock.verify; @PrepareForTest(SampleServlet.class) public class SampleServletTest { diff --git a/tests/easymock/testng-agent/src/test/java/samples/testng/agent/SystemClassUserTest.java b/tests/easymock/testng-agent/src/test/java/samples/testng/agent/SystemClassUserTest.java index f4ed7578b..ca62678a5 100644 --- a/tests/easymock/testng-agent/src/test/java/samples/testng/agent/SystemClassUserTest.java +++ b/tests/easymock/testng-agent/src/test/java/samples/testng/agent/SystemClassUserTest.java @@ -18,7 +18,6 @@ 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; @@ -28,9 +27,16 @@ import java.util.LinkedList; import java.util.List; +import samples.system.SystemClassUser; + import static org.easymock.EasyMock.anyLong; import static org.easymock.EasyMock.expect; -import static org.powermock.api.easymock.PowerMock.*; +import static org.powermock.api.easymock.PowerMock.createMock; +import static org.powermock.api.easymock.PowerMock.expectLastCall; +import static org.powermock.api.easymock.PowerMock.mockStatic; +import static org.powermock.api.easymock.PowerMock.mockStaticPartial; +import static org.powermock.api.easymock.PowerMock.replayAll; +import static org.powermock.api.easymock.PowerMock.verifyAll; import static org.testng.Assert.assertSame; import static org.testng.Assert.assertTrue; import static org.testng.AssertJUnit.assertEquals; @@ -123,7 +129,7 @@ public void assertThatPartialMockingOfFinalSystemClassesWorksForNonVoidMethods() @Test public void assertThatMockingOfCollectionsWork() throws Exception { - List list = new LinkedList(); + List list = new LinkedList<>(); mockStatic(Collections.class); Collections.shuffle(list); diff --git a/tests/easymock/testng/src/test/java/samples/testng/AnnotationDemoTest.java b/tests/easymock/testng/src/test/java/samples/testng/AnnotationDemoTest.java index a7360334c..179cc67cc 100644 --- a/tests/easymock/testng/src/test/java/samples/testng/AnnotationDemoTest.java +++ b/tests/easymock/testng/src/test/java/samples/testng/AnnotationDemoTest.java @@ -4,6 +4,7 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.testng.Assert; import org.testng.annotations.Test; + import samples.Service; import samples.annotationbased.AnnotationDemo; diff --git a/tests/easymock/testng/src/test/java/samples/testng/AnnotationDemoWithBeforeMethodTest.java b/tests/easymock/testng/src/test/java/samples/testng/AnnotationDemoWithBeforeMethodTest.java index 9d87d594e..72f22387a 100644 --- a/tests/easymock/testng/src/test/java/samples/testng/AnnotationDemoWithBeforeMethodTest.java +++ b/tests/easymock/testng/src/test/java/samples/testng/AnnotationDemoWithBeforeMethodTest.java @@ -5,6 +5,7 @@ import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; + import samples.Service; import samples.annotationbased.AnnotationDemo; @@ -18,26 +19,26 @@ */ public class AnnotationDemoWithBeforeMethodTest { - @Mock - private Service serviceMock; + @Mock + private Service serviceMock; - private AnnotationDemo tested; + private AnnotationDemo tested; - @BeforeMethod - public void setup() { - tested = new AnnotationDemo(serviceMock); - } + @BeforeMethod + public void setup() { + tested = new AnnotationDemo(serviceMock); + } - @Test + @Test @PrepareForTest - public void assertInjectionWorked() throws Exception { - final String expected = "mock"; - expect(serviceMock.getServiceMessage()).andReturn(expected); + public void assertInjectionWorked() throws Exception { + final String expected = "mock"; + expect(serviceMock.getServiceMessage()).andReturn(expected); - replayAll(); + replayAll(); - Assert.assertEquals(expected, tested.getServiceMessage()); + Assert.assertEquals(expected, tested.getServiceMessage()); - verifyAll(); - } + verifyAll(); + } } diff --git a/tests/easymock/testng/src/test/java/samples/testng/FinalTest.java b/tests/easymock/testng/src/test/java/samples/testng/FinalTest.java index 220b44944..74bfbac7e 100644 --- a/tests/easymock/testng/src/test/java/samples/testng/FinalTest.java +++ b/tests/easymock/testng/src/test/java/samples/testng/FinalTest.java @@ -3,10 +3,13 @@ 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.powermock.api.easymock.PowerMock.createMock; +import static org.powermock.api.easymock.PowerMock.replayAll; +import static org.powermock.api.easymock.PowerMock.verifyAll; import static org.testng.Assert.assertEquals; @PrepareForTest(FinalDemo.class) diff --git a/tests/easymock/testng/src/test/java/samples/testng/MockStaticExtendsPowerMockTestCaseTest.java b/tests/easymock/testng/src/test/java/samples/testng/MockStaticExtendsPowerMockTestCaseTest.java index d52b309ae..f451ca2c8 100644 --- a/tests/easymock/testng/src/test/java/samples/testng/MockStaticExtendsPowerMockTestCaseTest.java +++ b/tests/easymock/testng/src/test/java/samples/testng/MockStaticExtendsPowerMockTestCaseTest.java @@ -19,11 +19,14 @@ 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.*; +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 diff --git a/tests/easymock/testng/src/test/java/samples/testng/MockStaticTest.java b/tests/easymock/testng/src/test/java/samples/testng/MockStaticTest.java index 6fbc22edf..c79e807bf 100644 --- a/tests/easymock/testng/src/test/java/samples/testng/MockStaticTest.java +++ b/tests/easymock/testng/src/test/java/samples/testng/MockStaticTest.java @@ -18,6 +18,7 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.testng.Assert; import org.testng.annotations.Test; + import samples.singleton.StaticHelper; import samples.singleton.StaticService; diff --git a/tests/easymock/testng/src/test/java/samples/testng/PartialMockingWithBeforeClassTest.java b/tests/easymock/testng/src/test/java/samples/testng/PartialMockingWithBeforeClassTest.java index 0bfbe4a94..8e7507d56 100644 --- a/tests/easymock/testng/src/test/java/samples/testng/PartialMockingWithBeforeClassTest.java +++ b/tests/easymock/testng/src/test/java/samples/testng/PartialMockingWithBeforeClassTest.java @@ -20,6 +20,7 @@ import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; + import samples.privateandfinal.PrivateFinal; import static org.easymock.EasyMock.replay; diff --git a/tests/easymock/testng/src/test/java/samples/testng/PrivateFinalTest.java b/tests/easymock/testng/src/test/java/samples/testng/PrivateFinalTest.java index 849963a23..c3ceb102e 100644 --- a/tests/easymock/testng/src/test/java/samples/testng/PrivateFinalTest.java +++ b/tests/easymock/testng/src/test/java/samples/testng/PrivateFinalTest.java @@ -18,6 +18,7 @@ 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; diff --git a/tests/easymock/testng/src/test/java/samples/testng/SampleServletTest.java b/tests/easymock/testng/src/test/java/samples/testng/SampleServletTest.java index e28bd3db9..5cf1626ab 100644 --- a/tests/easymock/testng/src/test/java/samples/testng/SampleServletTest.java +++ b/tests/easymock/testng/src/test/java/samples/testng/SampleServletTest.java @@ -21,13 +21,16 @@ 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 javax.servlet.http.HttpServletResponse; + +import samples.servletmocking.SampleServlet; import static org.easymock.EasyMock.expect; -import static org.powermock.api.easymock.PowerMock.*; +import static org.powermock.api.easymock.PowerMock.createMock; +import static org.powermock.api.easymock.PowerMock.replay; +import static org.powermock.api.easymock.PowerMock.verify; @PrepareForTest(SampleServlet.class) public class SampleServletTest { diff --git a/tests/easymock/testng/src/test/java/samples/testng/StaticInitializerExampleTest.java b/tests/easymock/testng/src/test/java/samples/testng/StaticInitializerExampleTest.java index f75d8be4f..713e23adf 100644 --- a/tests/easymock/testng/src/test/java/samples/testng/StaticInitializerExampleTest.java +++ b/tests/easymock/testng/src/test/java/samples/testng/StaticInitializerExampleTest.java @@ -15,15 +15,17 @@ */ package samples.testng; -import org.testng.annotations.Test; import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor; +import org.powermock.modules.testng.PowerMockTestCase; import org.powermock.reflect.Whitebox; -import samples.staticinitializer.StaticInitializerExample; +import org.testng.annotations.Test; import java.util.HashSet; -import static org.testng.Assert.*; -import org.powermock.modules.testng.PowerMockTestCase; +import samples.staticinitializer.StaticInitializerExample; + +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertSame; @SuppressStaticInitializationFor("samples.staticinitializer.StaticInitializerExample") public class StaticInitializerExampleTest extends PowerMockTestCase { @@ -36,7 +38,7 @@ public void testSupressStaticInitializer() throws Exception { @Test public void testSupressStaticInitializerAndSetFinalField() throws Exception { assertNull(StaticInitializerExample.getMySet(), "Should be null because the static initializer should be suppressed"); - final HashSet hashSet = new HashSet(); + final HashSet hashSet = new HashSet<>(); Whitebox.setInternalState(StaticInitializerExample.class, "mySet", hashSet); assertSame(hashSet, Whitebox.getInternalState(StaticInitializerExample.class, "mySet")); } diff --git a/tests/easymock/testng/src/test/java/samples/testng/SystemClassUserTest.java b/tests/easymock/testng/src/test/java/samples/testng/SystemClassUserTest.java index 7f5624168..a842cb015 100644 --- a/tests/easymock/testng/src/test/java/samples/testng/SystemClassUserTest.java +++ b/tests/easymock/testng/src/test/java/samples/testng/SystemClassUserTest.java @@ -17,7 +17,6 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.testng.annotations.Test; -import samples.system.SystemClassUser; import java.net.InetAddress; import java.net.URL; @@ -27,9 +26,16 @@ import java.util.LinkedList; import java.util.List; +import samples.system.SystemClassUser; + import static org.easymock.EasyMock.anyLong; import static org.easymock.EasyMock.expect; -import static org.powermock.api.easymock.PowerMock.*; +import static org.powermock.api.easymock.PowerMock.createMock; +import static org.powermock.api.easymock.PowerMock.expectLastCall; +import static org.powermock.api.easymock.PowerMock.mockStatic; +import static org.powermock.api.easymock.PowerMock.mockStaticPartial; +import static org.powermock.api.easymock.PowerMock.replayAll; +import static org.powermock.api.easymock.PowerMock.verifyAll; import static org.testng.Assert.assertSame; import static org.testng.Assert.assertTrue; import static org.testng.AssertJUnit.assertEquals; @@ -108,7 +114,7 @@ public void assertThatPartialMockingOfFinalSystemClassesWorks() throws Exception @Test public void assertThatMockingOfCollectionsWork() throws Exception { - List list = new LinkedList(); + List list = new LinkedList<>(); mockStatic(Collections.class); Collections.shuffle(list); diff --git a/tests/java11/build.gradle b/tests/java11/build.gradle index d20b040ca..aa7682953 100644 --- a/tests/java11/build.gradle +++ b/tests/java11/build.gradle @@ -1,9 +1,9 @@ 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 } -// } + +if (JavaVersion.current() != JavaVersion.VERSION_11) { + project.tasks.all { task -> task.enabled = false } +} dependencies { testCompile("junit:junit:${junitVersion}") { @@ -15,16 +15,15 @@ configure(project.subprojects) { subproject -> 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 -// } + compileJava { + sourceCompatibility = 11 + targetCompatibility = 11 + } + + compileTestJava { + sourceCompatibility = 11 + targetCompatibility = 11 + } } project(":tests:java11:mockito-junit4") { diff --git a/tests/java11/mockito-junit4/src/test/java/samples/powermockito/junit4/bugs/github958/Github958Test.java b/tests/java11/mockito-junit4/src/test/java/samples/powermockito/junit4/bugs/github958/Github958Test.java index d8a64dad7..145946432 100644 --- a/tests/java11/mockito-junit4/src/test/java/samples/powermockito/junit4/bugs/github958/Github958Test.java +++ b/tests/java11/mockito-junit4/src/test/java/samples/powermockito/junit4/bugs/github958/Github958Test.java @@ -5,7 +5,7 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; @RunWith(PowerMockRunner.class) @PrepareForTest(OuterClass.class) diff --git a/tests/java8/mockito-junit4-agent/src/test/java/samples/powermockito/junit4/bugs/github510/ClassUsesInterfaceTest.java b/tests/java8/mockito-junit4-agent/src/test/java/samples/powermockito/junit4/bugs/github510/ClassUsesInterfaceTest.java index 1bccbc376..04b15f2a3 100644 --- a/tests/java8/mockito-junit4-agent/src/test/java/samples/powermockito/junit4/bugs/github510/ClassUsesInterfaceTest.java +++ b/tests/java8/mockito-junit4-agent/src/test/java/samples/powermockito/junit4/bugs/github510/ClassUsesInterfaceTest.java @@ -6,7 +6,7 @@ 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.assertj.core.api.Assertions.assertThat; import static org.powermock.api.mockito.PowerMockito.mockStatic; import static org.powermock.api.mockito.PowerMockito.when; diff --git a/tests/java8/mockito-junit4-rule-xstream/src/test/java/samples/powermockito/junit4/bugs/github510/ClassUsesInterfaceTest.java b/tests/java8/mockito-junit4-rule-xstream/src/test/java/samples/powermockito/junit4/bugs/github510/ClassUsesInterfaceTest.java index d46c39841..1e79e5f7c 100644 --- a/tests/java8/mockito-junit4-rule-xstream/src/test/java/samples/powermockito/junit4/bugs/github510/ClassUsesInterfaceTest.java +++ b/tests/java8/mockito-junit4-rule-xstream/src/test/java/samples/powermockito/junit4/bugs/github510/ClassUsesInterfaceTest.java @@ -6,7 +6,7 @@ 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.assertj.core.api.Assertions.assertThat; import static org.powermock.api.mockito.PowerMockito.mockStatic; import static org.powermock.api.mockito.PowerMockito.when; diff --git a/tests/java8/mockito-junit4/src/test/java/org/powermock/modules/junit4/largemethod/LargeMethodInInterfaceTest.java b/tests/java8/mockito-junit4/src/test/java/org/powermock/modules/junit4/largemethod/LargeMethodInInterfaceTest.java index 64ec7572a..0b40874f7 100644 --- a/tests/java8/mockito-junit4/src/test/java/org/powermock/modules/junit4/largemethod/LargeMethodInInterfaceTest.java +++ b/tests/java8/mockito-junit4/src/test/java/org/powermock/modules/junit4/largemethod/LargeMethodInInterfaceTest.java @@ -5,6 +5,7 @@ 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 org.junit.Assert.assertEquals; diff --git a/tests/java8/mockito-junit4/src/test/java/samples/powermockito/junit4/bugs/github510/Github510Test.java b/tests/java8/mockito-junit4/src/test/java/samples/powermockito/junit4/bugs/github510/Github510Test.java index f4e8eb2aa..26239ea56 100644 --- a/tests/java8/mockito-junit4/src/test/java/samples/powermockito/junit4/bugs/github510/Github510Test.java +++ b/tests/java8/mockito-junit4/src/test/java/samples/powermockito/junit4/bugs/github510/Github510Test.java @@ -6,7 +6,7 @@ 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.Assertions.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; diff --git a/tests/junit4/src/test/java/samples/powermockito/junit4/bugs/github352/GitHub352Test.java b/tests/junit4/src/test/java/samples/powermockito/junit4/bugs/github352/GitHub352Test.java index ac3523d3e..c571ee3d8 100644 --- a/tests/junit4/src/test/java/samples/powermockito/junit4/bugs/github352/GitHub352Test.java +++ b/tests/junit4/src/test/java/samples/powermockito/junit4/bugs/github352/GitHub352Test.java @@ -7,7 +7,7 @@ import org.junit.runner.Runner; import org.powermock.modules.junit4.PowerMockRunner; -import static org.assertj.core.api.Java6Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; public class GitHub352Test { diff --git a/tests/junit4/src/test/java/samples/powermockito/junit4/bugs/github722/GitHub722Test.java b/tests/junit4/src/test/java/samples/powermockito/junit4/bugs/github722/GitHub722Test.java index d674cef22..49dc81de2 100644 --- a/tests/junit4/src/test/java/samples/powermockito/junit4/bugs/github722/GitHub722Test.java +++ b/tests/junit4/src/test/java/samples/powermockito/junit4/bugs/github722/GitHub722Test.java @@ -8,7 +8,7 @@ import java.lang.reflect.Method; -import static org.assertj.core.api.Java6Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; public class GitHub722Test { diff --git a/tests/junit4/src/test/java/samples/powermockito/junit4/bugs/github722/UseTheoriesTest.java b/tests/junit4/src/test/java/samples/powermockito/junit4/bugs/github722/UseTheoriesTest.java index fb76f8c96..9946d7e8d 100644 --- a/tests/junit4/src/test/java/samples/powermockito/junit4/bugs/github722/UseTheoriesTest.java +++ b/tests/junit4/src/test/java/samples/powermockito/junit4/bugs/github722/UseTheoriesTest.java @@ -1,8 +1,8 @@ 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.junit.runner.RunWith; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunnerDelegate; diff --git a/tests/mockito/inline/src/test/java/samples/powermockito/inline/bugs/github793/MockitoFinalClassMockingTest.java b/tests/mockito/inline/src/test/java/samples/powermockito/inline/bugs/github793/MockitoFinalClassMockingTest.java index 19668abf2..0118ad8e0 100644 --- a/tests/mockito/inline/src/test/java/samples/powermockito/inline/bugs/github793/MockitoFinalClassMockingTest.java +++ b/tests/mockito/inline/src/test/java/samples/powermockito/inline/bugs/github793/MockitoFinalClassMockingTest.java @@ -18,13 +18,11 @@ 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.assertThat; import static org.assertj.core.api.Assertions.catchThrowable; import static org.junit.Assume.assumeTrue; import static org.mockito.Mockito.doNothing; @@ -59,12 +57,7 @@ public void should_mock_final_method_with_using_mockito_inline_mock_creator() { doNothing().when(mock).say(value); - Throwable throwable = catchThrowable(new ThrowingCallable() { - @Override - public void call() throws Throwable { - mock.say(value); - } - }); + Throwable throwable = catchThrowable(() -> mock.say(value)); assertThat(throwable) .as("Mock for final method works") diff --git a/tests/mockito/inline/src/test/java/samples/powermockito/inline/bugs/github793/PartialMockingExampleTest.java b/tests/mockito/inline/src/test/java/samples/powermockito/inline/bugs/github793/PartialMockingExampleTest.java index 9f3acdea6..84702eb12 100644 --- a/tests/mockito/inline/src/test/java/samples/powermockito/inline/bugs/github793/PartialMockingExampleTest.java +++ b/tests/mockito/inline/src/test/java/samples/powermockito/inline/bugs/github793/PartialMockingExampleTest.java @@ -20,6 +20,7 @@ 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; diff --git a/tests/mockito/inline/src/test/java/samples/powermockito/inline/bugs/github793/PowerMockStaticMockingTest.java b/tests/mockito/inline/src/test/java/samples/powermockito/inline/bugs/github793/PowerMockStaticMockingTest.java index 0d0763cc1..1d149418d 100644 --- a/tests/mockito/inline/src/test/java/samples/powermockito/inline/bugs/github793/PowerMockStaticMockingTest.java +++ b/tests/mockito/inline/src/test/java/samples/powermockito/inline/bugs/github793/PowerMockStaticMockingTest.java @@ -18,7 +18,6 @@ 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; @@ -27,8 +26,8 @@ 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.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assume.assumeTrue; import static org.mockito.Mockito.when; @@ -65,12 +64,9 @@ public void should_verify_static_method_when_mockito_inline_mock_creator_for_moc PowerMockito.doNothing().when(StaticClass.class,"say", value); - assertThatThrownBy(new ThrowingCallable() { - @Override - public void call() throws Throwable { - StaticClass.say(value); - PowerMockito.verifyNoMoreInteractions(StaticClass.class); - } + assertThatThrownBy(() -> { + StaticClass.say(value); + PowerMockito.verifyNoMoreInteractions(StaticClass.class); }).as("Verify exception is thrown") .isInstanceOf(NoInteractionsWanted.class); } diff --git a/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/AnnotationUsageTest.java b/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/AnnotationUsageTest.java index e38d53dd5..a28c69e66 100644 --- a/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/AnnotationUsageTest.java +++ b/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/AnnotationUsageTest.java @@ -24,11 +24,12 @@ 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 samples.Service; +import samples.annotationbased.AnnotationDemo; + import static org.junit.Assert.assertEquals; import static org.powermock.api.mockito.PowerMockito.when; diff --git a/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/AssertPowerMockRuleDelagatesToOtherRulesTest.java b/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/AssertPowerMockRuleDelagatesToOtherRulesTest.java index cbf8dfedc..46c0c00a3 100644 --- a/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/AssertPowerMockRuleDelagatesToOtherRulesTest.java +++ b/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/AssertPowerMockRuleDelagatesToOtherRulesTest.java @@ -27,7 +27,7 @@ import java.util.LinkedList; import java.util.List; -import static org.assertj.core.api.Java6Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * This test demonstrates that the PowerMockRule delegates to other rules. @@ -35,7 +35,7 @@ public class AssertPowerMockRuleDelagatesToOtherRulesTest { private static final MyObject BEFORE = new MyObject(); - private final List objects = new LinkedList(); + private final List objects = new LinkedList<>(); @Rule public PowerMockRule powerMockRule = new PowerMockRule(); diff --git a/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/LargeMethodTest.java b/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/LargeMethodTest.java index 2191398f6..5e9418bc4 100644 --- a/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/LargeMethodTest.java +++ b/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/LargeMethodTest.java @@ -4,6 +4,7 @@ import org.junit.Test; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.rule.PowerMockRule; + import samples.largemethod.MethodExceedingJvmLimit; import static org.junit.Assert.assertEquals; diff --git a/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/MemberModificationExampleTest.java b/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/MemberModificationExampleTest.java index 3403561c9..89f2115cd 100644 --- a/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/MemberModificationExampleTest.java +++ b/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/MemberModificationExampleTest.java @@ -19,15 +19,16 @@ import org.junit.Test; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.rule.PowerMockRule; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; + 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; diff --git a/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/MockFinalNonStaticMethodsTest.java b/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/MockFinalNonStaticMethodsTest.java index 594b25e8b..d99b7f66f 100644 --- a/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/MockFinalNonStaticMethodsTest.java +++ b/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/MockFinalNonStaticMethodsTest.java @@ -18,6 +18,7 @@ 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; diff --git a/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/MockFinalUsingAnnotationsTest.java b/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/MockFinalUsingAnnotationsTest.java index 1152c223e..ad925e9bb 100644 --- a/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/MockFinalUsingAnnotationsTest.java +++ b/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/MockFinalUsingAnnotationsTest.java @@ -21,6 +21,7 @@ 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; @@ -40,7 +41,7 @@ public class MockFinalUsingAnnotationsTest { private FinalDemo usingMockitoMockAnnotation; @SuppressWarnings("deprecation") - @org.mockito.Mock + @Mock private FinalDemo usingDeprecatedMockitoMockAnnotation; @Test diff --git a/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/MockStaticTest.java b/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/MockStaticTest.java index 10d486531..f2a4b60b3 100644 --- a/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/MockStaticTest.java +++ b/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/MockStaticTest.java @@ -18,6 +18,7 @@ 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; diff --git a/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/MockStaticWithPrivateCtorTest.java b/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/MockStaticWithPrivateCtorTest.java index 392f4fb00..c2c54ed48 100644 --- a/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/MockStaticWithPrivateCtorTest.java +++ b/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/MockStaticWithPrivateCtorTest.java @@ -20,6 +20,7 @@ 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; diff --git a/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/PrivateInstanceMockingTest.java b/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/PrivateInstanceMockingTest.java index 7f9669a51..090f3e9e5 100644 --- a/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/PrivateInstanceMockingTest.java +++ b/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/PrivateInstanceMockingTest.java @@ -3,6 +3,7 @@ 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; diff --git a/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/StubMethodTest.java b/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/StubMethodTest.java index 4d58c9e02..3f5695489 100644 --- a/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/StubMethodTest.java +++ b/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/StubMethodTest.java @@ -21,10 +21,11 @@ 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 org.junit.Assert.fail; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; import static org.powermock.api.support.membermodification.MemberMatcher.method; import static org.powermock.api.support.membermodification.MemberModifier.stub; diff --git a/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/SuppressConstructorDemoTest.java b/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/SuppressConstructorDemoTest.java index f9300c0aa..381534615 100644 --- a/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/SuppressConstructorDemoTest.java +++ b/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/SuppressConstructorDemoTest.java @@ -20,6 +20,7 @@ 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; diff --git a/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/SuppressConstructorHierarchyDemoTest.java b/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/SuppressConstructorHierarchyDemoTest.java index 93cce743d..43d3ed603 100644 --- a/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/SuppressConstructorHierarchyDemoTest.java +++ b/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/SuppressConstructorHierarchyDemoTest.java @@ -20,6 +20,7 @@ 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; @@ -35,46 +36,46 @@ public class SuppressConstructorHierarchyDemoTest { @Rule public PowerMockRule powerMockRule = new PowerMockRule(); - @Test + @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); - } + 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 + @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()); - } - } + @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()); - } + /** + * 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()); + } } diff --git a/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/SystemClassUserTest.java b/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/SystemClassUserTest.java index 3471b1893..4120623e9 100644 --- a/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/SystemClassUserTest.java +++ b/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/SystemClassUserTest.java @@ -19,17 +19,23 @@ 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 samples.system.SystemClassUser; + 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.*; +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.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 @@ -94,7 +100,7 @@ public void assertThatPartialMockingOfFinalSystemClassesWorks() throws Exception @Test public void assertThatMockingOfCollectionsWork() throws Exception { - List list = new LinkedList(); + List list = new LinkedList<>(); mockStatic(Collections.class); Collections.shuffle(list); diff --git a/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/WhenNewTest.java b/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/WhenNewTest.java index be471b3a3..6d6d38d7c 100644 --- a/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/WhenNewTest.java +++ b/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/WhenNewTest.java @@ -18,11 +18,12 @@ import org.junit.Rule; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.rule.PowerMockRule; + +import java.io.DataInputStream; + 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(..). * diff --git a/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/github512/Github512Test.java b/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/github512/Github512Test.java index 50cf65760..8c8271442 100644 --- a/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/github512/Github512Test.java +++ b/tests/mockito/junit4-agent/src/test/java/samples/powermockito/junit4/agent/github512/Github512Test.java @@ -5,9 +5,10 @@ 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.assertj.core.api.Assertions.assertThat; import static org.powermock.api.mockito.PowerMockito.method; import static org.powermock.api.mockito.PowerMockito.suppress; diff --git a/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/EnclosedTest.java b/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/EnclosedTest.java index f0fa6d0c8..2a21f1594 100644 --- a/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/EnclosedTest.java +++ b/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/EnclosedTest.java @@ -21,12 +21,16 @@ 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.*; +import static org.powermock.api.mockito.PowerMockito.mockStatic; +import static org.powermock.api.mockito.PowerMockito.verifyNoMoreInteractions; +import static org.powermock.api.mockito.PowerMockito.verifyStatic; +import static org.powermock.api.mockito.PowerMockito.when; /** * Demonstrates how PowerMockRunner with annotation PowerMockRunnerDelegate can diff --git a/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/JUnitParamsTest.java b/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/JUnitParamsTest.java index 951239061..fb0dcd55d 100644 --- a/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/JUnitParamsTest.java +++ b/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/JUnitParamsTest.java @@ -1,7 +1,5 @@ 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; @@ -11,6 +9,9 @@ import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunnerDelegate; +import junitparams.JUnitParamsRunner; +import junitparams.Parameters; + import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.when; diff --git a/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/SelfieTest.java b/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/SelfieTest.java index e65029912..48b20276f 100644 --- a/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/SelfieTest.java +++ b/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/SelfieTest.java @@ -24,12 +24,14 @@ 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.*; +import static org.powermock.api.mockito.PowerMockito.mockStatic; +import static org.powermock.api.mockito.PowerMockito.when; /** * Demonstrates how PowerMockRunner with annotation PowerMockRunnerDelegate can diff --git a/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/SuppressedMethodStubbing.java b/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/SuppressedMethodStubbing.java index d242395d5..cf5281e07 100644 --- a/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/SuppressedMethodStubbing.java +++ b/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/SuppressedMethodStubbing.java @@ -15,9 +15,10 @@ */ package powermock.modules.test.mockito.junit4.delegate; -import java.util.concurrent.Callable; import org.powermock.api.support.membermodification.strategy.MethodStubStrategy; +import java.util.concurrent.Callable; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; @@ -33,16 +34,13 @@ public void enforceOn(MethodStubStrategy stub) { @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; - } + super.verify((Callable) () -> { + try { + invocation.call(); + fail("Expected exception: " + value); + return null; + } catch (Exception actualException) { + return actualException; } }); } @@ -55,7 +53,7 @@ public String toString() { final Object value; - private SuppressedMethodStubbing(Object value) { + SuppressedMethodStubbing(Object value) { this.value = value; } diff --git a/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/SystemClassUserCases.java b/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/SystemClassUserCases.java index 4817909d2..eacfac6ef 100644 --- a/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/SystemClassUserCases.java +++ b/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/SystemClassUserCases.java @@ -19,17 +19,23 @@ 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 samples.system.SystemClassUser; + 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.*; +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.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 @@ -92,7 +98,7 @@ public void assertThatPartialMockingOfFinalSystemClassesWorks() throws Exception @Test public void assertThatMockingOfCollectionsWork() throws Exception { - List list = new LinkedList(); + List list = new LinkedList<>(); mockStatic(Collections.class); Collections.shuffle(list); diff --git a/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/SystemClassUserMethod.java b/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/SystemClassUserMethod.java index ec783aab6..0faa93347 100644 --- a/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/SystemClassUserMethod.java +++ b/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/SystemClassUserMethod.java @@ -15,10 +15,11 @@ */ package powermock.modules.test.mockito.junit4.delegate; +import org.junit.Test; + import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; -import org.junit.Test; public class SystemClassUserMethod { @@ -30,14 +31,13 @@ public SystemClassUserMethod(Method method) { public static SystemClassUserMethod[] values() { Method[] methods = SystemClassUserCases.class.getDeclaredMethods(); - List values = - new ArrayList(methods.length); + 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()]); + return values.toArray(new SystemClassUserMethod[0]); } @Override diff --git a/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/WhenNewCaseMethod.java b/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/WhenNewCaseMethod.java index 1c510a165..085ab4618 100644 --- a/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/WhenNewCaseMethod.java +++ b/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/WhenNewCaseMethod.java @@ -15,11 +15,13 @@ */ package powermock.modules.test.mockito.junit4.delegate; +import org.junit.Test; + 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 { @@ -51,12 +53,12 @@ public boolean nullPointerIsExpected() { public static WhenNewCaseMethod[] values() { Method[] methods = WhenNewCases.class.getDeclaredMethods(); List values - = new ArrayList(methods.length); + = 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()]); + return values.toArray(new WhenNewCaseMethod[0]); } } diff --git a/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/parameterized/FinalDemoTest.java b/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/parameterized/FinalDemoTest.java index 5f9c5769a..99488ca07 100644 --- a/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/parameterized/FinalDemoTest.java +++ b/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/parameterized/FinalDemoTest.java @@ -15,16 +15,17 @@ */ 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 java.lang.reflect.Method; +import java.util.Arrays; +import java.util.Collection; + import samples.finalmocking.FinalDemo; import samples.privateandfinal.PrivateFinal; @@ -33,7 +34,11 @@ 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.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; /** @@ -49,7 +54,7 @@ public class FinalDemoTest { @Parameterized.Parameters(name = "expected={0}") public static Collection expections() { - return java.util.Arrays.asList(new Object[][]{ + return Arrays.asList(new Object[][]{ {"Hello altered World"}, {"something"}, {"test"} }); } diff --git a/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/parameterized/MockFinalUsingAnnotationsTest.java b/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/parameterized/MockFinalUsingAnnotationsTest.java index e2705a47d..c68459fea 100644 --- a/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/parameterized/MockFinalUsingAnnotationsTest.java +++ b/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/parameterized/MockFinalUsingAnnotationsTest.java @@ -15,8 +15,6 @@ */ 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; @@ -25,6 +23,10 @@ import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunnerDelegate; import org.powermock.reflect.Whitebox; + +import java.util.ArrayList; +import java.util.List; + import samples.finalmocking.FinalDemo; import static org.junit.Assert.assertNull; @@ -42,7 +44,7 @@ public class MockFinalUsingAnnotationsTest { @Mock private FinalDemo usingMockitoMockAnnotation; - @org.mockito.Mock + @Mock private FinalDemo usingDeprecatedMockitoMockAnnotation; @Parameterized.Parameter(0) @@ -60,7 +62,7 @@ public void testMockFinal() throws Exception { @Parameterized.Parameters(name = "{0}") public static List vals() { MockField[] mockFields = MockField.values(); - List vals = new ArrayList(mockFields.length); + List vals = new ArrayList<>(mockFields.length); for (MockField each : mockFields) { vals.add(new Object[]{each}); } diff --git a/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/parameterized/StubMethodTest.java b/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/parameterized/StubMethodTest.java index 682416327..c028ac4e1 100644 --- a/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/parameterized/StubMethodTest.java +++ b/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/parameterized/StubMethodTest.java @@ -15,23 +15,29 @@ */ 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 java.util.Arrays; +import java.util.List; +import java.util.concurrent.Callable; + 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.*; +import static powermock.modules.test.mockito.junit4.delegate.SuppressedMethod.getFloat; +import static powermock.modules.test.mockito.junit4.delegate.SuppressedMethod.getObject; +import static powermock.modules.test.mockito.junit4.delegate.SuppressedMethod.getObjectStatic; +import static powermock.modules.test.mockito.junit4.delegate.SuppressedMethodStubbing.Hello; +import static powermock.modules.test.mockito.junit4.delegate.SuppressedMethodStubbing.exception; +import static powermock.modules.test.mockito.junit4.delegate.SuppressedMethodStubbing.float_4; @RunWith(PowerMockRunner.class) @PowerMockRunnerDelegate(Parameterized.class) @@ -49,12 +55,7 @@ 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); - } - }; + Callable methodInvocation = (Callable) () -> method.invokeOn(tested); stubbing.verify(methodInvocation); stubbing.verify(methodInvocation); diff --git a/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/parameterized/SuppressConstructorDemoTest.java b/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/parameterized/SuppressConstructorDemoTest.java index a29b0b8a3..60fdf368d 100644 --- a/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/parameterized/SuppressConstructorDemoTest.java +++ b/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/parameterized/SuppressConstructorDemoTest.java @@ -15,15 +15,17 @@ */ 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 java.util.Arrays; +import java.util.Collections; +import java.util.List; + import samples.suppressconstructor.SuppressConstructorDemo; import samples.suppressconstructor.SuppressConstructorSubclassDemo; diff --git a/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/parameterized/SuppressConstructorHierarchyDemoTest.java b/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/parameterized/SuppressConstructorHierarchyDemoTest.java index 4d190c5fc..23178ee0f 100644 --- a/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/parameterized/SuppressConstructorHierarchyDemoTest.java +++ b/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/parameterized/SuppressConstructorHierarchyDemoTest.java @@ -15,8 +15,6 @@ */ 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; @@ -24,10 +22,16 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunnerDelegate; + +import java.util.Arrays; +import java.util.List; + import samples.suppressconstructor.InvokeConstructor; import samples.suppressconstructor.SuppressConstructorHierarchy; -import static org.junit.Assert.*; +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; diff --git a/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/parameterized/SupressMethodExampleTest.java b/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/parameterized/SupressMethodExampleTest.java index 802771d4b..752854a9d 100644 --- a/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/parameterized/SupressMethodExampleTest.java +++ b/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/parameterized/SupressMethodExampleTest.java @@ -15,9 +15,6 @@ */ 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; @@ -27,17 +24,27 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunnerDelegate; + +import java.util.Arrays; +import java.util.Collection; + import samples.suppressconstructor.SuppressConstructorHierarchy; import samples.suppresseverything.SuppressEverything; +import samples.suppressfield.DomainObject; 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.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.powermock.api.support.membermodification.MemberModifier.constructor; +import static org.powermock.api.support.membermodification.MemberModifier.field; +import static org.powermock.api.support.membermodification.MemberModifier.method; +import static org.powermock.api.support.membermodification.MemberModifier.suppress; /** * Demonstrates PowerMock's ability to modify member structures. @@ -99,7 +106,7 @@ void doIt() { final Matcher expectation; - private FieldSuppression(Matcher expectation) { + FieldSuppression(Matcher expectation) { this.expectation = expectation; } diff --git a/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/parameterized/SystemClassUserTest.java b/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/parameterized/SystemClassUserTest.java index f9f5f548b..a44479259 100644 --- a/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/parameterized/SystemClassUserTest.java +++ b/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/parameterized/SystemClassUserTest.java @@ -15,9 +15,6 @@ */ 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; @@ -25,6 +22,11 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunnerDelegate; + +import java.lang.reflect.InvocationTargetException; +import java.util.ArrayList; +import java.util.List; + import powermock.modules.test.mockito.junit4.delegate.SystemClassUserCases; import powermock.modules.test.mockito.junit4.delegate.SystemClassUserMethod; import samples.system.SystemClassUser; @@ -63,7 +65,7 @@ public void evaluate() throws Throwable { @Parameterized.Parameters(name = "{0}") public static List paramValues() { - List values = new ArrayList(); + List values = new ArrayList<>(); for (SystemClassUserMethod tstCase : SystemClassUserMethod.values()) { values.add(new Object[]{tstCase}); } diff --git a/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/parameterized/WhenNewTest.java b/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/parameterized/WhenNewTest.java index dfe51be42..5d882ec4b 100644 --- a/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/parameterized/WhenNewTest.java +++ b/tests/mockito/junit4-delegate/src/test/java/powermock/modules/test/mockito/junit4/delegate/parameterized/WhenNewTest.java @@ -15,23 +15,24 @@ */ 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.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunnerDelegate; + +import java.io.DataInputStream; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + import powermock.modules.test.mockito.junit4.delegate.WhenNewCaseMethod; +import samples.classwithinnermembers.ClassWithInnerMembers; +import samples.expectnew.ExpectNewDemo; +import samples.newmocking.MyClass; import samples.powermockito.junit4.whennew.WhenNewCases; @PrepareForTest({MyClass.class, ExpectNewDemo.class, ClassWithInnerMembers.class, DataInputStream.class, @@ -57,7 +58,7 @@ public void test() throws Throwable { @Parameterized.Parameters(name = "{0}") public static Collection whenNewCases() { WhenNewCaseMethod[] cases = WhenNewCaseMethod.values(); - List paramValues = new ArrayList(cases.length); + List paramValues = new ArrayList<>(cases.length); for (WhenNewCaseMethod each : cases) { paramValues.add(new Object[]{each}); } diff --git a/tests/mockito/junit4-rule-objenesis/src/test/java/samples/powermockito/junit4/rule/objenesis/MockFinalNonStaticMethodsTest.java b/tests/mockito/junit4-rule-objenesis/src/test/java/samples/powermockito/junit4/rule/objenesis/MockFinalNonStaticMethodsTest.java index 9ccfe7f19..367e2a0cc 100644 --- a/tests/mockito/junit4-rule-objenesis/src/test/java/samples/powermockito/junit4/rule/objenesis/MockFinalNonStaticMethodsTest.java +++ b/tests/mockito/junit4-rule-objenesis/src/test/java/samples/powermockito/junit4/rule/objenesis/MockFinalNonStaticMethodsTest.java @@ -18,6 +18,7 @@ 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; diff --git a/tests/mockito/junit4-rule-objenesis/src/test/java/samples/powermockito/junit4/rule/objenesis/MockStaticTest.java b/tests/mockito/junit4-rule-objenesis/src/test/java/samples/powermockito/junit4/rule/objenesis/MockStaticTest.java index 005a65dbb..ff561d170 100644 --- a/tests/mockito/junit4-rule-objenesis/src/test/java/samples/powermockito/junit4/rule/objenesis/MockStaticTest.java +++ b/tests/mockito/junit4-rule-objenesis/src/test/java/samples/powermockito/junit4/rule/objenesis/MockStaticTest.java @@ -18,6 +18,7 @@ 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; diff --git a/tests/mockito/junit4-rule-objenesis/src/test/java/samples/powermockito/junit4/rule/objenesis/PowerMockRuleTest.java b/tests/mockito/junit4-rule-objenesis/src/test/java/samples/powermockito/junit4/rule/objenesis/PowerMockRuleTest.java index fe8a21a22..73814b695 100644 --- a/tests/mockito/junit4-rule-objenesis/src/test/java/samples/powermockito/junit4/rule/objenesis/PowerMockRuleTest.java +++ b/tests/mockito/junit4-rule-objenesis/src/test/java/samples/powermockito/junit4/rule/objenesis/PowerMockRuleTest.java @@ -1,6 +1,5 @@ package samples.powermockito.junit4.rule.objenesis; - import org.junit.Rule; import org.junit.Test; import org.powermock.core.classloader.annotations.MockPolicy; @@ -11,6 +10,7 @@ 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; diff --git a/tests/mockito/junit4-rule-objenesis/src/test/java/samples/powermockito/junit4/rule/objenesis/PrivateInstanceMockingTest.java b/tests/mockito/junit4-rule-objenesis/src/test/java/samples/powermockito/junit4/rule/objenesis/PrivateInstanceMockingTest.java index 5cff8eb59..2c59b29c3 100644 --- a/tests/mockito/junit4-rule-objenesis/src/test/java/samples/powermockito/junit4/rule/objenesis/PrivateInstanceMockingTest.java +++ b/tests/mockito/junit4-rule-objenesis/src/test/java/samples/powermockito/junit4/rule/objenesis/PrivateInstanceMockingTest.java @@ -3,6 +3,7 @@ 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; diff --git a/tests/mockito/junit4-rule-objenesis/src/test/java/samples/powermockito/junit4/rule/objenesis/StaticInitializerExampleTest.java b/tests/mockito/junit4-rule-objenesis/src/test/java/samples/powermockito/junit4/rule/objenesis/StaticInitializerExampleTest.java index 1412913e0..81887ad08 100644 --- a/tests/mockito/junit4-rule-objenesis/src/test/java/samples/powermockito/junit4/rule/objenesis/StaticInitializerExampleTest.java +++ b/tests/mockito/junit4-rule-objenesis/src/test/java/samples/powermockito/junit4/rule/objenesis/StaticInitializerExampleTest.java @@ -5,10 +5,11 @@ 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 samples.staticinitializer.StaticInitializerExample; + import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; @@ -21,7 +22,7 @@ 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(); + final HashSet hashSet = new HashSet<>(); Whitebox.setInternalState(StaticInitializerExample.class, "mySet", hashSet); assertSame(hashSet, Whitebox.getInternalState(StaticInitializerExample.class, "mySet")); } diff --git a/tests/mockito/junit4-rule-objenesis/src/test/java/samples/powermockito/junit4/rule/objenesis/SystemClassUserTest.java b/tests/mockito/junit4-rule-objenesis/src/test/java/samples/powermockito/junit4/rule/objenesis/SystemClassUserTest.java index 3093d256e..829426de3 100644 --- a/tests/mockito/junit4-rule-objenesis/src/test/java/samples/powermockito/junit4/rule/objenesis/SystemClassUserTest.java +++ b/tests/mockito/junit4-rule-objenesis/src/test/java/samples/powermockito/junit4/rule/objenesis/SystemClassUserTest.java @@ -20,13 +20,14 @@ 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 samples.system.SystemClassUser; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import static org.mockito.Mockito.times; @@ -98,7 +99,7 @@ public void assertThatPartialMockingOfFinalSystemClassesWorks() throws Exception @Test public void assertThatMockingOfCollectionsWork() throws Exception { - List list = new LinkedList(); + List list = new LinkedList<>(); mockStatic(Collections.class); Collections.shuffle(list); diff --git a/tests/mockito/junit4-rule-objenesis/src/test/java/samples/powermockito/junit4/rule/objenesis/WhenNewTest.java b/tests/mockito/junit4-rule-objenesis/src/test/java/samples/powermockito/junit4/rule/objenesis/WhenNewTest.java index 3c62b2f8d..04139b0a6 100644 --- a/tests/mockito/junit4-rule-objenesis/src/test/java/samples/powermockito/junit4/rule/objenesis/WhenNewTest.java +++ b/tests/mockito/junit4-rule-objenesis/src/test/java/samples/powermockito/junit4/rule/objenesis/WhenNewTest.java @@ -19,12 +19,13 @@ import org.junit.Rule; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.rule.PowerMockRule; + +import java.io.DataInputStream; + 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(..). * diff --git a/tests/mockito/junit4-rule-objenesis/src/test/java/samples/powermockito/junit4/rule/objenesis/bugs/github512/Github512Test.java b/tests/mockito/junit4-rule-objenesis/src/test/java/samples/powermockito/junit4/rule/objenesis/bugs/github512/Github512Test.java index dd145a0d2..caea02252 100644 --- a/tests/mockito/junit4-rule-objenesis/src/test/java/samples/powermockito/junit4/rule/objenesis/bugs/github512/Github512Test.java +++ b/tests/mockito/junit4-rule-objenesis/src/test/java/samples/powermockito/junit4/rule/objenesis/bugs/github512/Github512Test.java @@ -4,9 +4,10 @@ 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.assertj.core.api.Assertions.assertThat; import static org.powermock.api.mockito.PowerMockito.method; import static org.powermock.api.mockito.PowerMockito.suppress; diff --git a/tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/AssertPowerMockRuleDelagatesToOtherRulesTest.java b/tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/AssertPowerMockRuleDelagatesToOtherRulesTest.java index 32f97d6f2..a92a882cb 100644 --- a/tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/AssertPowerMockRuleDelagatesToOtherRulesTest.java +++ b/tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/AssertPowerMockRuleDelagatesToOtherRulesTest.java @@ -27,7 +27,7 @@ import java.util.LinkedList; import java.util.List; -import static org.assertj.core.api.Java6Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * This test demonstrates that the PowerMockRule delegates to other rules. @@ -35,7 +35,7 @@ public class AssertPowerMockRuleDelagatesToOtherRulesTest { private static final MyObject BEFORE = new MyObject(); - private final List objects = new LinkedList(); + private final List objects = new LinkedList<>(); @Rule public PowerMockRule powerMockRule = new PowerMockRule(); @@ -58,6 +58,7 @@ public void assertPowerMockRuleDelegatesToOtherRules() throws Exception { } private class MyRule implements MethodRule { + @Override public Statement apply(final Statement base, FrameworkMethod method, Object target) { return new Statement() { @Override diff --git a/tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/MockFinalNonStaticMethodsTest.java b/tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/MockFinalNonStaticMethodsTest.java index 6f1e4cc05..817ddf377 100644 --- a/tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/MockFinalNonStaticMethodsTest.java +++ b/tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/MockFinalNonStaticMethodsTest.java @@ -18,6 +18,7 @@ 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; diff --git a/tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/MockStaticTest.java b/tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/MockStaticTest.java index 73aa44de3..34d85416e 100644 --- a/tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/MockStaticTest.java +++ b/tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/MockStaticTest.java @@ -18,6 +18,7 @@ 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; diff --git a/tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/PowerMockRuleTest.java b/tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/PowerMockRuleTest.java index d92727909..6aeada8fe 100644 --- a/tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/PowerMockRuleTest.java +++ b/tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/PowerMockRuleTest.java @@ -1,6 +1,5 @@ package samples.powermockito.junit4.rule.xstream; - import org.junit.Rule; import org.junit.Test; import org.powermock.core.classloader.annotations.MockPolicy; @@ -11,6 +10,7 @@ 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; diff --git a/tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/PrivateInstanceMockingTest.java b/tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/PrivateInstanceMockingTest.java index b1eda541d..222512108 100644 --- a/tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/PrivateInstanceMockingTest.java +++ b/tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/PrivateInstanceMockingTest.java @@ -3,6 +3,7 @@ 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; diff --git a/tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/StaticInitializerExampleTest.java b/tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/StaticInitializerExampleTest.java index 979e7a571..2b66062ba 100644 --- a/tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/StaticInitializerExampleTest.java +++ b/tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/StaticInitializerExampleTest.java @@ -5,10 +5,11 @@ 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 samples.staticinitializer.StaticInitializerExample; + import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; @@ -21,7 +22,7 @@ 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(); + final HashSet hashSet = new HashSet<>(); Whitebox.setInternalState(StaticInitializerExample.class, "mySet", hashSet); assertSame(hashSet, Whitebox.getInternalState(StaticInitializerExample.class, "mySet")); } diff --git a/tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/SystemClassUserTest.java b/tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/SystemClassUserTest.java index 322f43eb4..327aaaae1 100644 --- a/tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/SystemClassUserTest.java +++ b/tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/SystemClassUserTest.java @@ -20,13 +20,14 @@ 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 samples.system.SystemClassUser; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import static org.mockito.Mockito.times; @@ -98,7 +99,7 @@ public void assertThatPartialMockingOfFinalSystemClassesWorks() throws Exception @Test public void assertThatMockingOfCollectionsWork() throws Exception { - List list = new LinkedList(); + List list = new LinkedList<>(); mockStatic(Collections.class); Collections.shuffle(list); diff --git a/tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/WhenNewTest.java b/tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/WhenNewTest.java index ad62021d9..8a4edb149 100644 --- a/tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/WhenNewTest.java +++ b/tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/WhenNewTest.java @@ -19,6 +19,7 @@ import org.junit.Rule; import org.junit.Test; import org.powermock.modules.junit4.rule.PowerMockRule; + import samples.powermockito.junit4.whennew.WhenNewCases; diff --git a/tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/github512/Github512Test.java b/tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/github512/Github512Test.java index d9ee3f3e9..3247a11df 100644 --- a/tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/github512/Github512Test.java +++ b/tests/mockito/junit4-rule-xstream/src/test/java/samples/powermockito/junit4/rule/xstream/github512/Github512Test.java @@ -4,9 +4,10 @@ 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.assertj.core.api.Assertions.assertThat; import static org.powermock.api.mockito.PowerMockito.method; import static org.powermock.api.mockito.PowerMockito.suppress; diff --git a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/FinalEqualsClassTest.java b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/FinalEqualsClassTest.java index 47b8df901..af1612742 100644 --- a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/FinalEqualsClassTest.java +++ b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/FinalEqualsClassTest.java @@ -1,13 +1,14 @@ 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; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; /* * Copyright 2011 the original author or authors. * diff --git a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/abstractmocking/AbstractMethodMockingTest.java b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/abstractmocking/AbstractMethodMockingTest.java index a38c11678..fbcee19b7 100644 --- a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/abstractmocking/AbstractMethodMockingTest.java +++ b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/abstractmocking/AbstractMethodMockingTest.java @@ -19,10 +19,15 @@ 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.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.powermock.api.mockito.PowerMockito.mock; +import static org.powermock.api.mockito.PowerMockito.spy; +import static org.powermock.api.mockito.PowerMockito.when; @RunWith(PowerMockRunner.class) @PrepareForTest( { AbstractMethodMocking.class }) diff --git a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/annotationbased/CaptorAnnotationTest.java b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/annotationbased/CaptorAnnotationTest.java index 596df04ee..17a27846c 100644 --- a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/annotationbased/CaptorAnnotationTest.java +++ b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/annotationbased/CaptorAnnotationTest.java @@ -21,6 +21,7 @@ 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; @@ -28,7 +29,10 @@ 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.*; +import static org.powermock.api.mockito.PowerMockito.method; +import static org.powermock.api.mockito.PowerMockito.mock; +import static org.powermock.api.mockito.PowerMockito.spy; +import static org.powermock.api.mockito.PowerMockito.verifyPrivate; /** * Asserts that {@link Captor} with PowerMock. diff --git a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/annotationbased/ChunkingAndStaticInitializerRemovalTest.java b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/annotationbased/ChunkingAndStaticInitializerRemovalTest.java index a389df5f0..04f50cebf 100644 --- a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/annotationbased/ChunkingAndStaticInitializerRemovalTest.java +++ b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/annotationbased/ChunkingAndStaticInitializerRemovalTest.java @@ -22,6 +22,7 @@ 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; diff --git a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/annotationbased/InjectMocksAnnotationTest.java b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/annotationbased/InjectMocksAnnotationTest.java index 77ff895b2..6a5580853 100644 --- a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/annotationbased/InjectMocksAnnotationTest.java +++ b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/annotationbased/InjectMocksAnnotationTest.java @@ -21,6 +21,7 @@ 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; diff --git a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/annotationbased/MockFinalUsingAnnotationsTest.java b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/annotationbased/MockFinalUsingAnnotationsTest.java index b1a1e3626..4324855d6 100644 --- a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/annotationbased/MockFinalUsingAnnotationsTest.java +++ b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/annotationbased/MockFinalUsingAnnotationsTest.java @@ -20,6 +20,7 @@ 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; @@ -37,7 +38,7 @@ public class MockFinalUsingAnnotationsTest { private FinalDemo usingMockitoMockAnnotation; @SuppressWarnings("deprecation") - @org.mockito.Mock + @Mock private FinalDemo usingDeprecatedMockitoMockAnnotation; @Test diff --git a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/annotationbased/MockFinalUsingAnnotationsWithAnswersTest.java b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/annotationbased/MockFinalUsingAnnotationsWithAnswersTest.java index a595afcd1..fa87ee088 100644 --- a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/annotationbased/MockFinalUsingAnnotationsWithAnswersTest.java +++ b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/annotationbased/MockFinalUsingAnnotationsWithAnswersTest.java @@ -21,6 +21,7 @@ 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; diff --git a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/annotationbased/SpyAnnotationTest.java b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/annotationbased/SpyAnnotationTest.java index 91a4231fb..7dbff645b 100644 --- a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/annotationbased/SpyAnnotationTest.java +++ b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/annotationbased/SpyAnnotationTest.java @@ -20,6 +20,7 @@ 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; diff --git a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/argumentmatcher/ArgumentMatcherTest.java b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/argumentmatcher/ArgumentMatcherTest.java index 7b4ee2703..b41c1dde3 100644 --- a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/argumentmatcher/ArgumentMatcherTest.java +++ b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/argumentmatcher/ArgumentMatcherTest.java @@ -18,11 +18,12 @@ 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 samples.argumentmatcher.ArgumentMatcherDemo; + import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.ArgumentMatchers.eq; @@ -34,7 +35,7 @@ public class ArgumentMatcherTest { @Test public void worksWithArgumentMatchers() throws Exception { - final ArrayList strings = new ArrayList(); + final ArrayList strings = new ArrayList<>(); final ArgumentMatcherDemo tested = mock(ArgumentMatcherDemo.class); doReturn(strings).when(tested, "findByNamedQuery", eq("AbstractPTVTicket.ticketSeatIds"), anyList()); diff --git a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github668/GitHub668Test.java b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github668/GitHub668Test.java index 307f8fa9a..1e8faa681 100644 --- a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github668/GitHub668Test.java +++ b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github668/GitHub668Test.java @@ -1,16 +1,14 @@ 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 javax.security.auth.Subject; -import static org.assertj.core.api.Java6Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.powermock.api.mockito.PowerMockito.mock; import static org.powermock.api.mockito.PowerMockito.when; @@ -22,7 +20,7 @@ public class GitHub668Test { public void shouldMockJavaxSystemFinalClasses() { Subject subject = mock(Subject.class); - final HashSet value = new HashSet(); + final HashSet value = new HashSet<>(); when(subject.getPrivateCredentials()).thenReturn(value); assertThat(subject.getPrivateCredentials()).isSameAs(value); diff --git a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github701/GitHub701Test.java b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github701/GitHub701Test.java index aaa54e6f7..9f3a962cc 100644 --- a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github701/GitHub701Test.java +++ b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github701/GitHub701Test.java @@ -6,7 +6,7 @@ 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.Assertions.assertThat; import static org.powermock.api.mockito.PowerMockito.doReturn; import static org.powermock.api.mockito.PowerMockito.mock; diff --git a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github704/PrepareForTestSignedTest.java b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github704/PrepareForTestSignedTest.java index 47d0e3c26..4ef6ed6c5 100644 --- a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github704/PrepareForTestSignedTest.java +++ b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github704/PrepareForTestSignedTest.java @@ -6,7 +6,7 @@ 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.Assertions.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; diff --git a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github731/MockingInterfacesTest.java b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github731/MockingInterfacesTest.java index f904b0499..30223700f 100644 --- a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github731/MockingInterfacesTest.java +++ b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github731/MockingInterfacesTest.java @@ -1,6 +1,5 @@ package samples.powermockito.junit4.bugs.github731; - import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.modules.junit4.PowerMockRunner; diff --git a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github781/GitHub781Test.java b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github781/GitHub781Test.java index ec22f7c89..39a393a8c 100644 --- a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github781/GitHub781Test.java +++ b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github781/GitHub781Test.java @@ -6,7 +6,7 @@ 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.Assertions.assertThat; import static org.mockito.Mockito.spy; @RunWith(PowerMockRunner.class) diff --git a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github801/GlobalPowerMockIgnoreTest.java b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github801/GlobalPowerMockIgnoreTest.java index 84e41bdd2..c503e91b5 100644 --- a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github801/GlobalPowerMockIgnoreTest.java +++ b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/bugs/github801/GlobalPowerMockIgnoreTest.java @@ -22,7 +22,7 @@ import org.junit.runner.RunWith; import org.powermock.modules.junit4.PowerMockRunner; -import static org.assertj.core.api.Java6Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; @RunWith(PowerMockRunner.class) public class GlobalPowerMockIgnoreTest { diff --git a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/constructor/InnerConstructorsAreFoundTest.java b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/constructor/InnerConstructorsAreFoundTest.java index ea109690b..fc952bb2a 100644 --- a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/constructor/InnerConstructorsAreFoundTest.java +++ b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/constructor/InnerConstructorsAreFoundTest.java @@ -35,7 +35,7 @@ public class InnerConstructorsAreFoundTest { interface AnyInterface { - }; + } class AnyImplementation implements AnyInterface { @Override @@ -49,7 +49,7 @@ class SomeOtherImplementationOfSomethingElse { public boolean equals(Object obj) { return true; } - }; + } // class WorkingObjectUnderTesting { diff --git a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/enums/EnumWithConstructorTest.java b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/enums/EnumWithConstructorTest.java index 9c164680c..c01c6a680 100644 --- a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/enums/EnumWithConstructorTest.java +++ b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/enums/EnumWithConstructorTest.java @@ -5,6 +5,7 @@ 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; diff --git a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/finalmocking/MockFinalMethodsCases.java b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/finalmocking/MockFinalMethodsCases.java index 281544c29..1377e6ca1 100644 --- a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/finalmocking/MockFinalMethodsCases.java +++ b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/finalmocking/MockFinalMethodsCases.java @@ -1,12 +1,13 @@ 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 samples.finalmocking.FinalDemo; +import samples.privateandfinal.PrivateFinal; + +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; diff --git a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/finalmocking/MockFinalNonStaticMethodsTest.java b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/finalmocking/MockFinalNonStaticMethodsTest.java index 5a3fa709b..a3b25dabc 100644 --- a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/finalmocking/MockFinalNonStaticMethodsTest.java +++ b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/finalmocking/MockFinalNonStaticMethodsTest.java @@ -18,6 +18,7 @@ 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; diff --git a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/getannotation/GetAnnotationTest.java b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/getannotation/GetAnnotationTest.java index 7d98625cd..0b2d46629 100644 --- a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/getannotation/GetAnnotationTest.java +++ b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/getannotation/GetAnnotationTest.java @@ -21,11 +21,16 @@ 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.*; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.powermock.api.mockito.PowerMockito.mockStatic; +import static org.powermock.api.mockito.PowerMockito.when; /** * Assert that "isAnnotationPresent" and "getAnnotation" works correctly when mockStatic is used diff --git a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/getclass/GetClassTest.java b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/getclass/GetClassTest.java index 1a917c07d..bdfc2bb29 100644 --- a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/getclass/GetClassTest.java +++ b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/getclass/GetClassTest.java @@ -20,9 +20,12 @@ 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.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; import static org.powermock.api.mockito.PowerMockito.mock; /** diff --git a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/jacoco/JacocoCoverageTest.java b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/jacoco/JacocoCoverageTest.java index 4e338dfa3..e228fda25 100644 --- a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/jacoco/JacocoCoverageTest.java +++ b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/jacoco/JacocoCoverageTest.java @@ -1,6 +1,5 @@ package samples.powermockito.junit4.jacoco; - import org.jacoco.core.analysis.Analyzer; import org.jacoco.core.analysis.CoverageBuilder; import org.jacoco.core.analysis.IClassCoverage; @@ -23,7 +22,7 @@ import java.net.URISyntaxException; import java.net.URL; -import static org.assertj.core.api.Java6Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; public class JacocoCoverageTest { @@ -101,23 +100,12 @@ private void instrumentClasses(IRuntime runtime) throws URISyntaxException, IOEx 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); + try (InputStream is = new FileInputStream(source); OutputStream 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(); - } } } @@ -150,14 +138,8 @@ private void copyOriginalFile(File originalFile) throws IOException, URISyntaxEx } private void writeInstrumentedFile(File originalFile, byte[] instrumented) throws IOException { - FileOutputStream fooStream = null; - try { - fooStream = new FileOutputStream(originalFile, false); + try (FileOutputStream fooStream = new FileOutputStream(originalFile, false)) { fooStream.write(instrumented); - } finally { - if (fooStream != null) { - fooStream.close(); - } } } diff --git a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/jacoco/TargetTest.java b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/jacoco/TargetTest.java index 64d1964ab..db5887ef0 100644 --- a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/jacoco/TargetTest.java +++ b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/jacoco/TargetTest.java @@ -5,7 +5,7 @@ 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.Assertions.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; diff --git a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/largemethod/LargeMethodTest.java b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/largemethod/LargeMethodTest.java index d435cda39..0b7f25ada 100644 --- a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/largemethod/LargeMethodTest.java +++ b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/largemethod/LargeMethodTest.java @@ -5,6 +5,7 @@ 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 org.junit.Assert.assertEquals; diff --git a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/membermodification/MemberModificationExampleTest.java b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/membermodification/MemberModificationExampleTest.java index 7dcf02e88..29ce3483a 100644 --- a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/membermodification/MemberModificationExampleTest.java +++ b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/membermodification/MemberModificationExampleTest.java @@ -19,18 +19,22 @@ import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; + 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.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; @@ -38,7 +42,9 @@ 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.*; +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. diff --git a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/partialmocking/PartialMockingExampleTest.java b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/partialmocking/PartialMockingExampleTest.java index 886403f41..bae00174a 100644 --- a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/partialmocking/PartialMockingExampleTest.java +++ b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/partialmocking/PartialMockingExampleTest.java @@ -20,13 +20,14 @@ 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 samples.partialmocking.PartialMockingExample; + +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -76,7 +77,7 @@ public void should_verify_spied_object_used_in_other_threads() { final CountDownLatch startLatch = new CountDownLatch(1); final CountDownLatch endLatch = new CountDownLatch(threadCounts); - final List values = new CopyOnWriteArrayList(); + final List values = new CopyOnWriteArrayList<>(); for (int i = 0; i < threadCounts; i++) { createAndStartThread(i, underTest, startLatch, endLatch, values); @@ -107,17 +108,14 @@ private void createAndStartThread(final int index, final PartialMockingExample u 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(); + Runnable runnable = () -> { + try { + startLatch.await(); + } catch (InterruptedException e) { + e.printStackTrace(); } + values.add(underTest.methodToTest()); + endLatch.countDown(); }; Thread thread = new Thread(runnable, "mock-use-" + index); diff --git a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/partialmocking/PartialMockingRetainsStateTest.java b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/partialmocking/PartialMockingRetainsStateTest.java index 8a6a677b0..a6e1e8a11 100644 --- a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/partialmocking/PartialMockingRetainsStateTest.java +++ b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/partialmocking/PartialMockingRetainsStateTest.java @@ -19,6 +19,7 @@ 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; diff --git a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/partialmocking/PrivatePartialMockingExampleTest.java b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/partialmocking/PrivatePartialMockingExampleTest.java index 289018ef3..3b28c78d2 100644 --- a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/partialmocking/PrivatePartialMockingExampleTest.java +++ b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/partialmocking/PrivatePartialMockingExampleTest.java @@ -19,12 +19,16 @@ 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 samples.partialmocking.PrivatePartialMockingExample; + import static org.junit.Assert.assertEquals; -import static org.powermock.api.mockito.PowerMockito.*; +import static org.powermock.api.mockito.PowerMockito.doReturn; +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; /** diff --git a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/partialmocking/StaticPartialMockingTest.java b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/partialmocking/StaticPartialMockingTest.java index 60102a9c0..bdb00c3d0 100644 --- a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/partialmocking/StaticPartialMockingTest.java +++ b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/partialmocking/StaticPartialMockingTest.java @@ -17,17 +17,24 @@ 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.mockito.PowerMockito.doAnswer; +import static org.powermock.api.mockito.PowerMockito.doNothing; +import static org.powermock.api.mockito.PowerMockito.doReturn; +import static org.powermock.api.mockito.PowerMockito.doThrow; +import static org.powermock.api.mockito.PowerMockito.spy; +import static org.powermock.api.mockito.PowerMockito.verifyPrivate; +import static org.powermock.api.mockito.PowerMockito.verifyStatic; +import static org.powermock.api.mockito.PowerMockito.when; import static org.powermock.api.support.membermodification.MemberMatcher.method; @RunWith(PowerMockRunner.class) @@ -69,12 +76,7 @@ public void partialPrivateMockingWithAnswerOfStaticMethodReturningObjectWorks() 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"); + doAnswer((Answer) invocation -> "Hello static").when(StaticExample.class, "privateObjectMethod"); assertEquals("Hello static", StaticExample.objectMethod()); /* @@ -190,12 +192,7 @@ public void partialMockingOfNonVoidPublicStaticMethodsWorks() throws Exception { public void partialMockingWithAnswerOfNonVoidPublicStaticMethodsWorks() throws Exception { spy(StaticExample.class); - doAnswer(new Answer() { - @Override - public String answer(InvocationOnMock invocation) throws Throwable { - return "something"; - } - }).when(StaticExample.class); + doAnswer((Answer) invocation -> "something").when(StaticExample.class); StaticExample.staticMethodReturningString(); assertEquals("something", StaticExample.staticMethodReturningString()); diff --git a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/privatemocking/PrivateInstanceMockingCases.java b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/privatemocking/PrivateInstanceMockingCases.java index 15ad7b823..030927298 100644 --- a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/privatemocking/PrivateInstanceMockingCases.java +++ b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/privatemocking/PrivateInstanceMockingCases.java @@ -19,18 +19,18 @@ 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 samples.privateandfinal.PrivateFinal; +import samples.privatemocking.PrivateMethodDemo; + +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import static org.junit.Assert.fail; @@ -80,7 +80,7 @@ public void expectationsWorkWithArgumentMatchersWhenSpyingOnPrivateMethods() thr 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"); + when(tested, "doSayYear", anyInt(), anyString()).thenReturn("another"); assertEquals("another", tested.sayYear("Johan", 29)); assertEquals("another", tested.sayYear("test", 12)); @@ -128,7 +128,7 @@ public void errorousVerificationOnPrivateMethodGivesFilteredErrorMessage() throw 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"); + when(tested, "doSayYear", anyInt(), anyString()).thenReturn("another"); assertEquals("another", tested.sayYear("Johan", 29)); assertEquals("another", tested.sayYear("test", 12)); diff --git a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/privatemocking/PrivateInstanceMockingTest.java b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/privatemocking/PrivateInstanceMockingTest.java index 24e00e65a..badda18a6 100644 --- a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/privatemocking/PrivateInstanceMockingTest.java +++ b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/privatemocking/PrivateInstanceMockingTest.java @@ -3,6 +3,7 @@ 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) diff --git a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/proxymethod/ProxyMethodTest.java b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/proxymethod/ProxyMethodTest.java index 0eca76c5f..bbce2e2d1 100644 --- a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/proxymethod/ProxyMethodTest.java +++ b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/proxymethod/ProxyMethodTest.java @@ -20,12 +20,13 @@ 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 samples.suppressmethod.SuppressMethod; +import samples.suppressmethod.SuppressMethodExample; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import static org.mockito.Mockito.verify; diff --git a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/simplemix/SimpleMixTest.java b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/simplemix/SimpleMixTest.java index a0467a3df..e1ba8dc63 100644 --- a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/simplemix/SimpleMixTest.java +++ b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/simplemix/SimpleMixTest.java @@ -23,13 +23,21 @@ 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.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.verifyNew; +import static org.powermock.api.mockito.PowerMockito.verifyPrivate; +import static org.powermock.api.mockito.PowerMockito.verifyStatic; +import static org.powermock.api.mockito.PowerMockito.when; +import static org.powermock.api.mockito.PowerMockito.whenNew; import static org.powermock.api.support.membermodification.MemberMatcher.method; /** @@ -77,6 +85,6 @@ public void finalSystemClassMocking() throws Exception { when(System.currentTimeMillis()).thenReturn(2000L); - assertEquals(2, Whitebox.invokeMethod(tested, "getValue")); + assertEquals(2, (int) Whitebox.invokeMethod(tested, "getValue")); } } diff --git a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/spy/SpyTest.java b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/spy/SpyTest.java index cc0ec2a73..4998c8f08 100644 --- a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/spy/SpyTest.java +++ b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/spy/SpyTest.java @@ -15,12 +15,13 @@ */ package samples.powermockito.junit4.spy; -import org.assertj.core.api.Java6Assertions; +import org.assertj.core.api.Assertions; 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; @@ -55,7 +56,7 @@ public void should_stub_spying_on_private_method_works() throws Exception { @Test public void should_call_real_method_when_spy_method_is_not_stubbed() { - Java6Assertions.assertThat(partialMock.getMyString()) + Assertions.assertThat(partialMock.getMyString()) .as("Real method is called") .isEqualTo(new SpyObject().getMyString()); } diff --git a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/stacktracecleaner/LocationFromStackTraceTest.java b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/stacktracecleaner/LocationFromStackTraceTest.java index 810caed41..d0c5c5d32 100644 --- a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/stacktracecleaner/LocationFromStackTraceTest.java +++ b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/stacktracecleaner/LocationFromStackTraceTest.java @@ -1,8 +1,5 @@ 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; @@ -17,6 +14,10 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunnerDelegate; + +import java.util.ArrayList; +import java.util.List; + import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.powermock.api.mockito.PowerMockito.doNothing; @@ -45,20 +46,20 @@ public void should_filter_extra_elements_in_stack_when_mocking_static_method() t Object mock = mockHandlerAdaptor.getMock(); MockHandler mockHandler = MockUtil.getMockHandler(mock); InvocationContainerImpl invocationContainer = (InvocationContainerImpl)mockHandler.getInvocationContainer(); - List stubbings = new ArrayList(invocationContainer.getStubbingsAscending()); + 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)")); + "LocationFromStackTraceTest.java:38)")); 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)")); + "LocationFromStackTraceTest.java:39)")); 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)")); + "LocationFromStackTraceTest.java:40)")); // 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 diff --git a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/staticandinstance/StaticAndInstanceDemoTest.java b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/staticandinstance/StaticAndInstanceDemoTest.java index 0368ff929..99d04aa73 100644 --- a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/staticandinstance/StaticAndInstanceDemoTest.java +++ b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/staticandinstance/StaticAndInstanceDemoTest.java @@ -19,10 +19,14 @@ 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.*; +import static org.powermock.api.mockito.PowerMockito.spy; +import static org.powermock.api.mockito.PowerMockito.verifyPrivate; +import static org.powermock.api.mockito.PowerMockito.verifyStatic; +import static org.powermock.api.mockito.PowerMockito.when; @RunWith(PowerMockRunner.class) @PrepareForTest(StaticAndInstanceDemo.class) diff --git a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/staticmocking/MockStaticCases.java b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/staticmocking/MockStaticCases.java index 1d271d3e2..4f0c5e92c 100644 --- a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/staticmocking/MockStaticCases.java +++ b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/staticmocking/MockStaticCases.java @@ -18,17 +18,17 @@ 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.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; @@ -54,12 +54,7 @@ public void should_call_reall_static_void_method() { doCallRealMethod().when(StaticService.class); StaticService.throwException(); - assertThatThrownBy(new ThrowingCallable() { - @Override - public void call() throws Throwable { - StaticService.throwException(); - } - }).as("Real method is called") + assertThatThrownBy(StaticService::throwException).as("Real method is called") .isInstanceOf(RuntimeException.class); } diff --git a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/staticmocking/MockStaticTest.java b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/staticmocking/MockStaticTest.java index 44a5ed16e..22123ff14 100644 --- a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/staticmocking/MockStaticTest.java +++ b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/staticmocking/MockStaticTest.java @@ -18,6 +18,7 @@ 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; diff --git a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/stress/PowerMockStressTest.java b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/stress/PowerMockStressTest.java index 691b1ad57..9a9c75a3d 100644 --- a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/stress/PowerMockStressTest.java +++ b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/stress/PowerMockStressTest.java @@ -22,6 +22,7 @@ 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; diff --git a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/system/SystemClassUserTest.java b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/system/SystemClassUserTest.java index b2d4f6123..aff69227b 100644 --- a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/system/SystemClassUserTest.java +++ b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/system/SystemClassUserTest.java @@ -17,11 +17,9 @@ 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; @@ -31,11 +29,22 @@ import java.util.List; import java.util.UUID; -import static org.junit.Assert.*; -import static org.mockito.BDDMockito.given; +import samples.system.SystemClassUser; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.times; -import static org.powermock.api.mockito.PowerMockito.*; +import static org.powermock.api.mockito.PowerMockito.doNothing; +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.spy; +import static org.powermock.api.mockito.PowerMockito.verifyStatic; +import static org.powermock.api.mockito.PowerMockito.when; +import static org.powermock.api.mockito.PowerMockito.whenNew; /** * Demonstrates PowerMockito's ability to mock non-final and final system @@ -99,7 +108,7 @@ public void assertThatPartialMockingOfFinalSystemClassesWorks() throws Exception @Test public void assertThatMockingOfCollectionsWork() throws Exception { - List list = new LinkedList(); + List list = new LinkedList<>(); mockStatic(Collections.class); Collections.shuffle(list); @@ -209,10 +218,8 @@ public void mockingStringBuilder() throws Exception { @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"); - } + when(builder.length()).then((Answer) invocation -> { + throw new IllegalStateException("Can't really happen"); }); new SystemClassUser().lengthOf(builder); } diff --git a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/verify/VerifyNoMoreInteractionsTest.java b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/verify/VerifyNoMoreInteractionsTest.java index b463f86a7..8b8383875 100644 --- a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/verify/VerifyNoMoreInteractionsTest.java +++ b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/verify/VerifyNoMoreInteractionsTest.java @@ -21,12 +21,13 @@ 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 samples.singleton.StaticHelper; import samples.singleton.StaticService; -import static org.assertj.core.api.Java6Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertNull; import static org.mockito.Mockito.times; import static org.powermock.api.mockito.PowerMockito.mock; diff --git a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/verify/VerifyZeroInteractionsTest.java b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/verify/VerifyZeroInteractionsTest.java index bfb7cdd9a..b5da0be27 100644 --- a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/verify/VerifyZeroInteractionsTest.java +++ b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/verify/VerifyZeroInteractionsTest.java @@ -18,24 +18,22 @@ 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.assertThat; +import static org.assertj.core.api.Assertions.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 { @@ -46,12 +44,7 @@ public void should_throw_verification_exception_in_case_if_static_method_is_call StaticExample.staticMethodReturningString(); - assertThatThrownBy(new ThrowingCallable() { - @Override - public void call() throws Throwable { - verifyZeroInteractions(StaticExample.class); - } - }).as("Verify Exception is thrown.") + assertThatThrownBy(() -> verifyZeroInteractions(StaticExample.class)).as("Verify Exception is thrown.") .isInstanceOf(NoInteractionsWanted.class) .hasMessageContaining("No interactions"); } @@ -62,12 +55,7 @@ public void should_throw_verification_exception_in_case_if_instance_method_calle mock.getServiceMessage(); - assertThatThrownBy(new ThrowingCallable() { - @Override - public void call() throws Throwable { - verifyZeroInteractions(mock); - } - }).as("Verify Exception is thrown.") + assertThatThrownBy(() -> verifyZeroInteractions(mock)).as("Verify Exception is thrown.") .isInstanceOf(NoInteractionsWanted.class) .hasMessageContaining("No interactions"); } @@ -76,12 +64,7 @@ public void call() throws Throwable { 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); - } - }); + final Throwable throwable = catchThrowable(() -> verifyZeroInteractions(StaticExample.class)); assertThat(throwable) .as("Verify Exception is not thrown.") @@ -92,12 +75,7 @@ public void call() throws Throwable { 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); - } - }); + final Throwable throwable = catchThrowable(() -> verifyZeroInteractions(mock)); assertThat(throwable) .as("Verify Exception is not thrown.") diff --git a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/whennew/DoesntSupportCreatingMocksInFieldsWhenNewDefect.java b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/whennew/DoesntSupportCreatingMocksInFieldsWhenNewDefect.java index 62ee5b395..ecf9b6d46 100644 --- a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/whennew/DoesntSupportCreatingMocksInFieldsWhenNewDefect.java +++ b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/whennew/DoesntSupportCreatingMocksInFieldsWhenNewDefect.java @@ -20,6 +20,7 @@ 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; diff --git a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/whennew/NewFileExampleTest.java b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/whennew/NewFileExampleTest.java index 9ce7f284e..1757e3366 100644 --- a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/whennew/NewFileExampleTest.java +++ b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/whennew/NewFileExampleTest.java @@ -19,12 +19,16 @@ 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 samples.expectnew.NewFileExample; + import static org.junit.Assert.assertTrue; -import static org.powermock.api.mockito.PowerMockito.*; +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; @RunWith(PowerMockRunner.class) @PrepareForTest(NewFileExample.class) diff --git a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/whennew/VerifyNewMultipleTimesTest.java b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/whennew/VerifyNewMultipleTimesTest.java index 1ecb0dea4..296f597a7 100644 --- a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/whennew/VerifyNewMultipleTimesTest.java +++ b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/whennew/VerifyNewMultipleTimesTest.java @@ -22,14 +22,17 @@ 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 samples.expectnew.NewFileExample; + 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.*; +import static org.powermock.api.mockito.PowerMockito.verifyNew; +import static org.powermock.api.mockito.PowerMockito.when; +import static org.powermock.api.mockito.PowerMockito.whenNew; @RunWith(PowerMockRunner.class) @PrepareForTest(NewFileExample.class) diff --git a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/whennew/VerifyNewWithoutWhenNewTest.java b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/whennew/VerifyNewWithoutWhenNewTest.java index 52bf630d1..4167dd104 100644 --- a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/whennew/VerifyNewWithoutWhenNewTest.java +++ b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/whennew/VerifyNewWithoutWhenNewTest.java @@ -5,6 +5,7 @@ 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; diff --git a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/whennew/WhenNewCases.java b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/whennew/WhenNewCases.java index e44be50bd..735900366 100644 --- a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/whennew/WhenNewCases.java +++ b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/whennew/WhenNewCases.java @@ -21,9 +21,19 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.reflect.Whitebox; import org.powermock.reflect.exceptions.ConstructorNotFoundException; + +import java.io.ByteArrayInputStream; +import java.io.DataInputStream; +import java.io.IOException; +import java.io.InputStream; + import samples.Service; import samples.classwithinnermembers.ClassWithInnerMembers; -import samples.classwithinnermembers.ClassWithInnerMembers.*; +import samples.classwithinnermembers.ClassWithInnerMembers.MyInnerClassWithPackageConstructorWithMultArgs; +import samples.classwithinnermembers.ClassWithInnerMembers.MyInnerClassWithPrivateConstructorWithDiffMultArgs; +import samples.classwithinnermembers.ClassWithInnerMembers.MyInnerClassWithPrivateConstructorWithMultArgs; +import samples.classwithinnermembers.ClassWithInnerMembers.MyInnerClassWithProtectedConstructorWithMultArgs; +import samples.classwithinnermembers.ClassWithInnerMembers.MyInnerClassWithPublicConstructorWithMultArgs; import samples.expectnew.CreationException; import samples.expectnew.ExpectNewDemo; import samples.expectnew.ExpectNewServiceUser; @@ -35,12 +45,7 @@ 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.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; @@ -51,7 +56,11 @@ 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.mockito.PowerMockito.doReturn; +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; /** @@ -626,12 +635,7 @@ public void testNewWithVarArgsConstructorWhenOneArgumentIsOfASubType() throws Ex Service serviceMock = mock(Service.class); VarArgsConstructorDemo varArgsConstructorDemoMock = mock(VarArgsConstructorDemo.class); - final Service serviceSubTypeInstance = new Service() { - - public String getServiceMessage() { - return "message"; - } - }; + final Service serviceSubTypeInstance = () -> "message"; whenNew(VarArgsConstructorDemo.class).withArguments(serviceSubTypeInstance, serviceMock).thenReturn( varArgsConstructorDemoMock); diff --git a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/withsettings/WithSettingsTest.java b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/withsettings/WithSettingsTest.java index 36bc83a8f..5f407846c 100644 --- a/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/withsettings/WithSettingsTest.java +++ b/tests/mockito/junit4/src/test/java/samples/powermockito/junit4/withsettings/WithSettingsTest.java @@ -19,6 +19,7 @@ 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; diff --git a/tests/mockito/junit49/src/test/java/samples/powermockito/junit4/rules/JUnit49RuleTest.java b/tests/mockito/junit49/src/test/java/samples/powermockito/junit4/rules/JUnit49RuleTest.java index 943ee47aa..b9589b67e 100644 --- a/tests/mockito/junit49/src/test/java/samples/powermockito/junit4/rules/JUnit49RuleTest.java +++ b/tests/mockito/junit49/src/test/java/samples/powermockito/junit4/rules/JUnit49RuleTest.java @@ -15,9 +15,6 @@ */ 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; @@ -31,6 +28,9 @@ import java.util.LinkedList; import java.util.List; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; + /** * JUnit 4.9 changed the implementation/execution of Rules. * Demonstrates that objects = new LinkedList(); + private List objects = new LinkedList<>(); @Rule public MyRule rule = new MyRule(); diff --git a/tests/mockito/testng/src/test/java/samples/powermockito/testng/staticmocking/MockStaticNotPreparedTest.java b/tests/mockito/testng/src/test/java/samples/powermockito/testng/staticmocking/MockStaticNotPreparedTest.java index ecad7dba0..49e2887a6 100644 --- a/tests/mockito/testng/src/test/java/samples/powermockito/testng/staticmocking/MockStaticNotPreparedTest.java +++ b/tests/mockito/testng/src/test/java/samples/powermockito/testng/staticmocking/MockStaticNotPreparedTest.java @@ -3,6 +3,7 @@ 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; diff --git a/tests/mockito/testng/src/test/java/samples/powermockito/testng/staticmocking/MockStaticPreparedWithoutMockStaticTest.java b/tests/mockito/testng/src/test/java/samples/powermockito/testng/staticmocking/MockStaticPreparedWithoutMockStaticTest.java index 71d81a33a..efb256dbb 100644 --- a/tests/mockito/testng/src/test/java/samples/powermockito/testng/staticmocking/MockStaticPreparedWithoutMockStaticTest.java +++ b/tests/mockito/testng/src/test/java/samples/powermockito/testng/staticmocking/MockStaticPreparedWithoutMockStaticTest.java @@ -4,6 +4,7 @@ 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; diff --git a/tests/mockito/testng/src/test/java/samples/powermockito/testng/staticmocking/MockitoMockStaticTest.java b/tests/mockito/testng/src/test/java/samples/powermockito/testng/staticmocking/MockitoMockStaticTest.java index c772ea4ae..e93d9b8e6 100644 --- a/tests/mockito/testng/src/test/java/samples/powermockito/testng/staticmocking/MockitoMockStaticTest.java +++ b/tests/mockito/testng/src/test/java/samples/powermockito/testng/staticmocking/MockitoMockStaticTest.java @@ -21,6 +21,7 @@ import org.testng.IObjectFactory; import org.testng.annotations.ObjectFactory; import org.testng.annotations.Test; + import samples.singleton.StaticHelper; import samples.singleton.StaticService; diff --git a/tests/testng/src/test/java/samples/testng/bugs/github647/GitHub647.java b/tests/testng/src/test/java/samples/testng/bugs/github647/GitHub647.java index cc267f73b..862355bae 100644 --- a/tests/testng/src/test/java/samples/testng/bugs/github647/GitHub647.java +++ b/tests/testng/src/test/java/samples/testng/bugs/github647/GitHub647.java @@ -5,11 +5,12 @@ 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 samples.testng.SimpleBaseTest; + import static org.testng.Assert.assertEquals; public class GitHub647 extends SimpleBaseTest { diff --git a/tests/utils/src/main/java/samples/Service.java b/tests/utils/src/main/java/samples/Service.java index 54a7b5eee..e32265466 100644 --- a/tests/utils/src/main/java/samples/Service.java +++ b/tests/utils/src/main/java/samples/Service.java @@ -23,5 +23,5 @@ */ public interface Service { - public String getServiceMessage(); + String getServiceMessage(); } diff --git a/tests/utils/src/main/java/samples/equalswithgetclass/EqualsWithGetClass.java b/tests/utils/src/main/java/samples/equalswithgetclass/EqualsWithGetClass.java index 42df35c6b..d4b715dc1 100644 --- a/tests/utils/src/main/java/samples/equalswithgetclass/EqualsWithGetClass.java +++ b/tests/utils/src/main/java/samples/equalswithgetclass/EqualsWithGetClass.java @@ -45,10 +45,8 @@ public boolean equals(Object obj) { 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; + return other.myString == null; + } else + return myString.equals(other.myString); } } diff --git a/tests/utils/src/main/java/samples/expectnew/ExpectNewDemo.java b/tests/utils/src/main/java/samples/expectnew/ExpectNewDemo.java index e8da872e8..b821f90eb 100644 --- a/tests/utils/src/main/java/samples/expectnew/ExpectNewDemo.java +++ b/tests/utils/src/main/java/samples/expectnew/ExpectNewDemo.java @@ -15,153 +15,157 @@ */ package samples.expectnew; +import java.io.ByteArrayInputStream; +import java.io.DataInputStream; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStream; +import java.io.PrintWriter; +import java.util.Date; + 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(); - } + 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; + return dummyField == other.dummyField; + } + + 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(); - } + return new VarArgsConstructorDemo(myFloat, ints).getInts(); + } - public byte[][] newVarArgs(byte[]... bytes) { - return new VarArgsConstructorDemo(bytes).getByteArrays(); - } + public byte[][] newVarArgs(byte[]... bytes) { + return new VarArgsConstructorDemo(bytes).getByteArrays(); + } - public byte[][] newVarArgsWithMatchers() { - return new VarArgsConstructorDemo(new byte[] { 42 }, new byte[] { 17 }).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 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 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 byte[][] newSimpleVarArgs(byte[]... bytes) { + return new SimpleVarArgsConstructorDemo(bytes).getByteArrays(); + } public Target createTarget(ITarget target) { Target domainTarget; diff --git a/tests/utils/src/main/java/samples/fieldmock/FieldInitializerDemo.java b/tests/utils/src/main/java/samples/fieldmock/FieldInitializerDemo.java index 70e295966..3b5e5c725 100644 --- a/tests/utils/src/main/java/samples/fieldmock/FieldInitializerDemo.java +++ b/tests/utils/src/main/java/samples/fieldmock/FieldInitializerDemo.java @@ -20,13 +20,13 @@ public class FieldInitializerDemo { - private Map map = new HashMap(); + private Map map = new HashMap<>(); - private static Map staticMap = new HashMap(); + private static Map staticMap = new HashMap<>(); private static Map staticMap2; static { - staticMap2 = new HashMap(); + staticMap2 = new HashMap<>(); System.out.println("### Static println!"); } diff --git a/tests/utils/src/main/java/samples/hashcode/HashCodeInitializedInCtor.java b/tests/utils/src/main/java/samples/hashcode/HashCodeInitializedInCtor.java index 4670c4eee..2357c4d7a 100644 --- a/tests/utils/src/main/java/samples/hashcode/HashCodeInitializedInCtor.java +++ b/tests/utils/src/main/java/samples/hashcode/HashCodeInitializedInCtor.java @@ -21,12 +21,11 @@ public class HashCodeInitializedInCtor { private final HashMap hash; public HashCodeInitializedInCtor() { - hash = new HashMap(); + hash = new HashMap<>(); } public static HashCodeInitializedInCtor newFaults() { - HashCodeInitializedInCtor fault = new HashCodeInitializedInCtor(); - return fault; + return new HashCodeInitializedInCtor(); } @Override diff --git a/tests/utils/src/main/java/samples/interfacefieldchange/InterfaceWithStaticFinalField.java b/tests/utils/src/main/java/samples/interfacefieldchange/InterfaceWithStaticFinalField.java index e38bafaca..f49c63b0b 100644 --- a/tests/utils/src/main/java/samples/interfacefieldchange/InterfaceWithStaticFinalField.java +++ b/tests/utils/src/main/java/samples/interfacefieldchange/InterfaceWithStaticFinalField.java @@ -23,5 +23,5 @@ * must be final in interfaces according to the specification). */ public interface InterfaceWithStaticFinalField { - static final String MY_STRING = "My value"; + String MY_STRING = "My value"; } diff --git a/tests/utils/src/main/java/samples/interfacemethodfinding/InterfaceMethodHierarchyUsage.java b/tests/utils/src/main/java/samples/interfacemethodfinding/InterfaceMethodHierarchyUsage.java index 071cf24c7..bcb94eedd 100644 --- a/tests/utils/src/main/java/samples/interfacemethodfinding/InterfaceMethodHierarchyUsage.java +++ b/tests/utils/src/main/java/samples/interfacemethodfinding/InterfaceMethodHierarchyUsage.java @@ -34,20 +34,15 @@ */ 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(); - } - } + @SuppressWarnings("checkstyle:EmptyBlock") + public void usePreparedStatement() { + // PreparedStatement extends other interfaces, this is the point of + // interest. + try (Connection conn = WsUtil.getConnection(); PreparedStatement prepared = conn.prepareStatement( + "select * from emp")) { + } + catch (Exception e) { + System.out.println(e); + } + } } diff --git a/tests/utils/src/main/java/samples/interfacemethodfinding/WsUtil.java b/tests/utils/src/main/java/samples/interfacemethodfinding/WsUtil.java index c4c7fea69..2ebe172c0 100644 --- a/tests/utils/src/main/java/samples/interfacemethodfinding/WsUtil.java +++ b/tests/utils/src/main/java/samples/interfacemethodfinding/WsUtil.java @@ -25,8 +25,6 @@ public class WsUtil { public static Connection getConnection() throws Exception { - Connection conn = null; - - return conn; + return null; } } diff --git a/tests/utils/src/main/java/samples/partialmocking/MockSelfDemo.java b/tests/utils/src/main/java/samples/partialmocking/MockSelfDemo.java index 44e54db74..3e022065b 100644 --- a/tests/utils/src/main/java/samples/partialmocking/MockSelfDemo.java +++ b/tests/utils/src/main/java/samples/partialmocking/MockSelfDemo.java @@ -59,9 +59,7 @@ public boolean equals(Object obj) { if (getClass() != obj.getClass()) return false; final MockSelfDemo other = (MockSelfDemo) obj; - if (hello != other.hello) - return false; - return true; + return hello == other.hello; } public String aMethod() { diff --git a/tests/utils/src/main/java/samples/privatefield/MockSelfPrivateFieldServiceClass.java b/tests/utils/src/main/java/samples/privatefield/MockSelfPrivateFieldServiceClass.java index f05bb4f9f..e8cb2fd41 100644 --- a/tests/utils/src/main/java/samples/privatefield/MockSelfPrivateFieldServiceClass.java +++ b/tests/utils/src/main/java/samples/privatefield/MockSelfPrivateFieldServiceClass.java @@ -27,8 +27,7 @@ public class MockSelfPrivateFieldServiceClass { private Service service; public String getCompositeMessage() { - final String message = getOwnMessage() + service.getServiceMessage(); - return message; + return getOwnMessage() + service.getServiceMessage(); } private String getOwnMessage() { diff --git a/tests/utils/src/main/java/samples/servletmocking/SampleServlet.java b/tests/utils/src/main/java/samples/servletmocking/SampleServlet.java index 1ed68b760..df9e4f755 100644 --- a/tests/utils/src/main/java/samples/servletmocking/SampleServlet.java +++ b/tests/utils/src/main/java/samples/servletmocking/SampleServlet.java @@ -16,17 +16,18 @@ package samples.servletmocking; +import java.io.IOException; 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 { + @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().write("out"); } diff --git a/tests/utils/src/main/java/samples/singleton/StaticService.java b/tests/utils/src/main/java/samples/singleton/StaticService.java index 1da25edc1..3e67d6fcf 100644 --- a/tests/utils/src/main/java/samples/singleton/StaticService.java +++ b/tests/utils/src/main/java/samples/singleton/StaticService.java @@ -67,7 +67,7 @@ public static String doStatic(int i) { } public static void assertThatVerifyWorksForMultipleMocks() { - StaticService.sayHello(); + sayHello(); StaticHelper.sayHelloHelper(); } diff --git a/tests/utils/src/main/java/samples/staticandinstance/StaticAndInstanceDemo.java b/tests/utils/src/main/java/samples/staticandinstance/StaticAndInstanceDemo.java index 7c7493d2b..aa1a64c57 100644 --- a/tests/utils/src/main/java/samples/staticandinstance/StaticAndInstanceDemo.java +++ b/tests/utils/src/main/java/samples/staticandinstance/StaticAndInstanceDemo.java @@ -23,7 +23,7 @@ public class StaticAndInstanceDemo { public String getMessage() { - return getPrivateMessage() + StaticAndInstanceDemo.getStaticMessage(); + return getPrivateMessage() + getStaticMessage(); } private String getPrivateMessage() { diff --git a/tests/utils/src/main/java/samples/staticinitializer/InterfaceComputation.java b/tests/utils/src/main/java/samples/staticinitializer/InterfaceComputation.java index 53fc74baf..d4dc7d971 100644 --- a/tests/utils/src/main/java/samples/staticinitializer/InterfaceComputation.java +++ b/tests/utils/src/main/java/samples/staticinitializer/InterfaceComputation.java @@ -17,17 +17,17 @@ interface InterfaceA { - public static final int A = 2 * InterfaceB.B; + int A = 2 * InterfaceB.B; // public void methodA(); } // End of interface interface InterfaceB { - public static final int B = InterfaceC.C + 1; + int B = InterfaceC.C + 1; // public String methodB(int qwe); } // End of interface interface InterfaceC extends InterfaceA { - public static final int C = A + 1; + int C = A + 1; } // End of interface public class InterfaceComputation implements InterfaceA, InterfaceB, InterfaceC diff --git a/tests/utils/src/main/java/samples/staticinitializer/StaticInitializerExample.java b/tests/utils/src/main/java/samples/staticinitializer/StaticInitializerExample.java index f6a7f2f1c..87f6408ba 100644 --- a/tests/utils/src/main/java/samples/staticinitializer/StaticInitializerExample.java +++ b/tests/utils/src/main/java/samples/staticinitializer/StaticInitializerExample.java @@ -23,7 +23,7 @@ public class StaticInitializerExample { private static final Set mySet; static { - mySet = new HashSet(); + mySet = new HashSet<>(); if (true) { throw new RuntimeException("This code must be suppressed!"); } diff --git a/tests/utils/src/main/java/samples/suppressconstructor/AppaleList.java b/tests/utils/src/main/java/samples/suppressconstructor/AppaleList.java index a27a6443b..4f1ae288d 100644 --- a/tests/utils/src/main/java/samples/suppressconstructor/AppaleList.java +++ b/tests/utils/src/main/java/samples/suppressconstructor/AppaleList.java @@ -30,9 +30,9 @@ public AppaleList(String str) { } public String getAll() { - List list = new ArrayList(); + List list = new ArrayList<>(); list.add("sb1"); - List list1 = new ArrayList(10); + List list1 = new ArrayList<>(10); list1.add("sb2"); list1.add("sb3"); list1.add("sb4"); diff --git a/tests/utils/src/main/java/samples/suppressfield/ItemRepository.java b/tests/utils/src/main/java/samples/suppressfield/ItemRepository.java index f3474f669..e0e63b700 100644 --- a/tests/utils/src/main/java/samples/suppressfield/ItemRepository.java +++ b/tests/utils/src/main/java/samples/suppressfield/ItemRepository.java @@ -3,7 +3,7 @@ import java.util.HashMap; public class ItemRepository { - private static HashMap itemMap = new HashMap(); + private static HashMap itemMap = new HashMap<>(); @SuppressWarnings("unused") private MyClass myClass = new MyClass(); diff --git a/tests/utils/src/main/java/samples/swing/SimpleSwingDemo.java b/tests/utils/src/main/java/samples/swing/SimpleSwingDemo.java index a073b1d34..ac68bfc1a 100644 --- a/tests/utils/src/main/java/samples/swing/SimpleSwingDemo.java +++ b/tests/utils/src/main/java/samples/swing/SimpleSwingDemo.java @@ -15,10 +15,10 @@ */ package samples.swing; -import javax.swing.*; -import java.awt.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; +import java.awt.FlowLayout; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JLabel; /** * A basic swing application example. @@ -27,30 +27,26 @@ */ public class SimpleSwingDemo extends JFrame { - private static final long serialVersionUID = -190175253588111657L; + private static final long serialVersionUID = -190175253588111657L; - public SimpleSwingDemo() { - initialize(); - } + public SimpleSwingDemo() { + initialize(); + } - private void initialize() { - setLayout(new FlowLayout()); - final JLabel jlbHelloWorld = new JLabel("Hello World!"); - JButton jButton = new JButton("Click Me!"); + 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"); - } - }); + jButton.addActionListener(actionevent -> jlbHelloWorld.setText("Clicked on button")); - add(jlbHelloWorld); - add(jButton); - setSize(100, 100); - setVisible(true); - } + add(jlbHelloWorld); + add(jButton); + setSize(100, 100); + setVisible(true); + } - public static void main(String[] args) { - new SimpleSwingDemo(); - } + public static void main(String[] args) { + new SimpleSwingDemo(); + } } diff --git a/tests/utils/src/main/java/samples/system/SystemClassUser.java b/tests/utils/src/main/java/samples/system/SystemClassUser.java index 69291ca84..1682cfcec 100644 --- a/tests/utils/src/main/java/samples/system/SystemClassUser.java +++ b/tests/utils/src/main/java/samples/system/SystemClassUser.java @@ -17,7 +17,11 @@ import java.io.IOException; import java.io.UnsupportedEncodingException; -import java.net.*; +import java.net.InetAddress; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLConnection; +import java.net.URLEncoder; import java.util.Collections; import java.util.List; import java.util.UUID; @@ -78,8 +82,7 @@ public InetAddress getLocalHost() throws IOException { public String generatePerishableToken() { final UUID uuid = UUID.randomUUID(); final String toString = uuid.toString(); - final String result = toString.replaceAll("-", ""); - return result; + return toString.replaceAll("-", ""); } public int lengthOf(StringBuilder to){