From a3d88ea27c35921647d7602755828ca73e15e865 Mon Sep 17 00:00:00 2001 From: Klaudio Sinani Date: Wed, 17 Nov 2021 22:54:06 +0100 Subject: SONAR-15631 - Refactor UTs to stop using ExpectedException --- .../client/bitbucketserver/BranchesListTest.java | 4 +- .../github/config/GithubAppConfigurationTest.java | 24 +- .../alm/client/github/security/AppTokenTest.java | 1 - .../github/security/GithubAppSecurityImplTest.java | 2 - .../bitbucket/BitbucketIdentityProviderTest.java | 11 +- .../java/org/sonar/auth/OAuthRestClientTest.java | 20 +- .../auth/github/GitHubIdentityProviderTest.java | 11 +- .../auth/github/UserIdentityFactoryImplTest.java | 4 - .../auth/gitlab/GitLabIdentityProviderTest.java | 2 - .../org/sonar/auth/gitlab/GitLabSettingsTest.java | 4 - .../sonar/auth/ldap/CallbackHandlerImplTest.java | 10 +- .../org/sonar/auth/ldap/ContextHelperTest.java | 6 +- .../java/org/sonar/auth/ldap/LdapSearchTest.java | 14 +- .../sonar/auth/ldap/LdapSettingsManagerTest.java | 34 +-- .../java/org/sonar/auth/saml/SamlSettingsTest.java | 40 ++- .../java/org/sonar/ce/queue/CeQueueImplTest.java | 12 +- .../projectanalysis/analysis/AnalysisImplTest.java | 23 +- .../analysis/AnalysisMetadataHolderImplTest.java | 153 +++++------ .../api/measurecomputer/ComponentImplTest.java | 45 ++-- .../MeasureComputerContextImplTest.java | 51 ++-- .../MeasureComputerDefinitionImplTest.java | 83 +++--- .../api/measurecomputer/MeasureImplTest.java | 81 +++--- .../api/posttask/CeTaskImplTest.java | 20 +- .../api/posttask/ConditionImplTest.java | 54 ++-- .../api/posttask/ConditionToConditionTest.java | 24 +- .../api/posttask/ProjectImplTest.java | 26 +- .../api/posttask/QualityGateImplTest.java | 33 +-- .../batch/BatchReportDirectoryHolderImplTest.java | 6 +- .../batch/BatchReportReaderImplTest.java | 11 +- .../component/BranchLoaderTest.java | 11 +- .../component/ComponentImplTest.java | 52 ++-- .../component/ComponentTreeBuilderTest.java | 25 +- .../component/CrawlerDepthLimitTest.java | 19 +- .../component/DefaultBranchImplTest.java | 4 - .../DisabledComponentsHolderImplTest.java | 17 +- .../component/FileAttributesTest.java | 17 +- .../component/ProjectPersisterTest.java | 4 - ...ostOrderDepthTraversalTypeAwareCrawlerTest.java | 6 +- ...PreOrderDepthTraversalTypeAwareCrawlerTest.java | 6 +- .../component/ReportVisitorsCrawlerTest.java | 31 ++- ...rsCrawlerWithPostOrderTypeAwareVisitorTest.java | 7 +- ...orsCrawlerWithPreOrderTypeAwareVisitorTest.java | 8 +- .../component/TreeRootHolderImplTest.java | 65 ++--- .../component/TypeAwareVisitorAdapterTest.java | 10 +- .../component/ViewAttributesTest.java | 12 +- ...ostOrderDepthTraversalTypeAwareCrawlerTest.java | 6 +- ...PreOrderDepthTraversalTypeAwareCrawlerTest.java | 6 +- .../component/ViewsVisitorsCrawlerTest.java | 37 ++- ...rsCrawlerWithPostOrderTypeAwareVisitorTest.java | 7 +- ...orsCrawlerWithPreOrderTypeAwareVisitorTest.java | 7 +- .../duplication/CrossProjectDuplicateTest.java | 20 +- ...rossProjectDuplicationStatusHolderImplTest.java | 11 +- .../duplication/DuplicationRepositoryImplTest.java | 56 ++--- .../duplication/DuplicationTest.java | 47 ++-- .../duplication/InProjectDuplicateTest.java | 26 +- .../duplication/InnerDuplicateTest.java | 12 +- .../projectanalysis/duplication/TextBlockTest.java | 19 +- .../event/EventRepositoryImplTest.java | 11 +- .../ce/task/projectanalysis/event/EventTest.java | 11 +- .../filemove/AddedFileRepositoryImplTest.java | 33 +-- .../MutableMovedFilesRepositoryImplTest.java | 36 ++- .../filemove/SourceSimilarityImplTest.java | 4 - .../formula/AverageFormulaTest.java | 75 +++--- .../formula/DistributionFormulaTest.java | 12 +- .../projectanalysis/formula/IntSumFormulaTest.java | 12 +- .../formula/LongSumFormulaTest.java | 12 +- .../ReportFormulaExecutorComponentVisitorTest.java | 26 +- .../formula/coverage/CoverageUtilsTest.java | 16 +- .../issue/ComponentIssuesLoaderTest.java | 3 - .../issue/ComponentIssuesRepositoryImplTest.java | 38 ++- .../issue/ComponentsWithUnprocessedIssuesTest.java | 37 ++- .../projectanalysis/issue/DebtCalculatorTest.java | 6 +- .../issue/IssueCreationDateCalculatorTest.java | 10 +- .../issue/MovedIssueVisitorTest.java | 22 +- .../projectanalysis/issue/NewAdHocRuleTest.java | 11 +- .../issue/RuleRepositoryImplTest.java | 44 ++-- .../issue/commonrule/CommentDensityRuleTest.java | 16 +- .../issue/commonrule/CommonRuleTest.java | 38 +-- .../issue/filter/IssueFilterTest.java | 20 +- .../language/LanguageRepositoryImplTest.java | 6 +- .../measure/BatchMeasureToMeasureTest.java | 11 +- .../measure/LiveMeasureDtoToMeasureTest.java | 15 +- .../measure/MapBasedRawMeasureRepositoryTest.java | 44 ++-- .../measure/MeasureComputersHolderImplTest.java | 25 +- .../measure/MeasureDtoToMeasureTest.java | 21 +- .../measure/MeasureRepositoryImplTest.java | 40 ++- .../task/projectanalysis/measure/MeasureTest.java | 86 ++++--- .../measure/MeasureToMeasureDtoTest.java | 11 +- .../PostMeasuresComputationChecksStepTest.java | 3 - .../measure/QualityGateStatusTest.java | 11 +- .../qualitygatedetails/EvaluatedConditionTest.java | 11 +- .../QualityGateDetailsDataTest.java | 12 +- .../metric/MetricDtoToMetricTest.java | 11 +- .../projectanalysis/metric/MetricImplTest.java | 27 +- .../metric/MetricRepositoryImplTest.java | 76 +++--- .../notification/NotificationFactoryTest.java | 135 +++++----- .../period/PeriodHolderImplTest.java | 30 +-- .../ce/task/projectanalysis/period/PeriodTest.java | 4 - .../qualitygate/ConditionEvaluatorTest.java | 28 +-- .../qualitygate/ConditionStatusTest.java | 26 +- .../projectanalysis/qualitygate/ConditionTest.java | 22 +- .../qualitygate/EvaluationResultTest.java | 6 +- .../EvaluationResultTextConverterTest.java | 11 +- .../qualitygate/QualityGateHolderImplTest.java | 47 ++-- .../qualitygate/QualityGateServiceImplTest.java | 6 +- .../QualityGateStatusHolderImplTest.java | 42 ++-- .../qualitymodel/RatingSettingsTest.java | 22 +- .../qualityprofile/ActiveRulesHolderImplTest.java | 37 ++- .../QProfileStatusRepositoryImplTest.java | 25 +- .../ce/task/projectanalysis/scm/ChangesetTest.java | 27 +- .../ce/task/projectanalysis/scm/DbScmInfoTest.java | 4 - .../projectanalysis/scm/ReportScmInfoTest.java | 63 +++-- .../task/projectanalysis/scm/ScmInfoImplTest.java | 34 ++- .../scm/ScmInfoRepositoryImplTest.java | 11 +- .../source/DbLineHashVersionTest.java | 1 - .../source/FileSourceDataWarningsTest.java | 33 +-- .../source/PersistFileSourcesStepTest.java | 3 - .../source/RangeOffsetConverterTest.java | 29 +-- .../projectanalysis/source/ReportIteratorTest.java | 10 +- .../source/SignificantCodeRepositoryTest.java | 3 - .../source/SourceHashRepositoryImplTest.java | 25 +- .../source/SourceLinesHashCacheTest.java | 10 +- .../source/SourceLinesRepositoryImplTest.java | 47 ++-- .../step/BuildComponentTreeStepTest.java | 6 +- .../step/ComputeQProfileMeasureStepTest.java | 3 - .../step/ExtractReportStepTest.java | 11 +- ...CrossProjectDuplicationsRepositoryStepTest.java | 3 - .../step/LoadDuplicationsFromReportStepTest.java | 21 +- .../step/LoadMeasureComputersStepTest.java | 131 +++++----- .../projectanalysis/step/LoadPeriodsStepTest.java | 41 ++- .../step/LoadQualityGateStepTest.java | 3 - .../LoadReportAnalysisMetadataHolderStepTest.java | 33 +-- .../step/PersistAdHocRulesStepTest.java | 1 - .../step/PersistComponentsStepTest.java | 29 +-- .../step/PersistIssuesStepTest.java | 1 - .../step/PersistProjectLinksStepTest.java | 11 +- .../step/QualityGateMeasuresStepTest.java | 13 +- .../step/RegisterQualityProfileStatusStepTest.java | 1 - .../step/ReportComputationStepsTest.java | 51 ++-- .../step/SendIssueNotificationsStepTest.java | 2 +- .../UpdateQualityProfilesLastUsedDateStepTest.java | 8 +- .../step/ViewsPersistAnalysisStepTest.java | 2 - .../taskprocessor/AuditPurgeTaskProcessorTest.java | 7 +- .../taskprocessor/IndexIssuesStepTest.java | 11 +- .../taskprocessor/IssueSyncTaskProcessorTest.java | 2 +- .../util/cache/MemoryCacheTest.java | 12 +- .../ProjectExportComputationStepsTest.java | 39 ++- .../analysis/ExportAnalysesStepTest.java | 10 +- .../branches/ExportBranchesStepTest.java | 10 +- .../component/ComponentRepositoryImplTest.java | 47 ++-- .../component/ExportComponentsStepTest.java | 10 +- .../file/ExportLineHashesStepTest.java | 3 - .../projectexport/issue/ExportIssuesStepTest.java | 42 ++-- .../rule/ExportAdHocRulesStepTest.java | 10 +- .../projectexport/rule/ExportRuleStepTest.java | 11 +- .../projectexport/rule/RuleRepositoryImplTest.java | 35 ++- .../sonar/ce/task/projectexport/rule/RuleTest.java | 18 +- .../task/projectexport/steps/DumpElementTest.java | 13 +- .../projectexport/steps/DumpWriterImplTest.java | 22 +- .../projectexport/steps/ExportEventsStepTest.java | 10 +- .../projectexport/steps/ExportLinksStepTest.java | 10 +- .../steps/ExportLiveMeasuresStepTest.java | 3 - .../steps/ExportMeasuresStepTest.java | 3 - .../projectexport/steps/ExportMetricsStepTest.java | 12 +- .../steps/ExportNewCodePeriodsStepTest.java | 10 +- .../steps/ExportSettingsStepTest.java | 10 +- .../projectexport/steps/LoadProjectStepTest.java | 16 +- .../java/org/sonar/ce/task/util/Files2Test.java | 77 +++--- .../java/org/sonar/ce/task/util/Protobuf2Test.java | 29 +-- .../org/sonar/ce/task/CeTaskComponentTest.java | 12 +- .../test/java/org/sonar/ce/task/CeTaskTest.java | 12 +- .../ce/task/container/TaskContainerImplTest.java | 11 +- .../org/sonar/ce/task/log/CeTaskLoggingTest.java | 4 - .../sonar/ce/task/log/CeTaskMessagesImplTest.java | 26 +- .../ce/task/step/ComputationStepExecutorTest.java | 39 ++- .../ExecuteStatelessInitExtensionsStepTest.java | 4 - .../MutableTaskResultHolderImplTest.java | 26 +- .../main/java/org/sonar/ce/ComputeEngineImpl.java | 2 - .../java/org/sonar/ce/ComputeEngineImplTest.java | 50 ++-- .../ce/StandaloneCeDistributedInformationTest.java | 12 +- .../test/java/org/sonar/ce/app/CeServerTest.java | 30 +-- .../ce/async/SynchronousAsyncExecutionTest.java | 10 +- .../ce/configuration/CeConfigurationImplTest.java | 32 +-- .../java/org/sonar/ce/httpd/CeHttpServerTest.java | 9 +- .../org/sonar/ce/logging/CeProcessLoggingTest.java | 39 ++- .../ce/monitoring/CommonCEQueueStatusImplTest.java | 21 +- ...isFailureNotificationExecutionListenerTest.java | 18 +- .../ce/platform/DatabaseCompatibilityTest.java | 12 +- .../sonar/ce/queue/InternalCeQueueImplTest.java | 37 ++- .../ce/systeminfo/SystemInfoHttpActionTest.java | 6 - .../CeTaskInterrupterProviderTest.java | 26 +- ...TaskInterrupterWorkerExecutionListenerTest.java | 2 - .../taskprocessor/CeTaskProcessorModuleTest.java | 2 - .../CeTaskProcessorRepositoryImplTest.java | 45 ++-- .../sonar/ce/taskprocessor/CeWorkerImplTest.java | 11 +- .../taskprocessor/SimpleCeTaskInterrupterTest.java | 12 +- .../TimeoutCeTaskInterrupterTest.java | 66 +++-- .../test/java/org/sonar/db/DatabaseUtilsTest.java | 25 +- .../java/org/sonar/db/DefaultDatabaseTest.java | 13 +- .../org/sonar/db/dialect/DialectUtilsTest.java | 6 +- .../test/java/org/sonar/db/dialect/MsSqlTest.java | 16 +- .../java/org/sonar/db/dialect/PostgreSqlTest.java | 29 +-- .../sonar/db/profiling/InvocationUtilsTest.java | 1 - .../src/test/java/org/sonar/db/DaoModuleTest.java | 1 - .../src/test/java/org/sonar/db/DaoUtilsTest.java | 2 - .../test/java/org/sonar/db/IsAliveMapperTest.java | 2 - .../src/test/java/org/sonar/db/PaginationTest.java | 35 +-- .../ProjectAlmSettingDaoWithPersisterTest.java | 2 - .../java/org/sonar/db/ce/CeActivityDtoTest.java | 26 +- .../test/java/org/sonar/db/ce/CeQueueDtoTest.java | 41 ++- .../org/sonar/db/ce/CeScannerContextDaoTest.java | 25 +- .../sonar/db/ce/CeTaskCharacteristicDaoTest.java | 5 - .../sonar/db/ce/CeTaskCharacteristicDtoTest.java | 4 +- .../java/org/sonar/db/ce/CeTaskInputDaoTest.java | 10 +- .../java/org/sonar/db/ce/CeTaskMessageDaoTest.java | 3 - .../java/org/sonar/db/ce/CeTaskMessageDtoTest.java | 25 +- .../sonar/db/ce/LogsIteratorInputStreamTest.java | 19 +- .../test/java/org/sonar/db/ce/UpdateIfTest.java | 28 +-- .../db/component/AnalysisPropertiesDaoTest.java | 32 +-- .../db/component/AnalysisPropertyDtoTest.java | 33 +-- .../db/component/ComponentKeyUpdaterDaoTest.java | 24 +- .../org/sonar/db/component/ComponentQueryTest.java | 19 +- .../sonar/db/component/ComponentTreeQueryTest.java | 25 +- .../sonar/db/component/ComponentValidatorTest.java | 30 +-- .../org/sonar/db/component/ProjectLinkDaoTest.java | 2 +- .../org/sonar/db/component/SnapshotDaoTest.java | 3 - .../org/sonar/db/component/SnapshotDtoTest.java | 27 +- .../test/java/org/sonar/db/createdb/CreateDb.java | 2 +- .../db/event/EventComponentChangeDaoTest.java | 3 - .../test/java/org/sonar/db/event/EventDaoTest.java | 3 - .../org/sonar/db/event/EventValidatorTest.java | 26 +- .../test/java/org/sonar/db/issue/IssueDaoTest.java | 17 +- .../test/java/org/sonar/db/issue/IssueDtoTest.java | 22 +- .../sonar/db/mapping/ProjectMappingsDaoTest.java | 58 ++--- .../java/org/sonar/db/measure/MeasureDaoTest.java | 3 - .../org/sonar/db/measure/MeasureTreeQueryTest.java | 13 +- .../org/sonar/db/measure/PastMeasureDtoTest.java | 6 +- .../ProjectMeasuresIndexerIteratorTest.java | 3 - .../java/org/sonar/db/metric/MetricDaoTest.java | 9 +- .../java/org/sonar/db/metric/MetricDtoTest.java | 33 +-- .../db/newcodeperiod/NewCodePeriodDtoTest.java | 4 - .../sonar/db/permission/PermissionQueryTest.java | 18 +- .../PermissionTemplateCharacteristicDtoTest.java | 14 +- .../template/PermissionTemplateDaoTest.java | 3 - .../java/org/sonar/db/plugin/PluginDaoTest.java | 3 - .../db/plugin/PluginDaoWithPersisterTest.java | 3 - .../InternalComponentPropertiesDaoTest.java | 3 - .../property/InternalComponentPropertyDtoTest.java | 26 +- .../db/property/InternalPropertiesDaoTest.java | 75 ++---- .../org/sonar/db/property/PropertiesDaoTest.java | 12 +- .../property/PropertiesDaoWithPersisterTest.java | 3 - .../test/java/org/sonar/db/purge/PurgeDaoTest.java | 3 - .../org/sonar/db/purge/PurgeDaoWithAuditTest.java | 1 - .../sonar/db/purge/PurgeableAnalysisDtoTest.java | 10 +- .../sonar/db/qualityprofile/ActiveRuleDaoTest.java | 85 +++---- .../db/qualityprofile/QProfileChangeDaoTest.java | 11 +- .../qualityprofile/QProfileEditUsersDaoTest.java | 20 +- .../test/java/org/sonar/db/rule/RuleDaoTest.java | 31 ++- .../test/java/org/sonar/db/rule/RuleDtoTest.java | 30 +-- .../org/sonar/db/rule/RuleRepositoryDaoTest.java | 15 +- .../db/schemamigration/SchemaMigrationDaoTest.java | 18 +- .../org/sonar/db/source/FileSourceDtoTest.java | 12 +- .../org/sonar/db/source/LineHashVersionTest.java | 17 +- .../sonar/db/user/GroupMembershipQueryTest.java | 18 +- .../test/java/org/sonar/db/user/RoleDaoTest.java | 20 +- .../test/java/org/sonar/db/user/UserDtoTest.java | 4 - .../db/user/UserGroupDaoWithPersisterTest.java | 1 - .../java/org/sonar/db/user/UserTokenDaoTest.java | 3 - .../db/user/UserTokenDaoWithPersisterTest.java | 3 - .../java/org/sonar/db/user/UserTokenDtoTest.java | 12 +- .../sonar/db/webhook/WebhookDeliveryDaoTest.java | 3 - .../charset/DatabaseCharsetCheckerTest.java | 17 +- .../migration/charset/MssqlCharsetHandlerTest.java | 17 +- .../charset/OracleCharsetHandlerTest.java | 17 +- .../charset/PostgresCharsetHandlerTest.java | 19 +- .../db/migration/def/BigIntegerColumnDefTest.java | 29 +-- .../db/migration/def/BlobColumnDefTest.java | 25 +- .../db/migration/def/BooleanColumnDefTest.java | 24 +- .../db/migration/def/ClobColumnDefTest.java | 27 +- .../db/migration/def/DecimalColumnDefTest.java | 56 ++--- .../db/migration/def/IntegerColumnDefTest.java | 25 +- .../db/migration/def/TimestampColumnDefTest.java | 21 +- .../db/migration/def/TinyIntColumnDefTest.java | 28 +-- .../platform/db/migration/def/ValidationsTest.java | 42 ++-- .../db/migration/def/VarcharColumnDefTest.java | 42 ++-- .../history/MigrationHistoryImplTest.java | 9 +- .../history/MigrationHistoryTableImplTest.java | 3 - .../history/NoTableMigrationHistoryImplTest.java | 18 +- .../db/migration/sql/AddColumnsBuilderTest.java | 13 +- .../db/migration/sql/AlterColumnsBuilderTest.java | 19 +- .../db/migration/sql/CreateIndexBuilderTest.java | 86 +++---- .../db/migration/sql/CreateTableAsBuilderTest.java | 17 +- .../db/migration/sql/CreateTableBuilderTest.java | 119 ++++----- .../sql/DbPrimaryKeyConstraintFinderTest.java | 1 - .../DropMsSQLDefaultConstraintsBuilderTest.java | 23 +- .../db/migration/sql/DropTableBuilderTest.java | 63 +++-- .../db/migration/sql/RenameColumnsBuilderTest.java | 27 +- .../db/migration/sql/RenameTableBuilderTest.java | 21 +- .../platform/db/migration/step/DataChangeTest.java | 113 +++++---- .../db/migration/step/DropIndexBuilderTest.java | 61 ++--- .../db/migration/step/MigrationNumberTest.java | 13 +- .../step/MigrationStepExecutionExceptionTest.java | 23 +- .../step/MigrationStepRegistryImplTest.java | 55 ++-- .../db/migration/step/MigrationStepsImplTest.java | 39 ++- .../migration/step/MigrationStepsProviderTest.java | 12 +- .../step/RegisteredMigrationStepTest.java | 19 +- .../platform/db/migration/step/UpsertImplTest.java | 12 +- .../version/v91/CreateAuditTableTest.java | 3 +- .../org/sonar/application/AppFileSystemTest.java | 18 +- .../java/org/sonar/application/AppLoggingTest.java | 18 +- .../org/sonar/application/AppReloaderImplTest.java | 35 ++- .../org/sonar/application/SchedulerImplTest.java | 4 - .../AppNodesClusterHostsConsistencyTest.java | 19 +- .../health/SearchNodeHealthProviderTest.java | 33 +-- .../application/command/AbstractCommandTest.java | 40 ++- .../command/CommandFactoryImplTest.java | 11 +- .../application/command/EsJvmOptionsTest.java | 14 +- .../sonar/application/command/JvmOptionsTest.java | 99 +++----- .../config/AppSettingsLoaderImplTest.java | 11 +- .../application/config/CommandLineParserTest.java | 14 +- .../application/config/FileSystemSettingsTest.java | 3 - .../sonar/application/config/JdbcSettingsTest.java | 39 ++- .../sonar/application/es/EsInstallationTest.java | 25 +- .../sonar/application/es/EsYmlSettingsTest.java | 11 +- .../process/ManagedProcessHandlerTest.java | 19 +- .../process/ProcessCommandsManagedProcessTest.java | 4 +- .../src/main/java/org/sonar/process/ProcessId.java | 2 - .../java/org/sonar/process/ProcessProperties.java | 2 - .../java/org/sonar/process/FileUtils2Test.java | 46 ++-- .../src/test/java/org/sonar/process/JmxTest.java | 19 +- .../org/sonar/process/NetworkUtilsImplTest.java | 4 - .../test/java/org/sonar/process/ProcessIdTest.java | 19 +- .../src/test/java/org/sonar/process/PropsTest.java | 11 +- .../java/org/sonar/process/SystemExitTest.java | 3 +- .../org/sonar/process/cluster/NodeTypeTest.java | 12 +- .../cluster/health/HealthStateRefresherTest.java | 3 - .../process/cluster/health/NodeDetailsTest.java | 103 ++++---- .../process/cluster/health/NodeHealthTest.java | 33 +-- .../cluster/health/SharedHealthStateImplTest.java | 11 +- .../process/cluster/hz/DistributedAnswerTest.java | 19 +- .../cluster/hz/HazelcastMemberBuilderTest.java | 1 - .../cluster/hz/HazelcastMemberImplTest.java | 3 - .../sonar/process/logging/LogLevelConfigTest.java | 96 +++---- .../sonar/process/logging/LogbackHelperTest.java | 32 +-- .../process/logging/LogbackJsonLayoutTest.java | 2 +- .../sharedmemoryfile/AllProcessesCommandsTest.java | 18 +- .../DefaultProcessCommandsTest.java | 56 ++--- .../notification/DefaultNotificationManager.java | 2 - .../server/notification/NotificationManager.java | 2 - .../sonar/server/async/AsyncExecutionImplTest.java | 16 +- .../component/index/ComponentIndexerTest.java | 4 +- .../component/index/SuggestionQueryTest.java | 33 +-- .../org/sonar/server/es/EsClientProviderTest.java | 18 +- .../java/org/sonar/server/es/EsClientTest.java | 24 +- .../server/es/IndexDefinitionContextTest.java | 12 +- .../test/java/org/sonar/server/es/IndexTest.java | 57 ++--- .../java/org/sonar/server/es/IndexTypeTest.java | 26 +- .../es/NewIndexSettingsConfigurationTest.java | 40 ++- .../es/OneToManyResilientIndexingListenerTest.java | 3 - .../es/OneToOneResilientIndexingListenerTest.java | 3 - .../org/sonar/server/es/SearchOptionsTest.java | 42 ++-- .../org/sonar/server/es/StartupIndexerTest.java | 19 +- .../org/sonar/server/es/newindex/NewIndexTest.java | 26 +- .../server/es/newindex/NewRegularIndexTest.java | 47 ++-- .../SimpleFieldTopAggregationDefinitionTest.java | 11 +- .../ComponentTextSearchQueryFactoryTest.java | 37 ++- .../sonar/server/favorite/FavoriteUpdaterTest.java | 18 +- .../sonar/server/issue/IssueFieldsSetterTest.java | 18 +- .../sonar/server/issue/index/IssueIndexerTest.java | 17 +- .../ChangesOnMyIssuesEmailTemplateTest.java | 11 +- .../notification/NewIssuesStatisticsTest.java | 10 +- .../org/sonar/server/issue/workflow/StateTest.java | 27 +- .../org/sonar/server/log/ServerLoggingTest.java | 18 +- .../sonar/server/measure/DebtRatingGridTest.java | 27 +- .../DefaultNotificationManagerTest.java | 28 +-- .../server/notification/EmailRecipientTest.java | 19 +- .../notification/NotificationServiceTest.java | 12 +- .../permission/index/AuthorizationDocTest.java | 24 +- .../platform/ServerLifecycleNotifierTest.java | 1 - .../platform/StartupMetadataProviderTest.java | 10 +- .../server/platform/TempFolderProviderTest.java | 3 - .../org/sonar/server/platform/UrlSettingsTest.java | 10 +- .../sonar/server/platform/WebServerImplTest.java | 4 - .../cluster/ProcessInfoProviderTest.java | 4 - .../platform/serverid/ServerIdChecksumTest.java | 12 +- .../InstalledPluginReferentialFactoryTest.java | 6 +- .../plugins/ServerExtensionInstallerTest.java | 6 - .../property/InternalPropertiesImplTest.java | 31 +-- .../server/qualitygate/ConditionEvaluatorTest.java | 20 +- .../sonar/server/qualitygate/ConditionTest.java | 26 +- .../server/qualitygate/EvaluatedConditionTest.java | 19 +- .../qualitygate/EvaluatedQualityGateTest.java | 40 ++- .../sonar/server/qualitygate/QualityGateTest.java | 47 ++-- .../server/qualityprofile/QualityProfileTest.java | 30 ++- .../server/rule/index/RuleIndexDefinitionTest.java | 1 - .../org/sonar/server/rule/index/RuleIndexTest.java | 11 +- .../sonar/server/setting/ChildSettingsTest.java | 19 +- .../setting/DatabaseSettingsEnablerTest.java | 4 - .../server/setting/ThreadLocalSettingsTest.java | 3 - .../util/AbstractStoppableExecutorServiceTest.java | 7 +- .../org/sonar/server/webhook/AnalysisTest.java | 12 +- .../java/org/sonar/server/webhook/BranchTest.java | 12 +- .../java/org/sonar/server/webhook/CeTaskTest.java | 19 +- .../sonar/server/webhook/ProjectAnalysisTest.java | 47 ++-- .../sonar/server/webhook/TestWebhookCaller.java | 1 - .../sonar/server/webhook/WebhookModuleTest.java | 3 - .../server/app/ProcessCommandWrapperImplTest.java | 39 ++- .../server/exceptions/BadRequestExceptionTest.java | 28 +-- .../org/sonar/server/exceptions/MessageTest.java | 17 +- .../sonar/server/plugins/PluginDownloaderTest.java | 9 +- .../sonar/server/plugins/PluginJarLoaderTest.java | 72 +++--- .../server/plugins/PluginUninstallerTest.java | 3 - .../server/plugins/ServerPluginRepositoryTest.java | 2 - .../org/sonar/server/plugins/TestProjectUtils.java | 3 +- .../sonar/server/plugins/UpdateCenterServlet.java | 4 +- .../plugins/edition/EditionBundledPluginsTest.java | 15 +- .../project/ProjectLifeCycleListenersImplTest.java | 47 ++-- .../sonar/server/project/RekeyedProjectTest.java | 19 +- .../qualitygate/changeevent/QGChangeEventTest.java | 40 ++- .../server/util/BooleanTypeValidationTest.java | 14 +- .../sonar/server/util/FloatTypeValidationTest.java | 14 +- .../server/util/GlobalLockManagerImplTest.java | 46 ++-- .../server/util/IntegerTypeValidationTest.java | 20 +- .../sonar/server/util/LongTypeValidationTest.java | 19 +- .../server/util/StringListTypeValidationTest.java | 14 +- .../authentication/BasicAuthenticationTest.java | 62 +++-- .../sonar/server/authentication/CookiesTest.java | 13 +- .../CredentialsAuthenticationTest.java | 65 +++-- .../CredentialsExternalAuthenticationTest.java | 64 +++-- .../DefaultAdminCredentialsVerifierImplTest.java | 1 - .../HttpHeadersAuthenticationTest.java | 20 +- .../IdentityProviderRepositoryTest.java | 11 +- .../server/authentication/InitFilterTest.java | 3 - .../server/authentication/JwtCsrfVerifierTest.java | 58 +++-- .../server/authentication/JwtHttpHandlerTest.java | 32 +-- .../server/authentication/JwtSerializerTest.java | 61 ++--- .../server/authentication/LogOAuthWarningTest.java | 3 - .../authentication/OAuth2CallbackFilterTest.java | 3 - .../authentication/OAuth2ContextFactoryTest.java | 4 - .../authentication/OAuthCsrfVerifierTest.java | 48 ++-- .../authentication/ResetPasswordFilterTest.java | 1 - .../authentication/UserRegistrarImplTest.java | 71 +++--- .../event/AuthenticationEventImplTest.java | 46 ++-- .../event/AuthenticationEventSourceTest.java | 75 +++--- .../event/AuthenticationExceptionTest.java | 12 +- .../server/permission/GroupUuidOrAnyoneTest.java | 4 - .../BuiltInQPChangeNotificationTest.java | 12 +- .../BuiltInQProfileInsertImplTest.java | 3 - .../BuiltInQProfileRepositoryImplTest.java | 34 +-- .../BuiltInQProfileUpdateImplTest.java | 1 - .../org/sonar/server/user/DoPrivilegedTest.java | 1 - .../sonar/server/user/ExternalIdentityTest.java | 19 +- .../java/org/sonar/server/user/NewUserTest.java | 26 +- .../sonar/server/user/UserUpdaterCreateTest.java | 277 ++++++++++---------- .../server/user/UserUpdaterReactivateTest.java | 61 ++--- .../usertoken/UserTokenAuthenticationTest.java | 3 - .../server/app/WebServerProcessLoggingTest.java | 39 ++- .../sonar/server/ce/http/CeHttpClientImplTest.java | 37 ++- .../email/EmailNotificationChannelTest.java | 4 - .../server/platform/ClusterVerificationTest.java | 17 +- .../platform/DatabaseServerCompatibilityTest.java | 3 - .../server/platform/PersistentSettingsTest.java | 2 +- .../platform/StandaloneSystemInfoWriterTest.java | 3 - .../platform/StartupMetadataPersisterTest.java | 3 - .../server/platform/db/EmbeddedDatabaseTest.java | 32 +-- .../platform/db/migration/AutoDbMigrationTest.java | 3 - .../platform/monitoring/BundledSectionTest.java | 2 +- .../platform/monitoring/EsIndexesSectionTest.java | 1 - .../platform/monitoring/PluginsSectionTest.java | 2 - .../cluster/AppNodesInfoLoaderImplTest.java | 4 - .../monitoring/cluster/NodeSystemSectionTest.java | 4 - .../platform/serverid/ServerIdFactoryImplTest.java | 21 +- .../platform/serverid/ServerIdManagerTest.java | 37 ++- .../web/requestid/RequestIdGeneratorImplTest.java | 23 +- .../plugins/PluginsRiskConsentFilterTest.java | 11 +- .../qualitygate/ProjectsInWarningDaemonTest.java | 3 - .../org/sonar/server/rule/RegisterRulesTest.java | 82 +++--- .../java/org/sonar/server/search/BaseDocTest.java | 12 +- .../server/startup/GeneratePluginIndexTest.java | 6 +- .../sonar/server/startup/RegisterMetricsTest.java | 11 +- .../startup/RegisterPermissionTemplatesTest.java | 3 - .../java/org/sonar/server/es/IndexCreatorTest.java | 11 +- .../es/metadata/EsDbCompatibilityImplTest.java | 4 - .../server/issue/index/IssueIndexFacetsTest.java | 4 - .../server/issue/index/IssueIndexFiltersTest.java | 49 ++-- .../index/IssueIndexSecurityHotspotsTest.java | 4 - .../issue/index/IssueIndexSecurityReportsTest.java | 5 - .../server/issue/index/IssueIndexSortTest.java | 4 - .../sonar/server/issue/index/IssueIndexTest.java | 7 - .../server/issue/index/IssueQueryFactoryTest.java | 94 ++++--- .../measure/index/ProjectMeasuresIndexTest.java | 20 +- .../index/ProjectMeasuresIndexTextSearchTest.java | 3 - .../measure/index/ProjectMeasuresQueryTest.java | 27 +- .../permission/index/PermissionIndexerTest.java | 3 - .../server/almintegration/ws/SetPatActionTest.java | 61 +++-- .../ws/azure/ListAzureProjectsActionTest.java | 5 - .../ImportBitbucketServerProjectActionTest.java | 109 ++++---- .../SearchBitbucketServerReposActionTest.java | 56 +++-- .../almsettings/ws/CountBindingActionTest.java | 20 +- .../almsettings/ws/CreateAzureActionTest.java | 29 +-- .../almsettings/ws/CreateBitbucketActionTest.java | 41 ++- .../ws/CreateBitbucketCloudActionTest.java | 38 ++- .../almsettings/ws/CreateGithubActionTest.java | 39 ++- .../almsettings/ws/CreateGitlabActionTest.java | 29 +-- .../server/almsettings/ws/DeleteActionTest.java | 20 +- .../almsettings/ws/GetBindingActionTest.java | 18 +- .../server/almsettings/ws/ListActionTest.java | 7 +- .../almsettings/ws/ListDefinitionsActionTest.java | 10 +- .../almsettings/ws/UpdateAzureActionTest.java | 29 +-- .../almsettings/ws/UpdateBitbucketActionTest.java | 31 +-- .../almsettings/ws/UpdateGithubActionTest.java | 39 ++- .../almsettings/ws/UpdateGitlabActionTest.java | 29 +-- .../sonar/server/badge/ws/MeasureActionTest.java | 49 ++-- .../server/badge/ws/QualityGateActionTest.java | 17 +- .../sonar/server/badge/ws/SvgGeneratorTest.java | 9 +- .../org/sonar/server/batch/BatchIndexTest.java | 34 +-- .../org/sonar/server/batch/FileActionTest.java | 16 +- .../org/sonar/server/batch/IndexActionTest.java | 9 +- .../org/sonar/server/batch/IssuesActionTest.java | 40 ++- .../sonar/server/batch/ProjectDataLoaderTest.java | 43 ++-- .../server/branch/pr/ws/DeleteActionTest.java | 43 ++-- .../sonar/server/branch/pr/ws/ListActionTest.java | 45 ++-- .../sonar/server/branch/ws/DeleteActionTest.java | 52 ++-- .../org/sonar/server/branch/ws/ListActionTest.java | 38 ++- .../sonar/server/branch/ws/RenameActionTest.java | 52 ++-- .../SetAutomaticDeletionProtectionActionTest.java | 80 +++--- .../org/sonar/server/ce/ws/CancelActionTest.java | 50 ++-- .../sonar/server/ce/ws/CancelAllActionTest.java | 16 +- .../org/sonar/server/ce/ws/InfoActionTest.java | 18 +- .../org/sonar/server/ce/ws/PauseActionTest.java | 18 +- .../org/sonar/server/ce/ws/ResumeActionTest.java | 18 +- .../sonar/server/ce/ws/WorkerCountActionTest.java | 9 +- .../ws/ProjectMeasuresQueryFactoryTest.java | 137 +++++----- .../ws/ProjectMeasuresQueryValidatorTest.java | 18 +- .../developers/ws/SearchEventsActionTest.java | 32 +-- .../org/sonar/server/email/ws/SendActionTest.java | 25 +- .../sonar/server/favorite/ws/AddActionTest.java | 47 ++-- .../org/sonar/server/health/ClusterHealthTest.java | 19 +- .../sonar/server/health/HealthCheckerImplTest.java | 37 ++- .../java/org/sonar/server/health/HealthTest.java | 43 ++-- .../server/health/NodeHealthProviderImplTest.java | 31 +-- .../java/org/sonar/server/issue/ActionTest.java | 20 +- .../org/sonar/server/issue/AddTagsActionTest.java | 26 +- .../org/sonar/server/issue/AssignActionTest.java | 26 +- .../sonar/server/issue/AvatarResolverImplTest.java | 26 +- .../org/sonar/server/issue/IssueFinderTest.java | 14 +- .../sonar/server/issue/RemoveTagsActionTest.java | 26 +- .../sonar/server/issue/SetSeverityActionTest.java | 11 +- .../org/sonar/server/issue/SetTypeActionTest.java | 18 +- .../sonar/server/issue/TransitionActionTest.java | 10 +- .../sonar/server/issue/TransitionServiceTest.java | 11 +- .../server/issue/ws/AddCommentActionTest.java | 27 +- .../sonar/server/issue/ws/AssignActionTest.java | 56 ++--- .../sonar/server/issue/ws/AuthorsActionTest.java | 35 ++- .../server/issue/ws/BulkChangeActionTest.java | 41 +-- .../sonar/server/issue/ws/ChangelogActionTest.java | 7 +- .../server/issue/ws/DeleteCommentActionTest.java | 32 ++- .../server/issue/ws/DoTransitionActionTest.java | 37 ++- .../server/issue/ws/EditCommentActionTest.java | 45 ++-- .../sonar/server/issue/ws/IssueUpdaterTest.java | 3 - .../issue/ws/SearchActionComponentsTest.java | 3 - .../server/issue/ws/SearchActionFacetsTest.java | 32 +-- .../sonar/server/issue/ws/SearchActionTest.java | 31 ++- .../server/issue/ws/SetSeverityActionTest.java | 21 +- .../sonar/server/issue/ws/SetTagsActionTest.java | 26 +- .../sonar/server/issue/ws/SetTypeActionTest.java | 20 +- .../org/sonar/server/issue/ws/TagsActionTest.java | 17 +- .../server/language/LanguageValidationTest.java | 4 - .../live/IssueMetricFormulaFactoryImplTest.java | 4 - .../measure/live/LiveMeasureComputerImplTest.java | 17 +- .../live/LiveQualityGateComputerImplTest.java | 3 - .../server/measure/live/MeasureMatrixTest.java | 19 +- .../server/measure/ws/ComponentActionTest.java | 85 ++++--- .../server/measure/ws/ComponentTreeActionTest.java | 263 ++++++++++--------- .../measure/ws/MeasureValueFormatterTest.java | 12 +- .../sonar/server/measure/ws/SearchActionTest.java | 67 +++-- .../server/measure/ws/SearchHistoryActionTest.java | 48 ++-- .../server/metric/ws/MetricKeyValidatorTest.java | 12 +- .../server/newcodeperiod/ws/ListActionTest.java | 21 +- .../server/newcodeperiod/ws/SetActionTest.java | 122 ++++----- .../server/newcodeperiod/ws/ShowActionTest.java | 30 +-- .../server/newcodeperiod/ws/UnsetActionTest.java | 47 ++-- .../server/notification/ws/AddActionTest.java | 89 +++---- .../ApplyPermissionTemplateQueryTest.java | 19 +- .../permission/GroupPermissionChangerTest.java | 46 ++-- .../permission/PermissionTemplateServiceTest.java | 3 - .../permission/UserPermissionChangerTest.java | 51 ++-- .../server/permission/ws/AddGroupActionTest.java | 185 +++++++------- .../server/permission/ws/AddUserActionTest.java | 180 ++++++------- .../server/permission/ws/BasePermissionWsTest.java | 3 - .../server/permission/ws/GroupsActionTest.java | 76 +++--- .../permission/ws/RemoveGroupActionTest.java | 241 +++++++++--------- .../server/permission/ws/RemoveUserActionTest.java | 211 ++++++++-------- .../server/permission/ws/UsersActionTest.java | 94 +++---- .../ws/template/AddGroupToTemplateActionTest.java | 47 ++-- .../AddProjectCreatorToTemplateActionTest.java | 40 +-- .../ws/template/AddUserToTemplateActionTest.java | 51 ++-- .../ws/template/ApplyTemplateActionTest.java | 52 ++-- .../ws/template/BulkApplyTemplateActionTest.java | 43 ++-- .../ws/template/CreateTemplateActionTest.java | 32 ++- .../ws/template/DeleteTemplateActionTest.java | 74 +++--- .../RemoveGroupFromTemplateActionTest.java | 59 +++-- ...RemoveProjectCreatorFromTemplateActionTest.java | 53 ++-- .../template/RemoveUserFromTemplateActionTest.java | 59 +++-- .../ws/template/SearchTemplatesActionTest.java | 10 +- .../ws/template/SearchTemplatesDataTest.java | 45 ++-- .../ws/template/SetDefaultTemplateActionTest.java | 38 +-- .../ws/template/TemplateGroupsActionTest.java | 79 +++--- .../ws/template/TemplateUsersActionTest.java | 54 ++-- .../ws/template/UpdateTemplateActionTest.java | 76 +++--- .../platform/ws/ChangeLogLevelActionTest.java | 28 +-- .../platform/ws/DbMigrationStatusActionTest.java | 12 +- .../sonar/server/platform/ws/HealthActionTest.java | 51 ++-- .../sonar/server/platform/ws/IndexActionTest.java | 11 +- .../sonar/server/platform/ws/InfoActionTest.java | 14 +- .../sonar/server/platform/ws/LogsActionTest.java | 14 +- .../server/platform/ws/MigrateDbActionTest.java | 14 +- .../server/platform/ws/RestartActionTest.java | 20 +- .../platform/ws/SafeModeHealthActionTest.java | 17 +- .../server/plugins/ws/AvailableActionTest.java | 114 ++++----- .../server/plugins/ws/CancelAllActionTest.java | 18 +- .../server/plugins/ws/DownloadActionTest.java | 3 - .../server/plugins/ws/InstalledActionTest.java | 3 - .../sonar/server/plugins/ws/PendingActionTest.java | 14 +- .../ws/PluginUpdateAggregateBuilderTest.java | 12 +- .../sonar/server/plugins/ws/UpdateActionTest.java | 41 ++- .../sonar/server/plugins/ws/UpdatesActionTest.java | 13 +- .../projectanalysis/ws/CreateEventActionTest.java | 59 ++--- .../projectanalysis/ws/DeleteActionTest.java | 40 ++- .../projectanalysis/ws/DeleteEventActionTest.java | 35 ++- .../projectanalysis/ws/EventValidatorTest.java | 12 +- .../projectanalysis/ws/SetBaselineActionTest.java | 50 ++-- .../ws/UnsetBaselineActionTest.java | 46 ++-- .../projectanalysis/ws/UpdateEventActionTest.java | 54 ++-- .../server/projectdump/ws/ExportActionTest.java | 36 ++- .../server/projectdump/ws/StatusActionTest.java | 70 +++--- .../server/projectlink/ws/CreateActionTest.java | 92 +++---- .../server/projectlink/ws/DeleteActionTest.java | 27 +- .../server/projectlink/ws/SearchActionTest.java | 66 +++-- .../server/projecttag/ws/SearchActionTest.java | 3 - .../QualityGateConditionsUpdaterTest.java | 96 +++---- .../server/qualitygate/QualityGateUpdaterTest.java | 11 +- .../server/qualitygate/ws/CopyActionTest.java | 47 ++-- .../server/qualitygate/ws/CreateActionTest.java | 27 +- .../qualitygate/ws/CreateConditionActionTest.java | 40 ++- .../qualitygate/ws/DeleteConditionActionTest.java | 38 ++- .../server/qualitygate/ws/DeselectActionTest.java | 41 ++- .../server/qualitygate/ws/DestroyActionTest.java | 43 ++-- .../qualitygate/ws/GetByProjectActionTest.java | 34 +-- .../server/qualitygate/ws/ListActionTest.java | 11 +- .../qualitygate/ws/ProjectStatusActionTest.java | 66 +++-- .../ws/QualityGateDetailsFormatterTest.java | 17 +- .../qualitygate/ws/RemoveGroupActionTest.java | 38 ++- .../server/qualitygate/ws/RenameActionTest.java | 45 ++-- .../server/qualitygate/ws/SearchActionTest.java | 33 ++- .../qualitygate/ws/SearchGroupsActionTest.java | 20 +- .../server/qualitygate/ws/SelectActionTest.java | 44 ++-- .../server/qualitygate/ws/ShowActionTest.java | 47 ++-- .../qualitygate/ws/UpdateConditionActionTest.java | 58 ++--- .../qualityprofile/QProfileBackuperImplTest.java | 23 +- .../server/qualityprofile/QProfileCopierTest.java | 3 - .../qualityprofile/QProfileExportersTest.java | 13 +- .../qualityprofile/QProfileFactoryImplTest.java | 24 +- .../qualityprofile/QProfileResetImplTest.java | 22 +- .../qualityprofile/QProfileRuleImplTest.java | 20 +- .../qualityprofile/QProfileTreeImplTest.java | 35 ++- .../RegisterQualityProfilesNotificationTest.java | 3 - .../RegisterQualityProfilesTest.java | 11 +- .../qualityprofile/ws/ActivateRuleActionTest.java | 28 +-- .../qualityprofile/ws/ActivateRulesActionTest.java | 27 +- .../qualityprofile/ws/AddGroupActionTest.java | 87 +++---- .../qualityprofile/ws/AddProjectActionTest.java | 65 +++-- .../qualityprofile/ws/AddUserActionTest.java | 78 +++--- .../qualityprofile/ws/ChangeParentActionTest.java | 15 +- .../qualityprofile/ws/ChangelogActionTest.java | 3 - .../qualityprofile/ws/CompareActionTest.java | 54 ++-- .../server/qualityprofile/ws/CopyActionTest.java | 81 +++--- .../server/qualityprofile/ws/CreateActionTest.java | 23 +- .../ws/DeactivateRuleActionTest.java | 21 +- .../ws/DeactivateRulesActionTest.java | 17 +- .../server/qualityprofile/ws/DeleteActionTest.java | 145 ++++++----- .../server/qualityprofile/ws/ExportActionTest.java | 28 +-- .../qualityprofile/ws/InheritanceActionTest.java | 17 +- .../qualityprofile/ws/ProjectsActionTest.java | 15 +- .../qualityprofile/ws/QProfileReferenceTest.java | 28 +-- .../qualityprofile/ws/QProfileWsSupportTest.java | 25 +- .../qualityprofile/ws/RemoveGroupActionTest.java | 87 +++---- .../qualityprofile/ws/RemoveProjectActionTest.java | 67 +++-- .../qualityprofile/ws/RemoveUserActionTest.java | 84 ++++--- .../server/qualityprofile/ws/RenameActionTest.java | 83 +++--- .../qualityprofile/ws/RestoreActionTest.java | 35 +-- .../server/qualityprofile/ws/SearchActionTest.java | 13 +- .../qualityprofile/ws/SearchGroupsActionTest.java | 47 ++-- .../qualityprofile/ws/SearchUsersActionTest.java | 54 ++-- .../qualityprofile/ws/SetDefaultActionTest.java | 32 +-- .../server/qualityprofile/ws/ShowActionTest.java | 22 +- .../org/sonar/server/root/ws/SearchActionTest.java | 20 +- .../sonar/server/root/ws/SetRootActionTest.java | 41 ++- .../sonar/server/root/ws/UnsetRootActionTest.java | 56 ++--- .../org/sonar/server/rule/RuleCreatorTest.java | 244 +++++++++--------- .../org/sonar/server/rule/RuleUpdaterTest.java | 62 ++--- .../org/sonar/server/rule/ws/AppActionTest.java | 3 - .../org/sonar/server/rule/ws/CreateActionTest.java | 28 +-- .../org/sonar/server/rule/ws/DeleteActionTest.java | 45 ++-- .../sonar/server/rule/ws/RuleQueryFactoryTest.java | 32 +-- .../org/sonar/server/rule/ws/SearchActionTest.java | 18 +- .../org/sonar/server/rule/ws/UpdateActionTest.java | 53 ++-- .../setting/ws/CheckSecretKeyActionTest.java | 11 +- .../sonar/server/setting/ws/EncryptActionTest.java | 31 +-- .../setting/ws/GenerateSecretKeyActionTest.java | 11 +- .../GenerateSecretKeyActionWithPersisterTest.java | 3 - .../setting/ws/ListDefinitionsActionTest.java | 22 +- .../sonar/server/setting/ws/ResetActionTest.java | 133 +++++----- .../org/sonar/server/setting/ws/SetActionTest.java | 280 +++++++++++---------- .../server/setting/ws/SettingsUpdaterTest.java | 22 +- .../sonar/server/setting/ws/ValuesActionTest.java | 65 ++--- .../org/sonar/server/source/SourceServiceTest.java | 18 +- .../sonar/server/source/ws/IndexActionTest.java | 27 +- .../server/source/ws/IssueSnippetsActionTest.java | 22 +- .../sonar/server/source/ws/LinesActionTest.java | 84 +++---- .../org/sonar/server/source/ws/RawActionTest.java | 40 ++- .../org/sonar/server/source/ws/ScmActionTest.java | 24 +- .../org/sonar/server/source/ws/ShowActionTest.java | 7 +- .../org/sonar/server/ui/PageRepositoryTest.java | 26 +- .../sonar/server/ui/ws/ComponentActionTest.java | 10 +- .../sonar/server/ui/ws/MarketplaceActionTest.java | 18 +- .../org/sonar/server/user/ws/CreateActionTest.java | 142 ++++++----- .../server/user/ws/CurrentActionHomepageTest.java | 3 - .../sonar/server/user/ws/DeactivateActionTest.java | 69 ++--- .../org/sonar/server/user/ws/GroupsActionTest.java | 58 +++-- .../user/ws/IdentityProvidersActionTest.java | 3 - .../server/user/ws/SetHomepageActionTest.java | 34 ++- .../sonar/server/user/ws/SetSettingActionTest.java | 17 +- .../user/ws/SkipOnboardingTutorialActionTest.java | 17 +- .../org/sonar/server/user/ws/UpdateActionTest.java | 86 ++++--- .../server/user/ws/UpdateLoginActionTest.java | 62 ++--- .../server/usergroups/ws/AddUserActionTest.java | 71 +++--- .../server/usergroups/ws/CreateActionTest.java | 80 +++--- .../server/usergroups/ws/DeleteActionTest.java | 53 ++-- .../sonar/server/usergroups/ws/GroupWsRefTest.java | 4 - .../server/usergroups/ws/RemoveUserActionTest.java | 79 +++--- .../server/usergroups/ws/SearchActionTest.java | 10 +- .../server/usergroups/ws/UpdateActionTest.java | 148 +++++------ .../server/usergroups/ws/UsersActionTest.java | 28 +-- .../server/usertoken/ws/GenerateActionTest.java | 54 ++-- .../server/usertoken/ws/RevokeActionTest.java | 27 +- .../server/usertoken/ws/SearchActionTest.java | 27 +- .../webhook/ws/WebhookDeliveryActionTest.java | 29 +-- .../server/ws/RemovedWebServiceHandlerTest.java | 4 - .../org/sonar/server/ws/ServletRequestTest.java | 4 - .../org/sonar/server/ws/ServletResponseTest.java | 4 - .../test/java/org/sonar/server/ws/WsUtilsTest.java | 21 +- .../java/org/sonar/server/app/StartupLogsTest.java | 12 +- .../org/sonar/server/app/TomcatContextsTest.java | 16 +- .../platform/platformlevel/PlatformLevelTest.java | 26 +- .../platform/web/MasterServletFilterTest.java | 18 +- .../sonar/server/platform/web/RootFilterTest.java | 13 +- .../server/platform/web/WebPagesCacheTest.java | 12 +- .../server/platform/web/WebPagesFilterTest.java | 4 - .../server/platform/web/WebServiceFilterTest.java | 4 - .../web/WebServiceReroutingFilterTest.java | 4 - 761 files changed, 9784 insertions(+), 12005 deletions(-) (limited to 'server') diff --git a/server/sonar-alm-client/src/test/java/org/sonar/alm/client/bitbucketserver/BranchesListTest.java b/server/sonar-alm-client/src/test/java/org/sonar/alm/client/bitbucketserver/BranchesListTest.java index 80fb549952a..feb9dc1fc88 100644 --- a/server/sonar-alm-client/src/test/java/org/sonar/alm/client/bitbucketserver/BranchesListTest.java +++ b/server/sonar-alm-client/src/test/java/org/sonar/alm/client/bitbucketserver/BranchesListTest.java @@ -19,10 +19,10 @@ */ package org.sonar.alm.client.bitbucketserver; +import java.util.Optional; import org.junit.Test; -import static org.assertj.core.api.Assertions.*; -import java.util.Optional; +import static org.assertj.core.api.Assertions.assertThat; public class BranchesListTest { diff --git a/server/sonar-alm-client/src/test/java/org/sonar/alm/client/github/config/GithubAppConfigurationTest.java b/server/sonar-alm-client/src/test/java/org/sonar/alm/client/github/config/GithubAppConfigurationTest.java index 6dd3e131e31..095d77e44ee 100644 --- a/server/sonar-alm-client/src/test/java/org/sonar/alm/client/github/config/GithubAppConfigurationTest.java +++ b/server/sonar-alm-client/src/test/java/org/sonar/alm/client/github/config/GithubAppConfigurationTest.java @@ -22,24 +22,19 @@ package org.sonar.alm.client.github.config; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; - import java.util.Random; import java.util.stream.Stream; import javax.annotation.Nullable; - import org.apache.commons.lang.ArrayUtils; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; @RunWith(DataProviderRunner.class) public class GithubAppConfigurationTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test @UseDataProvider("incompleteConfigurationParametersSonarQube") @@ -54,9 +49,9 @@ public class GithubAppConfigurationTest { public void getId_throws_ISE_if_config_is_incomplete(@Nullable Long applicationId, @Nullable String privateKey, @Nullable String apiEndpoint) { GithubAppConfiguration underTest = new GithubAppConfiguration(applicationId, privateKey, apiEndpoint); - expectConfigurationIncompleteISE(); - - underTest.getId(); + assertThatThrownBy(underTest::getId) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Configuration is not complete"); } @Test @@ -72,9 +67,9 @@ public class GithubAppConfigurationTest { public void getPrivateKeyFile_throws_ISE_if_config_is_incomplete(@Nullable Long applicationId, @Nullable String privateKey, @Nullable String apiEndpoint) { GithubAppConfiguration underTest = new GithubAppConfiguration(applicationId, privateKey, apiEndpoint); - expectConfigurationIncompleteISE(); - - underTest.getPrivateKey(); + assertThatThrownBy(underTest::getPrivateKey) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Configuration is not complete"); } @DataProvider @@ -144,11 +139,6 @@ public class GithubAppConfigurationTest { assertThat(underTest.hashCode()).isNotEqualTo(new GithubAppConfiguration(applicationId, privateKey, apiEndpoint)); } - private void expectConfigurationIncompleteISE() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Configuration is not complete"); - } - private GithubAppConfiguration newValidConfiguration(long applicationId) { return new GithubAppConfiguration(applicationId, randomAlphabetic(6), randomAlphabetic(6)); } diff --git a/server/sonar-alm-client/src/test/java/org/sonar/alm/client/github/security/AppTokenTest.java b/server/sonar-alm-client/src/test/java/org/sonar/alm/client/github/security/AppTokenTest.java index f9e5560520f..620e4d754a1 100644 --- a/server/sonar-alm-client/src/test/java/org/sonar/alm/client/github/security/AppTokenTest.java +++ b/server/sonar-alm-client/src/test/java/org/sonar/alm/client/github/security/AppTokenTest.java @@ -20,7 +20,6 @@ package org.sonar.alm.client.github.security; import org.junit.Test; -import org.sonar.alm.client.github.security.AppToken; import static org.assertj.core.api.Assertions.assertThat; diff --git a/server/sonar-alm-client/src/test/java/org/sonar/alm/client/github/security/GithubAppSecurityImplTest.java b/server/sonar-alm-client/src/test/java/org/sonar/alm/client/github/security/GithubAppSecurityImplTest.java index d558e2b54d2..bf3f196fb6a 100644 --- a/server/sonar-alm-client/src/test/java/org/sonar/alm/client/github/security/GithubAppSecurityImplTest.java +++ b/server/sonar-alm-client/src/test/java/org/sonar/alm/client/github/security/GithubAppSecurityImplTest.java @@ -20,14 +20,12 @@ package org.sonar.alm.client.github.security; import com.tngtech.java.junit.dataprovider.DataProviderRunner; - import java.io.IOException; import java.security.spec.InvalidKeySpecException; import java.time.Clock; import java.time.Instant; import java.time.ZoneId; import java.util.Random; - import org.junit.Test; import org.junit.runner.RunWith; import org.sonar.alm.client.github.config.GithubAppConfiguration; diff --git a/server/sonar-auth-bitbucket/src/test/java/org/sonar/auth/bitbucket/BitbucketIdentityProviderTest.java b/server/sonar-auth-bitbucket/src/test/java/org/sonar/auth/bitbucket/BitbucketIdentityProviderTest.java index d135fb14285..89bd3fb0f79 100755 --- a/server/sonar-auth-bitbucket/src/test/java/org/sonar/auth/bitbucket/BitbucketIdentityProviderTest.java +++ b/server/sonar-auth-bitbucket/src/test/java/org/sonar/auth/bitbucket/BitbucketIdentityProviderTest.java @@ -19,21 +19,18 @@ */ package org.sonar.auth.bitbucket; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.server.authentication.OAuth2IdentityProvider; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class BitbucketIdentityProviderTest { - @Rule - public ExpectedException thrown = ExpectedException.none(); private final MapSettings settings = new MapSettings(); private final BitbucketSettings bitbucketSettings = new BitbucketSettings(settings.asConfig()); @@ -75,9 +72,9 @@ public class BitbucketIdentityProviderTest { enableBitbucketAuthentication(false); OAuth2IdentityProvider.InitContext context = mock(OAuth2IdentityProvider.InitContext.class); - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Bitbucket authentication is disabled"); - underTest.init(context); + assertThatThrownBy(() -> underTest.init(context)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Bitbucket authentication is disabled"); } private void enableBitbucketAuthentication(boolean enabled) { diff --git a/server/sonar-auth-common/src/test/java/org/sonar/auth/OAuthRestClientTest.java b/server/sonar-auth-common/src/test/java/org/sonar/auth/OAuthRestClientTest.java index 02730651fc5..6488c491d90 100644 --- a/server/sonar-auth-common/src/test/java/org/sonar/auth/OAuthRestClientTest.java +++ b/server/sonar-auth-common/src/test/java/org/sonar/auth/OAuthRestClientTest.java @@ -32,20 +32,16 @@ import okhttp3.mockwebserver.MockWebServer; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static java.lang.String.format; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.sonar.auth.OAuthRestClient.executePaginatedRequest; import static org.sonar.auth.OAuthRestClient.executeRequest; public class OAuthRestClientTest { - - @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Rule public MockWebServer mockWebServer = new MockWebServer(); @@ -77,10 +73,9 @@ public class OAuthRestClientTest { public void fail_to_execute_request() throws IOException { mockWebServer.enqueue(new MockResponse().setResponseCode(404).setBody("Error!")); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage(format("Fail to execute request '%s/test'. HTTP code: 404, response: Error!", serverUrl)); - - executeRequest(serverUrl + "/test", oAuth20Service, auth2AccessToken); + assertThatThrownBy(() -> executeRequest(serverUrl + "/test", oAuth20Service, auth2AccessToken)) + .isInstanceOf(IllegalStateException.class) + .hasMessage(format("Fail to execute request '%s/test'. HTTP code: 404, response: Error!", serverUrl)); } @Test @@ -135,10 +130,9 @@ public class OAuthRestClientTest { .setBody("A")); mockWebServer.enqueue(new MockResponse().setResponseCode(404).setBody("Error!")); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage(format("Fail to execute request '%s/test?per_page=100&page=2'. HTTP code: 404, response: Error!", serverUrl)); - - executePaginatedRequest(serverUrl + "/test", oAuth20Service, auth2AccessToken, Arrays::asList); + assertThatThrownBy(() -> executePaginatedRequest(serverUrl + "/test", oAuth20Service, auth2AccessToken, Arrays::asList)) + .isInstanceOf(IllegalStateException.class) + .hasMessage(format("Fail to execute request '%s/test?per_page=100&page=2'. HTTP code: 404, response: Error!", serverUrl)); } private class TestAPI extends DefaultApi20 { diff --git a/server/sonar-auth-github/src/test/java/org/sonar/auth/github/GitHubIdentityProviderTest.java b/server/sonar-auth-github/src/test/java/org/sonar/auth/github/GitHubIdentityProviderTest.java index d7ee6b2efd2..2e5e47a770f 100644 --- a/server/sonar-auth-github/src/test/java/org/sonar/auth/github/GitHubIdentityProviderTest.java +++ b/server/sonar-auth-github/src/test/java/org/sonar/auth/github/GitHubIdentityProviderTest.java @@ -19,21 +19,18 @@ */ package org.sonar.auth.github; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.server.authentication.OAuth2IdentityProvider; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class GitHubIdentityProviderTest { - @Rule - public ExpectedException thrown = ExpectedException.none(); private MapSettings settings = new MapSettings(); private GitHubSettings gitHubSettings = new GitHubSettings(settings.asConfig()); @@ -128,9 +125,9 @@ public class GitHubIdentityProviderTest { setSettings(false); OAuth2IdentityProvider.InitContext context = mock(OAuth2IdentityProvider.InitContext.class); - thrown.expect(IllegalStateException.class); - thrown.expectMessage("GitHub authentication is disabled"); - underTest.init(context); + assertThatThrownBy(() -> underTest.init(context)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("GitHub authentication is disabled"); } @Test diff --git a/server/sonar-auth-github/src/test/java/org/sonar/auth/github/UserIdentityFactoryImplTest.java b/server/sonar-auth-github/src/test/java/org/sonar/auth/github/UserIdentityFactoryImplTest.java index 4755660dd41..09f03dbc5b0 100644 --- a/server/sonar-auth-github/src/test/java/org/sonar/auth/github/UserIdentityFactoryImplTest.java +++ b/server/sonar-auth-github/src/test/java/org/sonar/auth/github/UserIdentityFactoryImplTest.java @@ -19,9 +19,7 @@ */ package org.sonar.auth.github; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.config.PropertyDefinitions; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.server.authentication.UserIdentity; @@ -31,8 +29,6 @@ import static org.assertj.core.api.Assertions.assertThat; public class UserIdentityFactoryImplTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private MapSettings settings = new MapSettings(new PropertyDefinitions(System2.INSTANCE, GitHubSettings.definitions())); private UserIdentityFactoryImpl underTest = new UserIdentityFactoryImpl(); diff --git a/server/sonar-auth-gitlab/src/test/java/org/sonar/auth/gitlab/GitLabIdentityProviderTest.java b/server/sonar-auth-gitlab/src/test/java/org/sonar/auth/gitlab/GitLabIdentityProviderTest.java index 5d2e086a03c..385725ebb39 100644 --- a/server/sonar-auth-gitlab/src/test/java/org/sonar/auth/gitlab/GitLabIdentityProviderTest.java +++ b/server/sonar-auth-gitlab/src/test/java/org/sonar/auth/gitlab/GitLabIdentityProviderTest.java @@ -20,9 +20,7 @@ package org.sonar.auth.gitlab; import org.assertj.core.api.Assertions; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.authentication.Display; import org.sonar.api.server.authentication.OAuth2IdentityProvider; diff --git a/server/sonar-auth-gitlab/src/test/java/org/sonar/auth/gitlab/GitLabSettingsTest.java b/server/sonar-auth-gitlab/src/test/java/org/sonar/auth/gitlab/GitLabSettingsTest.java index aff9fde5902..f006a153d9f 100644 --- a/server/sonar-auth-gitlab/src/test/java/org/sonar/auth/gitlab/GitLabSettingsTest.java +++ b/server/sonar-auth-gitlab/src/test/java/org/sonar/auth/gitlab/GitLabSettingsTest.java @@ -20,9 +20,7 @@ package org.sonar.auth.gitlab; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.config.PropertyDefinitions; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.utils.System2; @@ -37,8 +35,6 @@ import static org.sonar.auth.gitlab.GitLabSettings.GITLAB_AUTH_URL; public class GitLabSettingsTest { - @Rule - public ExpectedException thrown = ExpectedException.none(); private MapSettings settings; private GitLabSettings config; diff --git a/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/CallbackHandlerImplTest.java b/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/CallbackHandlerImplTest.java index 4129ab03855..7eca018edcf 100644 --- a/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/CallbackHandlerImplTest.java +++ b/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/CallbackHandlerImplTest.java @@ -26,6 +26,7 @@ import javax.security.auth.callback.UnsupportedCallbackException; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; public class CallbackHandlerImplTest { @@ -40,9 +41,12 @@ public class CallbackHandlerImplTest { assertThat(passwordCallback.getPassword()).isEqualTo("secret".toCharArray()); } - @Test(expected = UnsupportedCallbackException.class) - public void unsupportedCallback() throws Exception { - new CallbackHandlerImpl("tester", "secret").handle(new Callback[] {mock(Callback.class)}); + @Test + public void unsupportedCallback() { + assertThatThrownBy(() -> { + new CallbackHandlerImpl("tester", "secret").handle(new Callback[] {mock(Callback.class)}); + }) + .isInstanceOf(UnsupportedCallbackException.class); } } diff --git a/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/ContextHelperTest.java b/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/ContextHelperTest.java index 4e5c7ae2423..ffaf9613aed 100644 --- a/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/ContextHelperTest.java +++ b/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/ContextHelperTest.java @@ -23,6 +23,7 @@ import javax.naming.Context; import javax.naming.NamingException; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; @@ -36,11 +37,12 @@ public class ContextHelperTest { ContextHelper.closeQuietly(context); } - @Test(expected = NamingException.class) + @Test public void shouldNotSwallow() throws Exception { Context context = mock(Context.class); doThrow(new NamingException()).when(context).close(); - ContextHelper.close(context, false); + assertThatThrownBy(() -> ContextHelper.close(context, false)) + .isInstanceOf(NamingException.class); } @Test diff --git a/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/LdapSearchTest.java b/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/LdapSearchTest.java index a19500cfb8c..367f0759a8b 100644 --- a/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/LdapSearchTest.java +++ b/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/LdapSearchTest.java @@ -26,21 +26,16 @@ import javax.naming.NamingException; import javax.naming.directory.SearchControls; import org.junit.BeforeClass; import org.junit.ClassRule; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.auth.ldap.server.LdapServer; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class LdapSearchTest { @ClassRule public static LdapServer server = new LdapServer("/users.example.org.ldif"); - - @Rule - public ExpectedException thrown = ExpectedException.none(); - private static Map contextFactories; @BeforeClass @@ -63,9 +58,10 @@ public class LdapSearchTest { assertThat(search.getReturningAttributes()).isEqualTo(new String[] {"objectClass"}); assertThat(search.toString()).isEqualTo("LdapSearch{baseDn=dc=example,dc=org, scope=subtree, request=(objectClass={0}), parameters=[inetOrgPerson], attributes=[objectClass]}"); assertThat(enumerationToArrayList(search.find()).size()).isEqualTo(3); - thrown.expect(NamingException.class); - thrown.expectMessage("Non unique result for " + search.toString()); - search.findUnique(); + + assertThatThrownBy(() -> search.findUnique()) + .isInstanceOf(NamingException.class) + .hasMessage("Non unique result for " + search.toString()); } @Test diff --git a/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/LdapSettingsManagerTest.java b/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/LdapSettingsManagerTest.java index f9927028341..446b09b3462 100644 --- a/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/LdapSettingsManagerTest.java +++ b/server/sonar-auth-ldap/src/test/java/org/sonar/auth/ldap/LdapSettingsManagerTest.java @@ -21,30 +21,25 @@ package org.sonar.auth.ldap; import java.util.Arrays; import java.util.Collections; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.config.internal.MapSettings; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.auth.ldap.LdapAutodiscovery.LdapSrvRecord; public class LdapSettingsManagerTest { - - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void shouldFailWhenNoLdapUrl() { MapSettings settings = generateMultipleLdapSettingsWithUserAndGroupMapping(); settings.removeProperty("ldap.example.url"); LdapSettingsManager settingsManager = new LdapSettingsManager(settings.asConfig(), new LdapAutodiscovery()); - thrown.expect(LdapException.class); - thrown.expectMessage("The property 'ldap.example.url' property is empty while it is mandatory."); - settingsManager.getContextFactories(); + assertThatThrownBy(settingsManager::getContextFactories) + .isInstanceOf(LdapException.class) + .hasMessage("The property 'ldap.example.url' property is empty while it is mandatory."); } @Test @@ -53,11 +48,9 @@ public class LdapSettingsManagerTest { settings.setProperty("ldap.url", "ldap://foo"); LdapSettingsManager settingsManager = new LdapSettingsManager(settings.asConfig(), new LdapAutodiscovery()); - thrown.expect(LdapException.class); - thrown - .expectMessage( - "When defining multiple LDAP servers with the property 'ldap.servers', all LDAP properties must be linked to one of those servers. Please remove properties like 'ldap.url', 'ldap.realm', ..."); - settingsManager.getContextFactories(); + assertThatThrownBy(settingsManager::getContextFactories) + .isInstanceOf(LdapException.class) + .hasMessage("When defining multiple LDAP servers with the property 'ldap.servers', all LDAP properties must be linked to one of those servers. Please remove properties like 'ldap.url', 'ldap.realm', ..."); } @Test @@ -98,10 +91,9 @@ public class LdapSettingsManagerTest { LdapSettingsManager settingsManager = new LdapSettingsManager( generateAutodiscoverSettings().asConfig(), ldapAutodiscovery); - thrown.expect(LdapException.class); - thrown.expectMessage("The property 'ldap.url' is empty and SonarQube is not able to auto-discover any LDAP server."); - - settingsManager.getContextFactories(); + assertThatThrownBy(settingsManager::getContextFactories) + .isInstanceOf(LdapException.class) + .hasMessage("The property 'ldap.url' is empty and SonarQube is not able to auto-discover any LDAP server."); } /** @@ -139,9 +131,9 @@ public class LdapSettingsManagerTest { LdapSettingsManager settingsManager = new LdapSettingsManager( new MapSettings().asConfig(), new LdapAutodiscovery()); - thrown.expect(LdapException.class); - thrown.expectMessage("The property 'ldap.url' is empty and no realm configured to try auto-discovery."); - settingsManager.getContextFactories(); + assertThatThrownBy(settingsManager::getContextFactories) + .isInstanceOf(LdapException.class) + .hasMessage("The property 'ldap.url' is empty and no realm configured to try auto-discovery."); } private MapSettings generateMultipleLdapSettingsWithUserAndGroupMapping() { diff --git a/server/sonar-auth-saml/src/test/java/org/sonar/auth/saml/SamlSettingsTest.java b/server/sonar-auth-saml/src/test/java/org/sonar/auth/saml/SamlSettingsTest.java index df260abe40f..89d35c7554c 100644 --- a/server/sonar-auth-saml/src/test/java/org/sonar/auth/saml/SamlSettingsTest.java +++ b/server/sonar-auth-saml/src/test/java/org/sonar/auth/saml/SamlSettingsTest.java @@ -22,21 +22,18 @@ package org.sonar.auth.saml; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.api.config.PropertyDefinitions; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.utils.System2; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; @RunWith(DataProviderRunner.class) public class SamlSettingsTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private MapSettings settings = new MapSettings(new PropertyDefinitions(System2.INSTANCE, SamlSettings.definitions())); @@ -177,42 +174,37 @@ public class SamlSettingsTest { @Test public void fail_to_get_provider_id_when_null() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Provider ID is missing"); - - underTest.getProviderId(); + assertThatThrownBy(() -> underTest.getProviderId()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Provider ID is missing"); } @Test public void fail_to_get_login_url_when_null() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Login URL is missing"); - - underTest.getLoginUrl(); + assertThatThrownBy(() -> underTest.getLoginUrl()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Login URL is missing"); } @Test public void fail_to_get_certificate_when_null() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Certificate is missing"); - - underTest.getCertificate(); + assertThatThrownBy(() -> underTest.getCertificate()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Certificate is missing"); } @Test public void fail_to_get_user_login_attribute_when_null() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("User login attribute is missing"); - - underTest.getUserLogin(); + assertThatThrownBy(() -> underTest.getUserLogin()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("User login attribute is missing"); } @Test public void fail_to_get_user_name_attribute_when_null() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("User name attribute is missing"); - - underTest.getUserName(); + assertThatThrownBy(() -> underTest.getUserName()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("User name attribute is missing"); } private void initAllSettings() { diff --git a/server/sonar-ce-common/src/test/java/org/sonar/ce/queue/CeQueueImplTest.java b/server/sonar-ce-common/src/test/java/org/sonar/ce/queue/CeQueueImplTest.java index 7dcc3045805..3eb566dfeef 100644 --- a/server/sonar-ce-common/src/test/java/org/sonar/ce/queue/CeQueueImplTest.java +++ b/server/sonar-ce-common/src/test/java/org/sonar/ce/queue/CeQueueImplTest.java @@ -27,7 +27,6 @@ import java.util.stream.IntStream; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.impl.utils.TestSystem2; import org.sonar.api.utils.System2; import org.sonar.ce.queue.CeTaskSubmit.Component; @@ -50,9 +49,9 @@ import static java.util.Arrays.asList; import static java.util.Collections.emptyMap; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; 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.assertj.core.api.Assertions.tuple; -import static org.hamcrest.Matchers.startsWith; import static org.sonar.ce.queue.CeQueue.SubmitOption.UNIQUE_QUEUE_PER_MAIN_COMPONENT; public class CeQueueImplTest { @@ -62,8 +61,6 @@ public class CeQueueImplTest { private System2 system2 = new TestSystem2().setNow(NOW); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester db = DbTester.create(system2); @@ -395,10 +392,9 @@ public class CeQueueImplTest { submit(CeTaskTypes.REPORT, newComponent(randomAlphabetic(11))); CeQueueDto ceQueueDto = db.getDbClient().ceQueueDao().peek(session, WORKER_UUID, false, false).get(); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage(startsWith("Task is in progress and can't be canceled")); - - underTest.cancel(db.getSession(), ceQueueDto); + assertThatThrownBy(() -> underTest.cancel(db.getSession(), ceQueueDto)) + .isInstanceOf(IllegalStateException.class) + .hasMessageStartingWith("Task is in progress and can't be canceled"); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/analysis/AnalysisImplTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/analysis/AnalysisImplTest.java index 8ce8e4ff11b..c4492e01a06 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/analysis/AnalysisImplTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/analysis/AnalysisImplTest.java @@ -19,16 +19,13 @@ */ package org.sonar.ce.task.projectanalysis.analysis; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class AnalysisImplTest { - @Rule - public ExpectedException thrown = ExpectedException.none(); private static final long ID = 10; private static final String UUID = "uuid "; @@ -47,22 +44,16 @@ public class AnalysisImplTest { @Test public void fail_with_NPE_when_building_snapshot_without_uuid() { - thrown.expect(NullPointerException.class); - thrown.expectMessage("uuid cannot be null"); - - new Analysis.Builder() - .setCreatedAt(CREATED_AT) - .build(); + assertThatThrownBy(() -> new Analysis.Builder().setCreatedAt(CREATED_AT).build()) + .isInstanceOf(NullPointerException.class) + .hasMessage("uuid cannot be null"); } @Test public void fail_with_NPE_when_building_snapshot_without_created_at() { - thrown.expect(NullPointerException.class); - thrown.expectMessage("createdAt cannot be null"); - - new Analysis.Builder() - .setUuid(UUID) - .build(); + assertThatThrownBy(() -> new Analysis.Builder().setUuid(UUID).build()) + .isInstanceOf(NullPointerException.class) + .hasMessage("createdAt cannot be null"); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/analysis/AnalysisMetadataHolderImplTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/analysis/AnalysisMetadataHolderImplTest.java index b54802b48ec..80432155a24 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/analysis/AnalysisMetadataHolderImplTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/analysis/AnalysisMetadataHolderImplTest.java @@ -26,9 +26,7 @@ import java.util.Arrays; import java.util.Optional; import java.util.stream.Stream; import javax.annotation.Nullable; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.ce.task.projectanalysis.component.DefaultBranchImpl; import org.sonar.core.platform.PlatformEditionProvider; @@ -36,6 +34,7 @@ import org.sonar.db.component.BranchType; import org.sonar.server.project.Project; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.core.platform.EditionProvider.Edition; @@ -50,28 +49,24 @@ public class AnalysisMetadataHolderImplTest { .build(); private static final long SOME_DATE = 10000000L; - @Rule - public ExpectedException expectedException = ExpectedException.none(); private final PlatformEditionProvider editionProvider = mock(PlatformEditionProvider.class); private final AnalysisMetadataHolderImpl underTest = new AnalysisMetadataHolderImpl(editionProvider); @Test public void setUuid_throws_NPE_is_parameter_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("Analysis uuid can't be null"); - - underTest.setUuid(null); + assertThatThrownBy(() -> underTest.setUuid(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("Analysis uuid can't be null"); } @Test public void setUuid_throws_ISE_if_called_twice() { underTest.setUuid("org1"); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Analysis uuid has already been set"); - - underTest.setUuid("org1"); + assertThatThrownBy(() -> underTest.setUuid("org1")) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Analysis uuid has already been set"); } @Test @@ -84,10 +79,9 @@ public class AnalysisMetadataHolderImplTest { @Test public void getAnalysisDate_throws_ISE_when_holder_is_not_initialized() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Analysis date has not been set"); - - new AnalysisMetadataHolderImpl(editionProvider).getAnalysisDate(); + assertThatThrownBy(() -> new AnalysisMetadataHolderImpl(editionProvider).getAnalysisDate()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Analysis date has not been set"); } @Test @@ -95,10 +89,9 @@ public class AnalysisMetadataHolderImplTest { AnalysisMetadataHolderImpl underTest = new AnalysisMetadataHolderImpl(editionProvider); underTest.setAnalysisDate(SOME_DATE); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Analysis date has already been set"); - - underTest.setAnalysisDate(SOME_DATE); + assertThatThrownBy(() -> underTest.setAnalysisDate(SOME_DATE)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Analysis date has already been set"); } @Test @@ -111,10 +104,9 @@ public class AnalysisMetadataHolderImplTest { @Test public void getForkDate_throws_ISE_when_holder_is_not_initialized() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Fork date has not been set"); - - new AnalysisMetadataHolderImpl(editionProvider).getForkDate(); + assertThatThrownBy(() -> new AnalysisMetadataHolderImpl(editionProvider).getForkDate()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Fork date has not been set"); } @Test @@ -122,10 +114,9 @@ public class AnalysisMetadataHolderImplTest { AnalysisMetadataHolderImpl underTest = new AnalysisMetadataHolderImpl(editionProvider); underTest.setForkDate(SOME_DATE); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Fork date has already been set"); - - underTest.setForkDate(SOME_DATE); + assertThatThrownBy(() -> underTest.setForkDate(SOME_DATE)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Fork date has already been set"); } @Test @@ -158,18 +149,16 @@ public class AnalysisMetadataHolderImplTest { @Test public void isFirstAnalysis_throws_ISE_when_base_project_snapshot_is_not_set() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Base project snapshot has not been set"); - - new AnalysisMetadataHolderImpl(editionProvider).isFirstAnalysis(); + assertThatThrownBy(() -> new AnalysisMetadataHolderImpl(editionProvider).isFirstAnalysis()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Base project snapshot has not been set"); } @Test public void baseProjectSnapshot_throws_ISE_when_base_project_snapshot_is_not_set() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Base project snapshot has not been set"); - - new AnalysisMetadataHolderImpl(editionProvider).getBaseAnalysis(); + assertThatThrownBy(() -> new AnalysisMetadataHolderImpl(editionProvider).getBaseAnalysis()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Base project snapshot has not been set"); } @Test @@ -177,9 +166,9 @@ public class AnalysisMetadataHolderImplTest { AnalysisMetadataHolderImpl underTest = new AnalysisMetadataHolderImpl(editionProvider); underTest.setBaseAnalysis(baseProjectAnalysis); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Base project snapshot has already been set"); - underTest.setBaseAnalysis(baseProjectAnalysis); + assertThatThrownBy(() -> underTest.setBaseAnalysis(baseProjectAnalysis)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Base project snapshot has already been set"); } @Test @@ -202,10 +191,9 @@ public class AnalysisMetadataHolderImplTest { @Test public void isCrossProjectDuplicationEnabled_throws_ISE_when_holder_is_not_initialized() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Cross project duplication flag has not been set"); - - new AnalysisMetadataHolderImpl(editionProvider).isCrossProjectDuplicationEnabled(); + assertThatThrownBy(() -> new AnalysisMetadataHolderImpl(editionProvider).isCrossProjectDuplicationEnabled()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Cross project duplication flag has not been set"); } @Test @@ -213,9 +201,9 @@ public class AnalysisMetadataHolderImplTest { AnalysisMetadataHolderImpl underTest = new AnalysisMetadataHolderImpl(editionProvider); underTest.setCrossProjectDuplicationEnabled(true); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Cross project duplication flag has already been set"); - underTest.setCrossProjectDuplicationEnabled(false); + assertThatThrownBy(() -> underTest.setCrossProjectDuplicationEnabled(false)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Cross project duplication flag has already been set"); } @Test @@ -229,10 +217,9 @@ public class AnalysisMetadataHolderImplTest { @Test public void getBranch_throws_ISE_when_holder_is_not_initialized() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Branch has not been set"); - - new AnalysisMetadataHolderImpl(editionProvider).getBranch(); + assertThatThrownBy(() -> new AnalysisMetadataHolderImpl(editionProvider).getBranch()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Branch has not been set"); } @Test @@ -240,9 +227,9 @@ public class AnalysisMetadataHolderImplTest { AnalysisMetadataHolderImpl underTest = new AnalysisMetadataHolderImpl(editionProvider); underTest.setBranch(new DefaultBranchImpl()); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Branch has already been set"); - underTest.setBranch(new DefaultBranchImpl()); + assertThatThrownBy(() -> underTest.setBranch(new DefaultBranchImpl())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Branch has already been set"); } @Test @@ -278,10 +265,9 @@ public class AnalysisMetadataHolderImplTest { when(branch.isMain()).thenReturn(false); AnalysisMetadataHolderImpl underTest = new AnalysisMetadataHolderImpl(editionProvider); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Branches and Pull Requests are not supported in Community Edition"); - - underTest.setBranch(branch); + assertThatThrownBy(() -> underTest.setBranch(branch)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Branches and Pull Requests are not supported in Community Edition"); } @DataProvider @@ -314,10 +300,9 @@ public class AnalysisMetadataHolderImplTest { @Test public void getPullRequestId_throws_ISE_when_holder_is_not_initialized() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Pull request key has not been set"); - - new AnalysisMetadataHolderImpl(editionProvider).getPullRequestKey(); + assertThatThrownBy(() -> new AnalysisMetadataHolderImpl(editionProvider).getPullRequestKey()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Pull request key has not been set"); } @Test @@ -325,9 +310,9 @@ public class AnalysisMetadataHolderImplTest { AnalysisMetadataHolderImpl underTest = new AnalysisMetadataHolderImpl(editionProvider); underTest.setPullRequestKey("pr-123"); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Pull request key has already been set"); - underTest.setPullRequestKey("pr-234"); + assertThatThrownBy(() -> underTest.setPullRequestKey("pr-234")) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Pull request key has already been set"); } @Test @@ -342,10 +327,9 @@ public class AnalysisMetadataHolderImplTest { @Test public void getProject_throws_ISE_when_holder_is_not_initialized() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Project has not been set"); - - new AnalysisMetadataHolderImpl(editionProvider).getProject(); + assertThatThrownBy(() -> new AnalysisMetadataHolderImpl(editionProvider).getProject()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Project has not been set"); } @Test @@ -353,10 +337,9 @@ public class AnalysisMetadataHolderImplTest { AnalysisMetadataHolderImpl underTest = new AnalysisMetadataHolderImpl(editionProvider); underTest.setProject(Project.from(newPrivateProjectDto())); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Project has already been set"); - - underTest.setProject(Project.from(newPrivateProjectDto())); + assertThatThrownBy(() -> underTest.setProject(Project.from(newPrivateProjectDto()))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Project has already been set"); } @Test @@ -370,10 +353,9 @@ public class AnalysisMetadataHolderImplTest { @Test public void getRootComponentRef_throws_ISE_when_holder_is_not_initialized() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Root component ref has not been set"); - - new AnalysisMetadataHolderImpl(editionProvider).getRootComponentRef(); + assertThatThrownBy(() -> new AnalysisMetadataHolderImpl(editionProvider).getRootComponentRef()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Root component ref has not been set"); } @Test @@ -381,9 +363,9 @@ public class AnalysisMetadataHolderImplTest { AnalysisMetadataHolderImpl underTest = new AnalysisMetadataHolderImpl(editionProvider); underTest.setRootComponentRef(10); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Root component ref has already been set"); - underTest.setRootComponentRef(9); + assertThatThrownBy(() -> underTest.setRootComponentRef(9)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Root component ref has already been set"); } @Test @@ -402,9 +384,9 @@ public class AnalysisMetadataHolderImplTest { AnalysisMetadataHolderImpl underTest = new AnalysisMetadataHolderImpl(editionProvider); underTest.setScmRevision("bd56dab"); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("ScmRevision has already been set"); - underTest.setScmRevision("bd56dab"); + assertThatThrownBy(() -> underTest.setScmRevision("bd56dab")) + .isInstanceOf(IllegalStateException.class) + .hasMessage("ScmRevision has already been set"); } @Test @@ -455,9 +437,8 @@ public class AnalysisMetadataHolderImplTest { @Test public void isBranch_throws_ISE_for_not_initialized_branch() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Branch has not been set"); - - underTest.isBranch(); + assertThatThrownBy(underTest::isBranch) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Branch has not been set"); } } diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/measurecomputer/ComponentImplTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/measurecomputer/ComponentImplTest.java index de93a76fc57..e31f23ee65c 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/measurecomputer/ComponentImplTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/measurecomputer/ComponentImplTest.java @@ -19,18 +19,14 @@ */ package org.sonar.ce.task.projectanalysis.api.measurecomputer; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.ce.measure.Component; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class ComponentImplTest { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void create_project() { ComponentImpl component = new ComponentImpl("Project", Component.Type.PROJECT, null); @@ -59,43 +55,40 @@ public class ComponentImplTest { @Test public void fail_with_ISE_when_calling_get_file_attributes_on_not_file() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Only component of type FILE have a FileAttributes object"); - - ComponentImpl component = new ComponentImpl("Project", Component.Type.PROJECT, null); - component.getFileAttributes(); + assertThatThrownBy(() -> { + ComponentImpl component = new ComponentImpl("Project", Component.Type.PROJECT, null); + component.getFileAttributes(); + }) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Only component of type FILE have a FileAttributes object"); } @Test public void fail_with_IAE_when_trying_to_create_a_file_without_file_attributes() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("omponent of type FILE must have a FileAttributes object"); - - new ComponentImpl("File", Component.Type.FILE, null); + assertThatThrownBy(() -> new ComponentImpl("File", Component.Type.FILE, null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("omponent of type FILE must have a FileAttributes object"); } @Test public void fail_with_IAE_when_trying_to_create_not_a_file_with_file_attributes() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Only component of type FILE have a FileAttributes object"); - - new ComponentImpl("Project", Component.Type.PROJECT, new ComponentImpl.FileAttributesImpl(null, true)); + assertThatThrownBy(() -> new ComponentImpl("Project", Component.Type.PROJECT, new ComponentImpl.FileAttributesImpl(null, true))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Only component of type FILE have a FileAttributes object"); } @Test public void fail_with_NPE_when_creating_component_without_key() { - thrown.expect(NullPointerException.class); - thrown.expectMessage("Key cannot be null"); - - new ComponentImpl(null, Component.Type.PROJECT, null); + assertThatThrownBy(() -> new ComponentImpl(null, Component.Type.PROJECT, null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("Key cannot be null"); } @Test public void fail_with_NPE_when_creating_component_without_type() { - thrown.expect(NullPointerException.class); - thrown.expectMessage("Type cannot be null"); - - new ComponentImpl("Project", null, null); + assertThatThrownBy(() -> new ComponentImpl("Project", null, null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("Type cannot be null"); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/measurecomputer/MeasureComputerContextImplTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/measurecomputer/MeasureComputerContextImplTest.java index b14be751b27..63c9458539c 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/measurecomputer/MeasureComputerContextImplTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/measurecomputer/MeasureComputerContextImplTest.java @@ -25,7 +25,6 @@ import java.util.List; import java.util.Optional; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.ce.measure.Component; import org.sonar.api.ce.measure.MeasureComputer; import org.sonar.api.config.internal.MapSettings; @@ -43,6 +42,7 @@ import org.sonar.ce.task.projectanalysis.metric.MetricRepositoryRule; import org.sonar.core.issue.DefaultIssue; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.api.measures.CoreMetrics.COMMENT_LINES_KEY; @@ -52,8 +52,6 @@ import static org.sonar.ce.task.projectanalysis.measure.Measure.newMeasureBuilde public class MeasureComputerContextImplTest { - @Rule - public ExpectedException thrown = ExpectedException.none(); private static final String INT_METRIC_KEY = "int_metric_key"; private static final String DOUBLE_METRIC_KEY = "double_metric_key"; @@ -134,11 +132,12 @@ public class MeasureComputerContextImplTest { @Test public void fail_with_IAE_when_get_measure_is_called_on_metric_not_in_input_list() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Only metrics in [another metric] can be used to load measures"); - - MeasureComputerContextImpl underTest = newContext(PROJECT_REF, "another metric", "debt"); - underTest.getMeasure(NCLOC_KEY); + assertThatThrownBy(() -> { + MeasureComputerContextImpl underTest = newContext(PROJECT_REF, "another metric", "debt"); + underTest.getMeasure(NCLOC_KEY); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Only metrics in [another metric] can be used to load measures"); } @Test @@ -171,11 +170,12 @@ public class MeasureComputerContextImplTest { @Test public void fail_with_IAE_when_get_children_measures_is_called_on_metric_not_in_input_list() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Only metrics in [another metric] can be used to load measures"); - - MeasureComputerContextImpl underTest = newContext(PROJECT_REF, "another metric", "debt"); - underTest.getChildrenMeasures(NCLOC_KEY); + assertThatThrownBy(() -> { + MeasureComputerContextImpl underTest = newContext(PROJECT_REF, "another metric", "debt"); + underTest.getChildrenMeasures(NCLOC_KEY); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Only metrics in [another metric] can be used to load measures"); } @Test @@ -230,22 +230,23 @@ public class MeasureComputerContextImplTest { @Test public void fail_with_IAE_when_add_measure_is_called_on_metric_not_in_output_list() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Only metrics in [int_metric_key] can be used to add measures. Metric 'double_metric_key' is not allowed."); - - MeasureComputerContextImpl underTest = newContext(PROJECT_REF, NCLOC_KEY, INT_METRIC_KEY); - underTest.addMeasure(DOUBLE_METRIC_KEY, 10); + assertThatThrownBy(() -> { + MeasureComputerContextImpl underTest = newContext(PROJECT_REF, NCLOC_KEY, INT_METRIC_KEY); + underTest.addMeasure(DOUBLE_METRIC_KEY, 10); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Only metrics in [int_metric_key] can be used to add measures. Metric 'double_metric_key' is not allowed."); } @Test public void fail_with_unsupported_operation_when_adding_measure_that_already_exists() { - thrown.expect(UnsupportedOperationException.class); - thrown.expectMessage("A measure on metric 'int_metric_key' already exists on component 'fileKey'"); - - measureRepository.addRawMeasure(FILE_1_REF, INT_METRIC_KEY, newMeasureBuilder().create(20)); - - MeasureComputerContextImpl underTest = newContext(FILE_1_REF, NCLOC_KEY, INT_METRIC_KEY); - underTest.addMeasure(INT_METRIC_KEY, 10); + assertThatThrownBy(() -> { + measureRepository.addRawMeasure(FILE_1_REF, INT_METRIC_KEY, newMeasureBuilder().create(20)); + MeasureComputerContextImpl underTest = newContext(FILE_1_REF, NCLOC_KEY, INT_METRIC_KEY); + underTest.addMeasure(INT_METRIC_KEY, 10); + }) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessage("A measure on metric 'int_metric_key' already exists on component 'fileKey'"); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/measurecomputer/MeasureComputerDefinitionImplTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/measurecomputer/MeasureComputerDefinitionImplTest.java index 5d2f612fc2f..f1ecae09d98 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/measurecomputer/MeasureComputerDefinitionImplTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/measurecomputer/MeasureComputerDefinitionImplTest.java @@ -19,17 +19,14 @@ */ package org.sonar.ce.task.projectanalysis.api.measurecomputer; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.ce.measure.MeasureComputer; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class MeasureComputerDefinitionImplTest { - @Rule - public ExpectedException thrown = ExpectedException.none(); @Test public void build_measure_computer_definition() { @@ -78,62 +75,68 @@ public class MeasureComputerDefinitionImplTest { @Test public void fail_with_NPE_when_null_input_metrics() { - thrown.expect(NullPointerException.class); - thrown.expectMessage("Input metrics cannot be null"); - - new MeasureComputerDefinitionImpl.BuilderImpl() - .setInputMetrics((String[]) null) - .setOutputMetrics("comment_density_1", "comment_density_2"); + assertThatThrownBy(() -> { + new MeasureComputerDefinitionImpl.BuilderImpl() + .setInputMetrics((String[]) null) + .setOutputMetrics("comment_density_1", "comment_density_2"); + }) + .isInstanceOf(NullPointerException.class) + .hasMessage("Input metrics cannot be null"); } @Test public void fail_with_NPE_when_one_input_metric_is_null() { - thrown.expect(NullPointerException.class); - thrown.expectMessage("Null metric is not allowed"); - - new MeasureComputerDefinitionImpl.BuilderImpl() - .setInputMetrics("ncloc", null) - .setOutputMetrics("comment_density_1", "comment_density_2"); + assertThatThrownBy(() -> { + new MeasureComputerDefinitionImpl.BuilderImpl() + .setInputMetrics("ncloc", null) + .setOutputMetrics("comment_density_1", "comment_density_2"); + }) + .isInstanceOf(NullPointerException.class) + .hasMessage("Null metric is not allowed"); } @Test public void fail_with_NPE_when_no_output_metrics() { - thrown.expect(NullPointerException.class); - thrown.expectMessage("Output metrics cannot be null"); - - new MeasureComputerDefinitionImpl.BuilderImpl() - .setInputMetrics("ncloc", "comment") - .build(); + assertThatThrownBy(() -> { + new MeasureComputerDefinitionImpl.BuilderImpl() + .setInputMetrics("ncloc", "comment") + .build(); + }) + .isInstanceOf(NullPointerException.class) + .hasMessage("Output metrics cannot be null"); } @Test public void fail_with_NPE_when_null_output_metrics() { - thrown.expect(NullPointerException.class); - thrown.expectMessage("Output metrics cannot be null"); - - new MeasureComputerDefinitionImpl.BuilderImpl() - .setInputMetrics("ncloc", "comment") - .setOutputMetrics((String[]) null); + assertThatThrownBy(() -> { + new MeasureComputerDefinitionImpl.BuilderImpl() + .setInputMetrics("ncloc", "comment") + .setOutputMetrics((String[]) null); + }) + .isInstanceOf(NullPointerException.class) + .hasMessage("Output metrics cannot be null"); } @Test public void fail_with_NPE_when_one_output_metric_is_null() { - thrown.expect(NullPointerException.class); - thrown.expectMessage("Null metric is not allowed"); - - new MeasureComputerDefinitionImpl.BuilderImpl() - .setInputMetrics("ncloc", "comment") - .setOutputMetrics("comment_density_1", null); + assertThatThrownBy(() -> { + new MeasureComputerDefinitionImpl.BuilderImpl() + .setInputMetrics("ncloc", "comment") + .setOutputMetrics("comment_density_1", null); + }) + .isInstanceOf(NullPointerException.class) + .hasMessage("Null metric is not allowed"); } @Test public void fail_with_IAE_with_empty_output_metrics() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("At least one output metric must be defined"); - - new MeasureComputerDefinitionImpl.BuilderImpl() - .setInputMetrics("ncloc", "comment") - .setOutputMetrics(); + assertThatThrownBy(() -> { + new MeasureComputerDefinitionImpl.BuilderImpl() + .setInputMetrics("ncloc", "comment") + .setOutputMetrics(); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("At least one output metric must be defined"); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/measurecomputer/MeasureImplTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/measurecomputer/MeasureImplTest.java index a3db5b53c5a..623fc2f6735 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/measurecomputer/MeasureImplTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/measurecomputer/MeasureImplTest.java @@ -19,17 +19,14 @@ */ package org.sonar.ce.task.projectanalysis.api.measurecomputer; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.ce.task.projectanalysis.measure.Measure; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class MeasureImplTest { - @Rule - public ExpectedException thrown = ExpectedException.none(); @Test public void get_int_value() { @@ -39,11 +36,12 @@ public class MeasureImplTest { @Test public void fail_with_ISE_when_not_int_value() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Value can not be converted to int because current value type is a DOUBLE"); - - MeasureImpl measure = new MeasureImpl(Measure.newMeasureBuilder().create(1d, 1)); - measure.getIntValue(); + assertThatThrownBy(() -> { + MeasureImpl measure = new MeasureImpl(Measure.newMeasureBuilder().create(1d, 1)); + measure.getIntValue(); + }) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Value can not be converted to int because current value type is a DOUBLE"); } @Test @@ -54,11 +52,12 @@ public class MeasureImplTest { @Test public void fail_with_ISE_when_not_double_value() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Value can not be converted to double because current value type is a INT"); - - MeasureImpl measure = new MeasureImpl(Measure.newMeasureBuilder().create(1)); - measure.getDoubleValue(); + assertThatThrownBy(() -> { + MeasureImpl measure = new MeasureImpl(Measure.newMeasureBuilder().create(1)); + measure.getDoubleValue(); + }) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Value can not be converted to double because current value type is a INT"); } @Test @@ -69,11 +68,12 @@ public class MeasureImplTest { @Test public void fail_with_ISE_when_not_long_value() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Value can not be converted to long because current value type is a STRING"); - - MeasureImpl measure = new MeasureImpl(Measure.newMeasureBuilder().create("value")); - measure.getLongValue(); + assertThatThrownBy(() -> { + MeasureImpl measure = new MeasureImpl(Measure.newMeasureBuilder().create("value")); + measure.getLongValue(); + }) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Value can not be converted to long because current value type is a STRING"); } @Test @@ -84,11 +84,12 @@ public class MeasureImplTest { @Test public void fail_with_ISE_when_not_string_value() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Value can not be converted to string because current value type is a LONG"); - - MeasureImpl measure = new MeasureImpl(Measure.newMeasureBuilder().create(1L)); - measure.getStringValue(); + assertThatThrownBy(() -> { + MeasureImpl measure = new MeasureImpl(Measure.newMeasureBuilder().create(1L)); + measure.getStringValue(); + }) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Value can not be converted to string because current value type is a LONG"); } @Test @@ -99,34 +100,32 @@ public class MeasureImplTest { @Test public void fail_with_ISE_when_not_boolean_value() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Value can not be converted to boolean because current value type is a DOUBLE"); - - MeasureImpl measure = new MeasureImpl(Measure.newMeasureBuilder().create(1d, 1)); - measure.getBooleanValue(); + assertThatThrownBy(() -> { + MeasureImpl measure = new MeasureImpl(Measure.newMeasureBuilder().create(1d, 1)); + measure.getBooleanValue(); + }) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Value can not be converted to boolean because current value type is a DOUBLE"); } @Test public void fail_with_ISE_when_creating_measure_with_no_value() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Only following types are allowed [BOOLEAN, INT, LONG, DOUBLE, STRING]"); - - new MeasureImpl(Measure.newMeasureBuilder().createNoValue()); + assertThatThrownBy(() -> new MeasureImpl(Measure.newMeasureBuilder().createNoValue())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Only following types are allowed [BOOLEAN, INT, LONG, DOUBLE, STRING]"); } @Test public void fail_with_ISE_when_creating_measure_with_not_allowed_value() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Only following types are allowed [BOOLEAN, INT, LONG, DOUBLE, STRING]"); - - new MeasureImpl(Measure.newMeasureBuilder().create(Measure.Level.ERROR)); + assertThatThrownBy(() -> new MeasureImpl(Measure.newMeasureBuilder().create(Measure.Level.ERROR))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Only following types are allowed [BOOLEAN, INT, LONG, DOUBLE, STRING]"); } @Test public void fail_with_NPE_when_creating_measure_with_null_measure() { - thrown.expect(NullPointerException.class); - thrown.expectMessage("Measure couldn't be null"); - - new MeasureImpl(null); + assertThatThrownBy(() -> new MeasureImpl(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("Measure couldn't be null"); } } diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/posttask/CeTaskImplTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/posttask/CeTaskImplTest.java index 64befba9afc..6fb8cd070e0 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/posttask/CeTaskImplTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/posttask/CeTaskImplTest.java @@ -19,33 +19,27 @@ */ package org.sonar.ce.task.projectanalysis.api.posttask; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.ce.posttask.CeTask; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class CeTaskImplTest { private static final String SOME_ID = "some id"; - @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Test public void constructor_throws_NPE_if_id_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("id can not be null"); - - new CeTaskImpl(null, CeTask.Status.SUCCESS); + assertThatThrownBy(() -> new CeTaskImpl(null, CeTask.Status.SUCCESS)) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("id can not be null"); } @Test public void constructor_throws_NPE_if_status_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("status can not be null"); - - new CeTaskImpl(SOME_ID, null); + assertThatThrownBy(() -> new CeTaskImpl(SOME_ID, null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("status can not be null"); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/posttask/ConditionImplTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/posttask/ConditionImplTest.java index 04c07f65710..49a2eaf329c 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/posttask/ConditionImplTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/posttask/ConditionImplTest.java @@ -22,13 +22,12 @@ package org.sonar.ce.task.projectanalysis.api.posttask; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.api.ce.posttask.QualityGate; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; @RunWith(DataProviderRunner.class) public class ConditionImplTest { @@ -36,8 +35,6 @@ public class ConditionImplTest { private static final String ERROR_THRESHOLD = "error threshold"; private static final String VALUE = "value"; - @Rule - public ExpectedException expectedException = ExpectedException.none(); private ConditionImpl.Builder builder = ConditionImpl.newBuilder() .setStatus(QualityGate.EvaluationStatus.OK) @@ -50,40 +47,36 @@ public class ConditionImplTest { public void build_throws_NPE_if_status_is_null() { builder.setStatus(null); - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("status can not be null"); - - builder.build(); + assertThatThrownBy(() -> builder.build()) + .isInstanceOf(NullPointerException.class) + .hasMessage("status can not be null"); } @Test public void build_throws_NPE_if_metricKey_is_null() { builder.setMetricKey(null); - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("metricKey can not be null"); - - builder.build(); + assertThatThrownBy(() -> builder.build()) + .isInstanceOf(NullPointerException.class) + .hasMessage("metricKey can not be null"); } @Test public void build_throws_NPE_if_operator_is_null() { builder.setOperator(null); - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("operator can not be null"); - - builder.build(); + assertThatThrownBy(() -> builder.build()) + .isInstanceOf(NullPointerException.class) + .hasMessage("operator can not be null"); } @Test public void build_throws_NPE_if_error_threshold_is_null() { builder.setErrorThreshold(null); - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("errorThreshold can not be null"); - - builder.build(); + assertThatThrownBy(() -> builder.build()) + .isInstanceOf(NullPointerException.class) + .hasMessage("errorThreshold can not be null"); } @Test @@ -91,10 +84,9 @@ public class ConditionImplTest { builder.setStatus(QualityGate.EvaluationStatus.NO_VALUE).setValue(null); ConditionImpl condition = builder.build(); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("There is no value when status is NO_VALUE"); - - condition.getValue(); + assertThatThrownBy(condition::getValue) + .isInstanceOf(IllegalStateException.class) + .hasMessage("There is no value when status is NO_VALUE"); } @DataProvider @@ -116,20 +108,18 @@ public class ConditionImplTest { builder.setStatus(status) .setValue(null); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("value can not be null when status is not NO_VALUE"); - - builder.build(); + assertThatThrownBy(() -> builder.build()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("value can not be null when status is not NO_VALUE"); } @Test public void build_throws_IAE_if_value_is_not_null_but_status_is_NO_VALUE() { builder.setStatus(QualityGate.EvaluationStatus.NO_VALUE); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("value must be null when status is NO_VALUE"); - - builder.build(); + assertThatThrownBy(() -> builder.build()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("value must be null when status is NO_VALUE"); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/posttask/ConditionToConditionTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/posttask/ConditionToConditionTest.java index bdcd20e1b76..120fbb13c48 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/posttask/ConditionToConditionTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/posttask/ConditionToConditionTest.java @@ -24,9 +24,7 @@ import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.Collections; import java.util.Map; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.api.ce.posttask.QualityGate; import org.sonar.ce.task.projectanalysis.metric.Metric; @@ -35,6 +33,7 @@ import org.sonar.ce.task.projectanalysis.qualitygate.ConditionStatus; import static com.google.common.collect.ImmutableMap.of; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -46,26 +45,22 @@ public class ConditionToConditionTest { private static final String SOME_VALUE = "some value"; private static final ConditionStatus SOME_CONDITION_STATUS = ConditionStatus.create(ConditionStatus.EvaluationStatus.OK, SOME_VALUE); private static final Condition SOME_CONDITION = new Condition(newMetric(METRIC_KEY), Condition.Operator.LESS_THAN.getDbValue(), ERROR_THRESHOLD); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void apply_throws_NPE_if_Condition_argument_is_null() { ConditionToCondition underTest = new ConditionToCondition(NO_STATUS_PER_CONDITIONS); - expectedException.expect(NullPointerException.class); - - underTest.apply(null); + assertThatThrownBy(() -> underTest.apply(null)) + .isInstanceOf(NullPointerException.class); } @Test public void apply_throws_ISE_if_there_is_no_ConditionStatus_for_Condition_argument() { ConditionToCondition underTest = new ConditionToCondition(NO_STATUS_PER_CONDITIONS); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Missing ConditionStatus for condition on metric key " + METRIC_KEY); - - underTest.apply(SOME_CONDITION); + assertThatThrownBy(() -> underTest.apply(SOME_CONDITION)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Missing ConditionStatus for condition on metric key " + METRIC_KEY); } @Test @@ -112,10 +107,9 @@ public class ConditionToConditionTest { QualityGate.Condition res = underTest.apply(otherCondition); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("There is no value when status is NO_VALUE"); - - res.getValue(); + assertThatThrownBy(res::getValue) + .isInstanceOf(IllegalStateException.class) + .hasMessage("There is no value when status is NO_VALUE"); } @DataProvider diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/posttask/ProjectImplTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/posttask/ProjectImplTest.java index 0ef7b2e789c..cf820975992 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/posttask/ProjectImplTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/posttask/ProjectImplTest.java @@ -19,42 +19,36 @@ */ package org.sonar.ce.task.projectanalysis.api.posttask; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class ProjectImplTest { private static final String SOME_UUID = "some uuid"; private static final String SOME_KEY = "some key"; private static final String SOME_NAME = "some name"; - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void constructor_throws_NPE_if_uuid_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("uuid can not be null"); - - new ProjectImpl(null, SOME_KEY, SOME_NAME); + assertThatThrownBy(() -> new ProjectImpl(null, SOME_KEY, SOME_NAME)) + .isInstanceOf(NullPointerException.class) + .hasMessage("uuid can not be null"); } @Test public void constructor_throws_NPE_if_key_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("key can not be null"); - - new ProjectImpl(SOME_UUID, null, SOME_NAME); + assertThatThrownBy(() -> new ProjectImpl(SOME_UUID, null, SOME_NAME)) + .isInstanceOf(NullPointerException.class) + .hasMessage("key can not be null"); } @Test public void constructor_throws_NPE_if_name_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("name can not be null"); - - new ProjectImpl(SOME_UUID, SOME_KEY, null); + assertThatThrownBy(() -> new ProjectImpl(SOME_UUID, SOME_KEY, null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("name can not be null"); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/posttask/QualityGateImplTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/posttask/QualityGateImplTest.java index cfef66040a3..b95cf7083b1 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/posttask/QualityGateImplTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/posttask/QualityGateImplTest.java @@ -22,12 +22,11 @@ package org.sonar.ce.task.projectanalysis.api.posttask; import com.google.common.collect.ImmutableList; import java.util.Collections; import java.util.List; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.ce.posttask.QualityGate; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -36,42 +35,36 @@ public class QualityGateImplTest { private static final String SOME_NAME = "some name"; private static final QualityGate.Status SOME_STATUS = QualityGate.Status.OK; - @Rule - public ExpectedException expectedException = ExpectedException.none(); private QualityGate.Condition condition = mock(QualityGate.Condition.class); private QualityGateImpl underTest = new QualityGateImpl(SOME_ID, SOME_NAME, SOME_STATUS, ImmutableList.of(condition)); @Test public void constructor_throws_NPE_if_id_argument_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("id can not be null"); - - new QualityGateImpl(null, SOME_NAME, SOME_STATUS, Collections.emptyList()); + assertThatThrownBy(() -> new QualityGateImpl(null, SOME_NAME, SOME_STATUS, Collections.emptyList())) + .isInstanceOf(NullPointerException.class) + .hasMessage("id can not be null"); } @Test public void constructor_throws_NPE_if_name_argument_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("name can not be null"); - - new QualityGateImpl(SOME_ID, null, SOME_STATUS, Collections.emptyList()); + assertThatThrownBy(() -> new QualityGateImpl(SOME_ID, null, SOME_STATUS, Collections.emptyList())) + .isInstanceOf(NullPointerException.class) + .hasMessage("name can not be null"); } @Test public void constructor_throws_NPE_if_status_argument_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("status can not be null"); - - new QualityGateImpl(SOME_ID, SOME_NAME, null, Collections.emptyList()); + assertThatThrownBy(() -> new QualityGateImpl(SOME_ID, SOME_NAME, null, Collections.emptyList())) + .isInstanceOf(NullPointerException.class) + .hasMessage("status can not be null"); } @Test public void constructor_throws_NPE_if_conditions_argument_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("conditions can not be null"); - - new QualityGateImpl(SOME_ID, SOME_NAME, SOME_STATUS, null); + assertThatThrownBy(() -> new QualityGateImpl(SOME_ID, SOME_NAME, SOME_STATUS, null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("conditions can not be null"); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/batch/BatchReportDirectoryHolderImplTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/batch/BatchReportDirectoryHolderImplTest.java index 7d3ca0a43ce..96cf99feba5 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/batch/BatchReportDirectoryHolderImplTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/batch/BatchReportDirectoryHolderImplTest.java @@ -23,12 +23,14 @@ import java.io.File; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class BatchReportDirectoryHolderImplTest { - @Test(expected = IllegalStateException.class) + @Test public void getDirectory_throws_ISE_if_holder_is_empty() { - new BatchReportDirectoryHolderImpl().getDirectory(); + assertThatThrownBy(() -> new BatchReportDirectoryHolderImpl().getDirectory()) + .isInstanceOf(IllegalStateException.class); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/batch/BatchReportReaderImplTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/batch/BatchReportReaderImplTest.java index 60e65e5d8fe..26c90347541 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/batch/BatchReportReaderImplTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/batch/BatchReportReaderImplTest.java @@ -33,6 +33,7 @@ import org.sonar.scanner.protocol.output.ScannerReportWriter; import static com.google.common.collect.ImmutableList.of; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class BatchReportReaderImplTest { private static final int COMPONENT_REF = 1; @@ -61,9 +62,10 @@ public class BatchReportReaderImplTest { writer = new ScannerReportWriter(holder.getDirectory()); } - @Test(expected = IllegalStateException.class) + @Test public void readMetadata_throws_ISE_if_no_metadata() { - underTest.readMetadata(); + assertThatThrownBy(() -> underTest.readMetadata()) + .isInstanceOf(IllegalStateException.class); } @Test @@ -134,9 +136,10 @@ public class BatchReportReaderImplTest { assertThat(underTest.readChangesets(COMPONENT_REF)).isNotSameAs(underTest.readChangesets(COMPONENT_REF)); } - @Test(expected = IllegalStateException.class) + @Test public void readComponent_throws_ISE_if_file_does_not_exist() { - underTest.readComponent(COMPONENT_REF); + assertThatThrownBy(() -> underTest.readComponent(COMPONENT_REF)) + .isInstanceOf(IllegalStateException.class); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/BranchLoaderTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/BranchLoaderTest.java index 2c585def1c3..60eb0e98dee 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/BranchLoaderTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/BranchLoaderTest.java @@ -21,7 +21,6 @@ package org.sonar.ce.task.projectanalysis.component; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.utils.MessageException; import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule; import org.sonar.ce.task.projectanalysis.analysis.Branch; @@ -29,13 +28,12 @@ import org.sonar.db.component.BranchDto; import org.sonar.scanner.protocol.output.ScannerReport; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; public class BranchLoaderTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public AnalysisMetadataHolderRule metadataHolder = new AnalysisMetadataHolderRule(); @@ -46,10 +44,9 @@ public class BranchLoaderTest { .setBranchName("bar") .build(); - expectedException.expect(MessageException.class); - expectedException.expectMessage("Current edition does not support branch feature"); - - new BranchLoader(metadataHolder).load(metadata); + assertThatThrownBy(() -> new BranchLoader(metadataHolder).load(metadata)) + .isInstanceOf(MessageException.class) + .hasMessage("Current edition does not support branch feature"); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ComponentImplTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ComponentImplTest.java index c900fc9708c..3e8255d4f7b 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ComponentImplTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ComponentImplTest.java @@ -21,14 +21,13 @@ package org.sonar.ce.task.projectanalysis.component; import java.util.Arrays; import java.util.Collections; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.ce.task.projectanalysis.component.Component.Status; import static com.google.common.base.Strings.repeat; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.fail; import static org.sonar.ce.task.projectanalysis.component.Component.Type.FILE; import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT; @@ -39,8 +38,6 @@ public class ComponentImplTest { static final String KEY = "KEY"; static final String UUID = "UUID"; - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void verify_key_uuid_and_name() { @@ -53,56 +50,51 @@ public class ComponentImplTest { @Test public void builder_throws_NPE_if_component_arg_is_Null() { - expectedException.expect(NullPointerException.class); - - builder(null); + assertThatThrownBy(() -> builder(null)) + .isInstanceOf(NullPointerException.class); } @Test public void builder_throws_NPE_if_status_arg_is_Null() { - expectedException.expect(NullPointerException.class); - - builder(FILE).setStatus(null); + assertThatThrownBy(() -> builder(FILE).setStatus(null)) + .isInstanceOf(NullPointerException.class); } @Test public void builder_throws_NPE_if_status_is_Null() { - expectedException.expect(NullPointerException.class); - - builder(Component.Type.DIRECTORY) - .setName("DIR") - .setDbKey(KEY) - .setUuid(UUID) - .setReportAttributes(ReportAttributes.newBuilder(1).build()) - .build(); + assertThatThrownBy(() -> { + builder(Component.Type.DIRECTORY) + .setName("DIR") + .setDbKey(KEY) + .setUuid(UUID) + .setReportAttributes(ReportAttributes.newBuilder(1).build()) + .build(); + }) + .isInstanceOf(NullPointerException.class); } @Test public void set_key_throws_NPE_if_component_arg_is_Null() { - expectedException.expect(NullPointerException.class); - - builder(FILE).setUuid(null); + assertThatThrownBy(() -> builder(FILE).setUuid(null)) + .isInstanceOf(NullPointerException.class); } @Test public void set_uuid_throws_NPE_if_component_arg_is_Null() { - expectedException.expect(NullPointerException.class); - - builder(FILE).setDbKey(null); + assertThatThrownBy(() -> builder(FILE).setDbKey(null)) + .isInstanceOf(NullPointerException.class); } @Test public void build_without_key_throws_NPE_if_component_arg_is_Null() { - expectedException.expect(NullPointerException.class); - - builder(FILE).setUuid("ABCD").build(); + assertThatThrownBy(() -> builder(FILE).setUuid("ABCD").build()) + .isInstanceOf(NullPointerException.class); } @Test public void build_without_uuid_throws_NPE_if_component_arg_is_Null() { - expectedException.expect(NullPointerException.class); - - builder(FILE).setDbKey(KEY).build(); + assertThatThrownBy(() -> builder(FILE).setDbKey(KEY).build()) + .isInstanceOf(NullPointerException.class); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ComponentTreeBuilderTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ComponentTreeBuilderTest.java index 6d0a4de70d8..a5a0a810b24 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ComponentTreeBuilderTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ComponentTreeBuilderTest.java @@ -31,7 +31,6 @@ import java.util.function.Function; import java.util.function.UnaryOperator; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.ExternalResource; import org.sonar.ce.task.projectanalysis.analysis.Branch; import org.sonar.core.component.ComponentKeys; @@ -41,6 +40,7 @@ import org.sonar.server.project.Project; import static com.google.common.base.Preconditions.checkArgument; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -64,8 +64,6 @@ public class ComponentTreeBuilderTest { private static final ProjectAttributes SOME_PROJECT_ATTRIBUTES = new ProjectAttributes( randomAlphabetic(20), new Random().nextBoolean() ? null : randomAlphabetic(12), "1def5123"); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public ScannerComponentProvider scannerComponentProvider = new ScannerComponentProvider(); @@ -717,10 +715,9 @@ public class ComponentTreeBuilderTest { .setType(FILE) .setProjectRelativePath("src/js/Foo.js")); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("File 'src/js/Foo.js' has no line"); - - call(project); + assertThatThrownBy(() -> call(project)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("File 'src/js/Foo.js' has no line"); } @Test @@ -736,10 +733,9 @@ public class ComponentTreeBuilderTest { .setProjectRelativePath("src/js/Foo.js") .setLines(0)); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("File 'src/js/Foo.js' has no line"); - - call(project); + assertThatThrownBy(() -> call(project)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("File 'src/js/Foo.js' has no line"); } @Test @@ -755,10 +751,9 @@ public class ComponentTreeBuilderTest { .setProjectRelativePath("src/js/Foo.js") .setLines(-10)); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("File 'src/js/Foo.js' has no line"); - - call(project); + assertThatThrownBy(() -> call(project)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("File 'src/js/Foo.js' has no line"); } private static class ScannerComponentProvider extends ExternalResource implements Function { diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/CrawlerDepthLimitTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/CrawlerDepthLimitTest.java index c0759e88777..8e8ae53aab7 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/CrawlerDepthLimitTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/CrawlerDepthLimitTest.java @@ -28,9 +28,7 @@ import java.util.Arrays; import java.util.Set; import java.util.stream.Collectors; import javax.annotation.Nullable; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.ce.task.projectanalysis.component.Component.Type; @@ -40,14 +38,13 @@ import static com.google.common.base.Predicates.not; import static com.google.common.collect.FluentIterable.from; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; @RunWith(DataProviderRunner.class) public class CrawlerDepthLimitTest { private static final Set REPORT_TYPES = Arrays.stream(Type.values()).filter(Type::isReportType).collect(Collectors.toSet()); private static final Set VIEWS_TYPES = Arrays.stream(Type.values()).filter(Type::isViewsType).collect(Collectors.toSet()); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void PROJECT_isSameAs_only_PROJECT_type() { @@ -283,10 +280,9 @@ public class CrawlerDepthLimitTest { @Test @UseDataProvider("viewsTypes") public void reportMaxDepth_throws_IAE_if_type_is_views(Type viewsType) { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("A Report max depth must be a report type"); - - CrawlerDepthLimit.reportMaxDepth(viewsType); + assertThatThrownBy(() -> CrawlerDepthLimit.reportMaxDepth(viewsType)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("A Report max depth must be a report type"); } @Test @@ -298,10 +294,9 @@ public class CrawlerDepthLimitTest { @Test @UseDataProvider("reportTypes") public void withViewsMaxDepth_throws_IAE_if_type_is_report(Type reportType) { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("A Views max depth must be a views type"); - - CrawlerDepthLimit.reportMaxDepth(reportType).withViewsMaxDepth(reportType); + assertThatThrownBy(() -> CrawlerDepthLimit.reportMaxDepth(reportType).withViewsMaxDepth(reportType)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("A Views max depth must be a views type"); } @DataProvider diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/DefaultBranchImplTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/DefaultBranchImplTest.java index fc6e1d79560..b557fba135e 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/DefaultBranchImplTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/DefaultBranchImplTest.java @@ -19,9 +19,7 @@ */ package org.sonar.ce.task.projectanalysis.component; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.db.component.BranchDto; import org.sonar.db.component.BranchType; import org.sonar.scanner.protocol.output.ScannerReport; @@ -33,8 +31,6 @@ public class DefaultBranchImplTest { private static final String PROJECT_KEY = "P"; private static final ScannerReport.Component FILE = ScannerReport.Component.newBuilder().setType(ComponentType.FILE).setProjectRelativePath("src/Foo.js").build(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void default_branch_represents_the_project() { diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/DisabledComponentsHolderImplTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/DisabledComponentsHolderImplTest.java index 03e307afb33..08eade4925d 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/DisabledComponentsHolderImplTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/DisabledComponentsHolderImplTest.java @@ -20,16 +20,13 @@ package org.sonar.ce.task.projectanalysis.component; import com.google.common.collect.ImmutableSet; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class DisabledComponentsHolderImplTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); DisabledComponentsHolderImpl underTest = new DisabledComponentsHolderImpl(); @@ -44,15 +41,15 @@ public class DisabledComponentsHolderImplTest { public void setUuids_fails_if_called_twice() { underTest.setUuids(ImmutableSet.of("U1", "U2")); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("UUIDs have already been set in repository"); - underTest.setUuids(ImmutableSet.of("U1", "U2")); + assertThatThrownBy(() -> underTest.setUuids(ImmutableSet.of("U1", "U2"))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("UUIDs have already been set in repository"); } @Test public void getUuids_fails_if_not_initialized() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("UUIDs have not been set in repository"); - underTest.getUuids(); + assertThatThrownBy(() -> underTest.getUuids()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("UUIDs have not been set in repository"); } } diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/FileAttributesTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/FileAttributesTest.java index 1469f478619..0425ae4f20b 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/FileAttributesTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/FileAttributesTest.java @@ -19,16 +19,13 @@ */ package org.sonar.ce.task.projectanalysis.component; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class FileAttributesTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void create_production_file() { @@ -59,16 +56,16 @@ public class FileAttributesTest { @Test public void fail_with_IAE_when_lines_is_0() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Number of lines must be greater than zero"); - new FileAttributes(true, "java", 0); + assertThatThrownBy(() -> new FileAttributes(true, "java", 0)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Number of lines must be greater than zero"); } @Test public void fail_with_IAE_when_lines_is_less_than_0() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Number of lines must be greater than zero"); - new FileAttributes(true, "java", -10); + assertThatThrownBy(() -> new FileAttributes(true, "java", -10)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Number of lines must be greater than zero"); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ProjectPersisterTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ProjectPersisterTest.java index d510e4f8e0f..95ebea61b74 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ProjectPersisterTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ProjectPersisterTest.java @@ -22,7 +22,6 @@ package org.sonar.ce.task.projectanalysis.component; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.impl.utils.TestSystem2; import org.sonar.api.utils.System2; import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule; @@ -32,7 +31,6 @@ import org.sonar.db.project.ProjectDto; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT; @@ -53,8 +51,6 @@ public class ProjectPersisterTest { public DbTester dbTester = DbTester.create(System2.INSTANCE); @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule(); - @Rule - public ExpectedException exception = ExpectedException.none(); public TestSystem2 system2 = new TestSystem2(); private ProjectPersister underTest = new ProjectPersister(dbTester.getDbClient(), treeRootHolder, system2); diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ReportPostOrderDepthTraversalTypeAwareCrawlerTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ReportPostOrderDepthTraversalTypeAwareCrawlerTest.java index c40edc2cb81..6835661d12e 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ReportPostOrderDepthTraversalTypeAwareCrawlerTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ReportPostOrderDepthTraversalTypeAwareCrawlerTest.java @@ -22,6 +22,7 @@ package org.sonar.ce.task.projectanalysis.component; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.ce.task.projectanalysis.component.Component.Type.DIRECTORY; import static org.sonar.ce.task.projectanalysis.component.Component.Type.FILE; import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT; @@ -41,9 +42,10 @@ public class ReportPostOrderDepthTraversalTypeAwareCrawlerTest { private final DepthTraversalTypeAwareCrawler directoryCrawler = new DepthTraversalTypeAwareCrawler(directoryVisitor); private final DepthTraversalTypeAwareCrawler fileCrawler = new DepthTraversalTypeAwareCrawler(fileVisitor); - @Test(expected = NullPointerException.class) + @Test public void visit_null_Component_throws_NPE() { - fileCrawler.visit(null); + assertThatThrownBy(() -> fileCrawler.visit(null)) + .isInstanceOf(NullPointerException.class); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ReportPreOrderDepthTraversalTypeAwareCrawlerTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ReportPreOrderDepthTraversalTypeAwareCrawlerTest.java index eb523c5e5ed..dbb76cc31bd 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ReportPreOrderDepthTraversalTypeAwareCrawlerTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ReportPreOrderDepthTraversalTypeAwareCrawlerTest.java @@ -22,6 +22,7 @@ package org.sonar.ce.task.projectanalysis.component; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.ce.task.projectanalysis.component.Component.Type.DIRECTORY; import static org.sonar.ce.task.projectanalysis.component.Component.Type.FILE; import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT; @@ -42,9 +43,10 @@ public class ReportPreOrderDepthTraversalTypeAwareCrawlerTest { private final DepthTraversalTypeAwareCrawler directoryCrawler = new DepthTraversalTypeAwareCrawler(directoryVisitor); private final DepthTraversalTypeAwareCrawler fileCrawler = new DepthTraversalTypeAwareCrawler(fileVisitor); - @Test(expected = NullPointerException.class) + @Test public void visit_null_Component_throws_NPE() { - fileCrawler.visit(null); + assertThatThrownBy(() -> fileCrawler.visit(null)) + .isInstanceOf(NullPointerException.class); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ReportVisitorsCrawlerTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ReportVisitorsCrawlerTest.java index c5f7ca473b6..63f6b3277d9 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ReportVisitorsCrawlerTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ReportVisitorsCrawlerTest.java @@ -20,12 +20,11 @@ package org.sonar.ce.task.projectanalysis.component; import java.util.Arrays; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.InOrder; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.inOrder; @@ -38,8 +37,6 @@ import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order public class ReportVisitorsCrawlerTest { - @Rule - public ExpectedException thrown = ExpectedException.none(); private static final Component FILE_5 = component(FILE, 5); private static final Component DIRECTORY_4 = component(DIRECTORY, 4, FILE_5); @@ -104,21 +101,23 @@ public class ReportVisitorsCrawlerTest { @Test public void fail_with_IAE_when_visitor_is_not_path_aware_or_type_aware() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Only TypeAwareVisitor and PathAwareVisitor can be used"); - - ComponentVisitor componentVisitor = new ComponentVisitor() { - @Override - public Order getOrder() { - return PRE_ORDER; - } + assertThatThrownBy(() -> { + ComponentVisitor componentVisitor = new ComponentVisitor() { + @Override + public Order getOrder() { + return PRE_ORDER; + } - @Override - public CrawlerDepthLimit getMaxDepth() { + @Override + public CrawlerDepthLimit getMaxDepth() { return CrawlerDepthLimit.FILE; } - }; - new VisitorsCrawler(Arrays.asList(componentVisitor)); + }; + + new VisitorsCrawler(Arrays.asList(componentVisitor)); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Only TypeAwareVisitor and PathAwareVisitor can be used"); } private static Component component(final Component.Type type, final int ref, final Component... children) { diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ReportVisitorsCrawlerWithPostOrderTypeAwareVisitorTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ReportVisitorsCrawlerWithPostOrderTypeAwareVisitorTest.java index 5b33b594cf8..7048a634c72 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ReportVisitorsCrawlerWithPostOrderTypeAwareVisitorTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ReportVisitorsCrawlerWithPostOrderTypeAwareVisitorTest.java @@ -23,6 +23,7 @@ import java.util.Arrays; import org.junit.Test; import org.mockito.InOrder; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; @@ -46,10 +47,12 @@ public class ReportVisitorsCrawlerWithPostOrderTypeAwareVisitorTest { }); private final InOrder inOrder = inOrder(spyProjectVisitor, spyDirectoryVisitor, spyFileVisitor); - @Test(expected = NullPointerException.class) + @Test public void visit_null_Component_throws_NPE() { VisitorsCrawler underTest = newVisitorsCrawler(spyFileVisitor); - underTest.visit(null); + + assertThatThrownBy(() -> underTest.visit(null)) + .isInstanceOf(NullPointerException.class); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ReportVisitorsCrawlerWithPreOrderTypeAwareVisitorTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ReportVisitorsCrawlerWithPreOrderTypeAwareVisitorTest.java index 6b707b1a8c4..923f77fba0b 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ReportVisitorsCrawlerWithPreOrderTypeAwareVisitorTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ReportVisitorsCrawlerWithPreOrderTypeAwareVisitorTest.java @@ -23,6 +23,7 @@ import java.util.Arrays; import org.junit.Test; import org.mockito.InOrder; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; @@ -30,7 +31,6 @@ import static org.sonar.ce.task.projectanalysis.component.Component.Type.DIRECTO import static org.sonar.ce.task.projectanalysis.component.Component.Type.FILE; import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT; import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.PRE_ORDER; - public class ReportVisitorsCrawlerWithPreOrderTypeAwareVisitorTest { private static final Component FILE_5 = component(FILE, 5); @@ -46,10 +46,12 @@ public class ReportVisitorsCrawlerWithPreOrderTypeAwareVisitorTest { }); private final InOrder inOrder = inOrder(spyProjectVisitor, spyDirectoryVisitor, spyFileVisitor); - @Test(expected = NullPointerException.class) + @Test public void visit_null_Component_throws_NPE() { VisitorsCrawler underTest = newVisitorsCrawler(spyFileVisitor); - underTest.visit(null); + + assertThatThrownBy(() -> underTest.visit(null)) + .isInstanceOf(NullPointerException.class); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/TreeRootHolderImplTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/TreeRootHolderImplTest.java index 266591781d6..0c2c430e324 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/TreeRootHolderImplTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/TreeRootHolderImplTest.java @@ -19,11 +19,10 @@ */ package org.sonar.ce.task.projectanalysis.component; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.ce.task.projectanalysis.component.Component.Type.DIRECTORY; import static org.sonar.ce.task.projectanalysis.component.Component.Type.FILE; import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT; @@ -46,49 +45,43 @@ public class TreeRootHolderImplTest { .build()) .build(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); - private TreeRootHolderImpl underTest = new TreeRootHolderImpl(); @Test public void setRoots_throws_NPE_if_root_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("root can not be null"); - - underTest.setRoots(null, DUMB_PROJECT); + assertThatThrownBy(() -> underTest.setRoots(null, DUMB_PROJECT)) + .isInstanceOf(NullPointerException.class) + .hasMessage("root can not be null"); } @Test public void setRoots_throws_NPE_if_reportRoot_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("root can not be null"); - - underTest.setRoots(DUMB_PROJECT, null); + assertThatThrownBy(() -> underTest.setRoots(DUMB_PROJECT, null)) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("root can not be null"); } @Test public void setRoot_throws_ISE_when_called_twice() { underTest.setRoots(DUMB_PROJECT, DUMB_PROJECT); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("root can not be set twice in holder"); - - underTest.setRoots(null, DUMB_PROJECT); + assertThatThrownBy(() -> underTest.setRoots(null, DUMB_PROJECT)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("root can not be set twice in holder"); } @Test public void getRoot_throws_ISE_if_root_has_not_been_set_yet() { - expectNotInitialized_ISE(); - - underTest.getRoot(); + assertThatThrownBy(() -> underTest.getRoot()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Holder has not been initialized yet"); } @Test public void getComponentByRef_throws_ISE_if_root_has_not_been_set() { - expectNotInitialized_ISE(); - - underTest.getComponentByRef(12); + assertThatThrownBy(() -> underTest.getComponentByRef(12)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Holder has not been initialized yet"); } @Test @@ -113,10 +106,9 @@ public class TreeRootHolderImplTest { public void getComponentByRef_throws_IAE_if_holder_does_not_contain_specified_component() { underTest.setRoots(SOME_REPORT_COMPONENT_TREE, DUMB_PROJECT); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Component with ref '6' can't be found"); - - underTest.getComponentByRef(6); + assertThatThrownBy(() -> underTest.getComponentByRef(6)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Component with ref '6' can't be found"); } @Test @@ -130,10 +122,9 @@ public class TreeRootHolderImplTest { public void getComponentByRef_throws_IAE_if_holder_contains_View_tree() { underTest.setRoots(SOME_VIEWS_COMPONENT_TREE, DUMB_PROJECT); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Component with ref '1' can't be found"); - - underTest.getComponentByRef(1); + assertThatThrownBy(() -> underTest.getComponentByRef(1)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Component with ref '1' can't be found"); } @Test @@ -150,9 +141,9 @@ public class TreeRootHolderImplTest { @Test public void getSize_throws_ISE_if_not_initialized() { - expectNotInitialized_ISE(); - - underTest.getSize(); + assertThatThrownBy(() -> underTest.getSize()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Holder has not been initialized yet"); } @Test @@ -160,10 +151,4 @@ public class TreeRootHolderImplTest { underTest.setRoots(SOME_REPORT_COMPONENT_TREE, DUMB_PROJECT); assertThat(underTest.getSize()).isEqualTo(3); } - - private void expectNotInitialized_ISE() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Holder has not been initialized yet"); - } - } diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/TypeAwareVisitorAdapterTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/TypeAwareVisitorAdapterTest.java index 2c4edca52ce..3263d4648af 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/TypeAwareVisitorAdapterTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/TypeAwareVisitorAdapterTest.java @@ -21,13 +21,17 @@ package org.sonar.ce.task.projectanalysis.component; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.POST_ORDER; public class TypeAwareVisitorAdapterTest { - @Test(expected = NullPointerException.class) + @Test public void non_null_max_depth_fast_fail() { - new TypeAwareVisitorAdapter(null, POST_ORDER) { - }; + assertThatThrownBy(() -> { + new TypeAwareVisitorAdapter(null, POST_ORDER) { + }; + }) + .isInstanceOf(NullPointerException.class); } } diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ViewAttributesTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ViewAttributesTest.java index 5fbc18e1e51..9f4def1250f 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ViewAttributesTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ViewAttributesTest.java @@ -19,18 +19,15 @@ */ package org.sonar.ce.task.projectanalysis.component; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.resources.Qualifiers; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.ce.task.projectanalysis.component.ViewAttributes.Type.APPLICATION; import static org.sonar.ce.task.projectanalysis.component.ViewAttributes.Type.PORTFOLIO; public class ViewAttributesTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private ViewAttributes underTest; @@ -58,9 +55,8 @@ public class ViewAttributesTest { @Test public void fail_if_unknown_view_qualifier() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Qualifier 'TRK' is not supported"); - - ViewAttributes.Type.fromQualifier(Qualifiers.PROJECT); + assertThatThrownBy(() -> ViewAttributes.Type.fromQualifier(Qualifiers.PROJECT)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Qualifier 'TRK' is not supported"); } } diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ViewsPostOrderDepthTraversalTypeAwareCrawlerTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ViewsPostOrderDepthTraversalTypeAwareCrawlerTest.java index 8e7dc268107..b532c300531 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ViewsPostOrderDepthTraversalTypeAwareCrawlerTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ViewsPostOrderDepthTraversalTypeAwareCrawlerTest.java @@ -22,6 +22,7 @@ package org.sonar.ce.task.projectanalysis.component; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT_VIEW; import static org.sonar.ce.task.projectanalysis.component.Component.Type.SUBVIEW; import static org.sonar.ce.task.projectanalysis.component.Component.Type.VIEW; @@ -44,9 +45,10 @@ public class ViewsPostOrderDepthTraversalTypeAwareCrawlerTest { private final DepthTraversalTypeAwareCrawler subViewCrawler = new DepthTraversalTypeAwareCrawler(subViewVisitor); private final DepthTraversalTypeAwareCrawler projectViewCrawler = new DepthTraversalTypeAwareCrawler(projectViewVisitor); - @Test(expected = NullPointerException.class) + @Test public void visit_null_Component_throws_NPE() { - projectViewCrawler.visit(null); + assertThatThrownBy(() -> projectViewCrawler.visit(null)) + .isInstanceOf(NullPointerException.class); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ViewsPreOrderDepthTraversalTypeAwareCrawlerTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ViewsPreOrderDepthTraversalTypeAwareCrawlerTest.java index 2eae8fd5e6d..024daaac85a 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ViewsPreOrderDepthTraversalTypeAwareCrawlerTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ViewsPreOrderDepthTraversalTypeAwareCrawlerTest.java @@ -22,6 +22,7 @@ package org.sonar.ce.task.projectanalysis.component; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT_VIEW; import static org.sonar.ce.task.projectanalysis.component.Component.Type.SUBVIEW; import static org.sonar.ce.task.projectanalysis.component.Component.Type.VIEW; @@ -44,9 +45,10 @@ public class ViewsPreOrderDepthTraversalTypeAwareCrawlerTest { private final DepthTraversalTypeAwareCrawler subViewCrawler = new DepthTraversalTypeAwareCrawler(subViewVisitor); private final DepthTraversalTypeAwareCrawler projectViewCrawler = new DepthTraversalTypeAwareCrawler(projectViewVisitor); - @Test(expected = NullPointerException.class) + @Test public void visit_null_Component_throws_NPE() { - projectViewCrawler.visit(null); + assertThatThrownBy(() -> projectViewCrawler.visit(null)) + .isInstanceOf(NullPointerException.class); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ViewsVisitorsCrawlerTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ViewsVisitorsCrawlerTest.java index 01648900842..c1f593bb211 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ViewsVisitorsCrawlerTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ViewsVisitorsCrawlerTest.java @@ -20,12 +20,11 @@ package org.sonar.ce.task.projectanalysis.component; import java.util.Arrays; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.InOrder; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.inOrder; @@ -38,8 +37,6 @@ import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order public class ViewsVisitorsCrawlerTest { - @Rule - public ExpectedException thrown = ExpectedException.none(); private static final Component PROJECT_VIEW_5 = component(PROJECT_VIEW, 5); private static final Component SUBVIEW_4 = component(SUBVIEW, 4, PROJECT_VIEW_5); @@ -104,21 +101,23 @@ public class ViewsVisitorsCrawlerTest { @Test public void fail_with_IAE_when_visitor_is_not_path_aware_or_type_aware() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Only TypeAwareVisitor and PathAwareVisitor can be used"); - - ComponentVisitor componentVisitor = new ComponentVisitor() { - @Override - public Order getOrder() { - return PRE_ORDER; - } - - @Override - public CrawlerDepthLimit getMaxDepth() { - return CrawlerDepthLimit.PROJECT_VIEW; - } - }; - new VisitorsCrawler(Arrays.asList(componentVisitor)); + assertThatThrownBy(() -> { + ComponentVisitor componentVisitor = new ComponentVisitor() { + @Override + public Order getOrder() { + return PRE_ORDER; + } + + @Override + public CrawlerDepthLimit getMaxDepth() { + return CrawlerDepthLimit.PROJECT_VIEW; + } + }; + + new VisitorsCrawler(Arrays.asList(componentVisitor)); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Only TypeAwareVisitor and PathAwareVisitor can be used"); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ViewsVisitorsCrawlerWithPostOrderTypeAwareVisitorTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ViewsVisitorsCrawlerWithPostOrderTypeAwareVisitorTest.java index 7963ffbec09..0bb6e0b7f08 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ViewsVisitorsCrawlerWithPostOrderTypeAwareVisitorTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ViewsVisitorsCrawlerWithPostOrderTypeAwareVisitorTest.java @@ -30,7 +30,7 @@ import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT import static org.sonar.ce.task.projectanalysis.component.Component.Type.SUBVIEW; import static org.sonar.ce.task.projectanalysis.component.Component.Type.VIEW; import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.POST_ORDER; - +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class ViewsVisitorsCrawlerWithPostOrderTypeAwareVisitorTest { private static final Component PROJECT_VIEW_5 = component(PROJECT_VIEW, 5); @@ -48,10 +48,11 @@ public class ViewsVisitorsCrawlerWithPostOrderTypeAwareVisitorTest { }); private final InOrder inOrder = inOrder(spyViewVisitor, spySubViewVisitor, spyProjectViewVisitor); - @Test(expected = NullPointerException.class) + @Test public void visit_null_Component_throws_NPE() { VisitorsCrawler underTest = newVisitorsCrawler(spyProjectViewVisitor); - underTest.visit(null); + assertThatThrownBy(() -> underTest.visit(null)) + .isInstanceOf(NullPointerException.class); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ViewsVisitorsCrawlerWithPreOrderTypeAwareVisitorTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ViewsVisitorsCrawlerWithPreOrderTypeAwareVisitorTest.java index cb12aec8f5a..31945a6f3e5 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ViewsVisitorsCrawlerWithPreOrderTypeAwareVisitorTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ViewsVisitorsCrawlerWithPreOrderTypeAwareVisitorTest.java @@ -23,6 +23,7 @@ import java.util.Arrays; import org.junit.Test; import org.mockito.InOrder; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; @@ -48,10 +49,12 @@ public class ViewsVisitorsCrawlerWithPreOrderTypeAwareVisitorTest { }); private final InOrder inOrder = inOrder(spyViewVisitor, spySubViewVisitor, spyProjectViewVisitor); - @Test(expected = NullPointerException.class) + @Test public void visit_null_Component_throws_NPE() { VisitorsCrawler underTest = newVisitorsCrawler(spyProjectViewVisitor); - underTest.visit(null); + + assertThatThrownBy(() -> underTest.visit(null)) + .isInstanceOf(NullPointerException.class); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/duplication/CrossProjectDuplicateTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/duplication/CrossProjectDuplicateTest.java index e41a69a83dd..938c97c9fe4 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/duplication/CrossProjectDuplicateTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/duplication/CrossProjectDuplicateTest.java @@ -19,33 +19,27 @@ */ package org.sonar.ce.task.projectanalysis.duplication; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class CrossProjectDuplicateTest { private static final String FILE_KEY_1 = "file key 1"; private static final String FILE_KEY_2 = "file key 2"; - @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Test public void constructors_throws_NPE_if_fileKey_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("fileKey can not be null"); - - new CrossProjectDuplicate(null, new TextBlock(1, 1)); + assertThatThrownBy(() -> new CrossProjectDuplicate(null, new TextBlock(1, 1))) + .isInstanceOf(NullPointerException.class) + .hasMessage("fileKey can not be null"); } @Test public void constructors_throws_NPE_if_textBlock_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("textBlock of duplicate can not be null"); - - new CrossProjectDuplicate(FILE_KEY_1, null); + assertThatThrownBy(() -> new CrossProjectDuplicate(FILE_KEY_1, null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("textBlock of duplicate can not be null"); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/duplication/CrossProjectDuplicationStatusHolderImplTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/duplication/CrossProjectDuplicationStatusHolderImplTest.java index e91c7fd4285..be7cc89319d 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/duplication/CrossProjectDuplicationStatusHolderImplTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/duplication/CrossProjectDuplicationStatusHolderImplTest.java @@ -21,20 +21,18 @@ package org.sonar.ce.task.projectanalysis.duplication; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.utils.log.LogTester; import org.sonar.api.utils.log.LoggerLevel; import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule; import org.sonar.ce.task.projectanalysis.analysis.Branch; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class CrossProjectDuplicationStatusHolderImplTest { - @Rule - public ExpectedException thrown = ExpectedException.none(); @Rule public LogTester logTester = new LogTester(); @Rule @@ -101,10 +99,9 @@ public class CrossProjectDuplicationStatusHolderImplTest { @Test public void isEnabled_throws_ISE_when_start_have_not_been_called_before() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Flag hasn't been initialized, the start() should have been called before"); - - underTest.isEnabled(); + assertThatThrownBy(() -> underTest.isEnabled()) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Flag hasn't been initialized, the start() should have been called before"); } private static Branch newBranch(boolean supportsCrossProjectCpd) { diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/duplication/DuplicationRepositoryImplTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/duplication/DuplicationRepositoryImplTest.java index c1bcb82a6a6..c3e05b4113a 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/duplication/DuplicationRepositoryImplTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/duplication/DuplicationRepositoryImplTest.java @@ -24,15 +24,14 @@ import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.Arrays; import org.assertj.core.api.Assertions; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import org.sonar.ce.task.projectanalysis.util.WrapInSingleElementArray; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -42,26 +41,25 @@ public class DuplicationRepositoryImplTest { private static final Component FILE_COMPONENT_2 = ReportComponent.builder(Component.Type.FILE, 2).build(); private static final Duplication SOME_DUPLICATION = createDuplication(1, 2); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private DuplicationRepository underTest = new DuplicationRepositoryImpl(); @Test public void getDuplications_throws_NPE_if_Component_argument_is_null() { - expectFileArgumentNPE(); - - underTest.getDuplications(null); + assertThatThrownBy(() -> underTest.getDuplications(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("file can not be null"); } @Test @UseDataProvider("allComponentTypesButFile") public void getDuplications_throws_IAE_if_Component_type_is_not_FILE(Component.Type type) { - expectFileTypeIAE(); - - Component component = mockComponentGetType(type); - - underTest.getDuplications(component); + assertThatThrownBy(() -> { + Component component = mockComponentGetType(type); + underTest.getDuplications(component); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("type of file must be FILE"); } @Test @@ -71,27 +69,27 @@ public class DuplicationRepositoryImplTest { @Test public void add_throws_NPE_if_file_argument_is_null() { - expectFileArgumentNPE(); - - underTest.add(null, SOME_DUPLICATION); + assertThatThrownBy(() -> underTest.add(null, SOME_DUPLICATION)) + .isInstanceOf(NullPointerException.class) + .hasMessage("file can not be null"); } @Test public void addDuplication_inner_throws_NPE_if_duplication_argument_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("duplication can not be null"); - - underTest.add(FILE_COMPONENT_1, null); + assertThatThrownBy(() -> underTest.add(FILE_COMPONENT_1, null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("duplication can not be null"); } @Test @UseDataProvider("allComponentTypesButFile") public void addDuplication_inner_throws_IAE_if_file_type_is_not_FILE(Component.Type type) { - expectFileTypeIAE(); - - Component component = mockComponentGetType(type); - - underTest.add(component, SOME_DUPLICATION); + assertThatThrownBy(() -> { + Component component = mockComponentGetType(type); + underTest.add(component, SOME_DUPLICATION); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("type of file must be FILE"); } @Test @@ -145,16 +143,6 @@ public class DuplicationRepositoryImplTest { assertThat(underTest.getDuplications(component)).isEmpty(); } - private void expectFileArgumentNPE() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("file can not be null"); - } - - private void expectFileTypeIAE() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("type of file must be FILE"); - } - private Component mockComponentGetType(Component.Type type) { Component component = mock(Component.class); when(component.getType()).thenReturn(type); diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/duplication/DuplicationTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/duplication/DuplicationTest.java index 979c9915eaa..d6bc28a9b32 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/duplication/DuplicationTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/duplication/DuplicationTest.java @@ -23,13 +23,12 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; public class DuplicationTest { @@ -41,55 +40,47 @@ public class DuplicationTest { private static final String FILE_KEY_1 = "1"; private static final String FILE_KEY_2 = "2"; - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void constructor_throws_NPE_if_original_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("original TextBlock can not be null"); - - new Duplication(null, Collections.emptyList()); + assertThatThrownBy(() -> new Duplication(null, Collections.emptyList())) + .isInstanceOf(NullPointerException.class) + .hasMessage("original TextBlock can not be null"); } @Test public void constructor_throws_NPE_if_duplicates_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("duplicates can not be null"); - - new Duplication(SOME_ORIGINAL_TEXTBLOCK, null); + assertThatThrownBy(() -> new Duplication(SOME_ORIGINAL_TEXTBLOCK, null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("duplicates can not be null"); } @Test public void constructor_throws_IAE_if_duplicates_is_empty() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("duplicates can not be empty"); - - new Duplication(SOME_ORIGINAL_TEXTBLOCK, Collections.emptyList()); + assertThatThrownBy(() -> new Duplication(SOME_ORIGINAL_TEXTBLOCK, Collections.emptyList())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("duplicates can not be empty"); } @Test public void constructor_throws_NPE_if_duplicates_contains_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("duplicates can not contain null"); - - new Duplication(SOME_ORIGINAL_TEXTBLOCK, Arrays.asList(mock(Duplicate.class), null, mock(Duplicate.class))); + assertThatThrownBy(() -> new Duplication(SOME_ORIGINAL_TEXTBLOCK, Arrays.asList(mock(Duplicate.class), null, mock(Duplicate.class)))) + .isInstanceOf(NullPointerException.class) + .hasMessage("duplicates can not contain null"); } @Test public void constructor_throws_IAE_if_duplicates_contains_InnerDuplicate_of_original() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("TextBlock of an InnerDuplicate can not be the original TextBlock"); - - new Duplication(SOME_ORIGINAL_TEXTBLOCK, Arrays.asList(mock(Duplicate.class), new InnerDuplicate(SOME_ORIGINAL_TEXTBLOCK), mock(Duplicate.class))); + assertThatThrownBy(() -> new Duplication(SOME_ORIGINAL_TEXTBLOCK, Arrays.asList(mock(Duplicate.class), new InnerDuplicate(SOME_ORIGINAL_TEXTBLOCK), mock(Duplicate.class)))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("TextBlock of an InnerDuplicate can not be the original TextBlock"); } @Test public void constructor_throws_IAE_when_attempting_to_sort_Duplicate_of_unkown_type() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Unsupported type of Duplicate " + MyDuplicate.class.getName()); - - new Duplication(SOME_ORIGINAL_TEXTBLOCK, Arrays.asList(new MyDuplicate(), new MyDuplicate())); + assertThatThrownBy(() -> new Duplication(SOME_ORIGINAL_TEXTBLOCK, Arrays.asList(new MyDuplicate(), new MyDuplicate()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Unsupported type of Duplicate " + MyDuplicate.class.getName()); } private static final class MyDuplicate implements Duplicate { diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/duplication/InProjectDuplicateTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/duplication/InProjectDuplicateTest.java index 193c7ac0462..acde4f14a7f 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/duplication/InProjectDuplicateTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/duplication/InProjectDuplicateTest.java @@ -19,43 +19,37 @@ */ package org.sonar.ce.task.projectanalysis.duplication; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class InProjectDuplicateTest { private static final Component FILE_1 = ReportComponent.builder(Component.Type.FILE, 1).build(); private static final Component FILE_2 = ReportComponent.builder(Component.Type.FILE, 2).build(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void constructors_throws_NPE_if_file_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("file can not be null"); - - new InProjectDuplicate(null, new TextBlock(1, 1)); + assertThatThrownBy(() -> new InProjectDuplicate(null, new TextBlock(1, 1))) + .isInstanceOf(NullPointerException.class) + .hasMessage("file can not be null"); } @Test public void constructors_throws_NPE_if_textBlock_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("textBlock of duplicate can not be null"); - - new InProjectDuplicate(FILE_1, null); + assertThatThrownBy(() -> new InProjectDuplicate(FILE_1, null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("textBlock of duplicate can not be null"); } @Test public void constructors_throws_IAE_if_type_of_file_argument_is_not_FILE() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("file must be of type FILE"); - - new InProjectDuplicate(ReportComponent.builder(Component.Type.PROJECT, 1).build(), new TextBlock(1, 1)); + assertThatThrownBy(() -> new InProjectDuplicate(ReportComponent.builder(Component.Type.PROJECT, 1).build(), new TextBlock(1, 1))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("file must be of type FILE"); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/duplication/InnerDuplicateTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/duplication/InnerDuplicateTest.java index e95016d8e54..b62e3aea8fb 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/duplication/InnerDuplicateTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/duplication/InnerDuplicateTest.java @@ -19,22 +19,18 @@ */ package org.sonar.ce.task.projectanalysis.duplication; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class InnerDuplicateTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void constructors_throws_NPE_if_textBlock_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("textBlock of duplicate can not be null"); - - new InnerDuplicate(null); + assertThatThrownBy(() -> new InnerDuplicate(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("textBlock of duplicate can not be null"); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/duplication/TextBlockTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/duplication/TextBlockTest.java index 3ab735fe2d4..7b12ae7789d 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/duplication/TextBlockTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/duplication/TextBlockTest.java @@ -24,30 +24,25 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Random; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class TextBlockTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void constructor_throws_IAE_if_start_is_0() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("First line index must be >= 1"); - - new TextBlock(0, 2); + assertThatThrownBy(() -> new TextBlock(0, 2)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("First line index must be >= 1"); } @Test public void constructor_throws_IAE_if_end_is_less_than_start() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Last line index must be >= first line index"); - - new TextBlock(1, 0); + assertThatThrownBy(() -> new TextBlock(1, 0)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Last line index must be >= first line index"); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/event/EventRepositoryImplTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/event/EventRepositoryImplTest.java index 89a30e81aa8..3773c6416ed 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/event/EventRepositoryImplTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/event/EventRepositoryImplTest.java @@ -26,6 +26,7 @@ import org.sonar.ce.task.projectanalysis.component.ReportComponent; import org.sonar.ce.task.projectanalysis.component.ViewsComponent; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.fail; public class EventRepositoryImplTest { @@ -50,14 +51,16 @@ public class EventRepositoryImplTest { assertThat(underTest.getEvents(COMPONENT_2)).extracting("name").containsExactly(EVENT_2.getName()); } - @Test(expected = NullPointerException.class) + @Test public void add_throws_NPE_if_component_arg_is_null() { - underTest.add(null, EVENT_1); + assertThatThrownBy(() -> underTest.add(null, EVENT_1)) + .isInstanceOf(NullPointerException.class); } - @Test(expected = NullPointerException.class) + @Test public void add_throws_NPE_if_even_arg_is_null() { - underTest.add(COMPONENT_1, null); + assertThatThrownBy(() -> underTest.add(COMPONENT_1, null)) + .isInstanceOf(NullPointerException.class); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/event/EventTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/event/EventTest.java index aad1dc5a470..d823db06c21 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/event/EventTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/event/EventTest.java @@ -22,6 +22,7 @@ package org.sonar.ce.task.projectanalysis.event; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class EventTest { @@ -29,14 +30,16 @@ public class EventTest { private static final String SOME_DATA = "some data"; private static final String SOME_DESCRIPTION = "some description"; - @Test(expected = NullPointerException.class) + @Test public void createAlert_fail_fast_null_check_on_null_name() { - Event.createAlert(null, SOME_DATA, SOME_DESCRIPTION); + assertThatThrownBy(() -> Event.createAlert(null, SOME_DATA, SOME_DESCRIPTION)) + .isInstanceOf(NullPointerException.class); } - @Test(expected = NullPointerException.class) + @Test public void createProfile_fail_fast_null_check_on_null_name() { - Event.createProfile(null, SOME_DATA, SOME_DESCRIPTION); + assertThatThrownBy(() -> Event.createProfile(null, SOME_DATA, SOME_DESCRIPTION)) + .isInstanceOf(NullPointerException.class); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/filemove/AddedFileRepositoryImplTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/filemove/AddedFileRepositoryImplTest.java index be7efaa546a..fa23481ade2 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/filemove/AddedFileRepositoryImplTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/filemove/AddedFileRepositoryImplTest.java @@ -23,31 +23,27 @@ import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.Arrays; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder; import org.sonar.ce.task.projectanalysis.component.Component; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @RunWith(DataProviderRunner.class) public class AddedFileRepositoryImplTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private AnalysisMetadataHolder analysisMetadataHolder = mock(AnalysisMetadataHolder.class); private AddedFileRepositoryImpl underTest = new AddedFileRepositoryImpl(analysisMetadataHolder); @Test public void isAdded_fails_with_NPE_if_component_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("component can't be null"); - - underTest.isAdded(null); + assertThatThrownBy(() -> underTest.isAdded(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("component can't be null"); } @Test @@ -85,10 +81,9 @@ public class AddedFileRepositoryImplTest { @Test public void register_fails_with_NPE_if_component_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("component can't be null"); - - underTest.register(null); + assertThatThrownBy(() -> underTest.register(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("component can't be null"); } @Test @@ -96,10 +91,9 @@ public class AddedFileRepositoryImplTest { public void register_fails_with_IAE_if_component_is_not_a_file(Component.Type anyTypeButFile) { Component component = newComponent(anyTypeButFile); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("component must be a file"); - - underTest.register(component); + assertThatThrownBy(() -> underTest.register(component)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("component must be a file"); } @DataProvider @@ -115,10 +109,9 @@ public class AddedFileRepositoryImplTest { when(analysisMetadataHolder.isFirstAnalysis()).thenReturn(true); Component component = newComponent(Component.Type.FILE); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("No file can be registered on first analysis"); - - underTest.register(component); + assertThatThrownBy(() -> underTest.register(component)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("No file can be registered on first analysis"); } private static Component newComponent(Component.Type type) { diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/filemove/MutableMovedFilesRepositoryImplTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/filemove/MutableMovedFilesRepositoryImplTest.java index 424c7f6918a..e6549162597 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/filemove/MutableMovedFilesRepositoryImplTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/filemove/MutableMovedFilesRepositoryImplTest.java @@ -20,13 +20,12 @@ package org.sonar.ce.task.projectanalysis.filemove; import java.util.Random; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.ViewsComponent; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.fail; import static org.sonar.ce.task.projectanalysis.component.ReportComponent.builder; @@ -41,25 +40,20 @@ public class MutableMovedFilesRepositoryImplTest { }; private static final MovedFilesRepository.OriginalFile SOME_ORIGINAL_FILE = new MovedFilesRepository.OriginalFile("uuid for 100", "key for 100"); - @Rule - public ExpectedException expectedException = ExpectedException.none(); - private MutableMovedFilesRepositoryImpl underTest = new MutableMovedFilesRepositoryImpl(); @Test public void setOriginalFile_throws_NPE_when_file_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("file can't be null"); - - underTest.setOriginalFile(null, SOME_ORIGINAL_FILE); + assertThatThrownBy(() -> underTest.setOriginalFile(null, SOME_ORIGINAL_FILE)) + .isInstanceOf(NullPointerException.class) + .hasMessage("file can't be null"); } @Test public void setOriginalFile_throws_NPE_when_originalFile_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("originalFile can't be null"); - - underTest.setOriginalFile(SOME_FILE, null); + assertThatThrownBy(() -> underTest.setOriginalFile(SOME_FILE, null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("originalFile can't be null"); } @Test @@ -80,11 +74,10 @@ public class MutableMovedFilesRepositoryImplTest { public void setOriginalFile_throws_ISE_if_settings_another_originalFile() { underTest.setOriginalFile(SOME_FILE, SOME_ORIGINAL_FILE); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Original file OriginalFile{uuid='uuid for 100', key='key for 100'} " + - "already registered for file ReportComponent{ref=1, key='key_1', type=FILE}"); - - underTest.setOriginalFile(SOME_FILE, new MovedFilesRepository.OriginalFile("uudi", "key")); + assertThatThrownBy(() -> underTest.setOriginalFile(SOME_FILE, new MovedFilesRepository.OriginalFile("uudi", "key"))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Original file OriginalFile{uuid='uuid for 100', key='key for 100'} " + + "already registered for file ReportComponent{ref=1, key='key_1', type=FILE}"); } @Test @@ -104,10 +97,9 @@ public class MutableMovedFilesRepositoryImplTest { @Test public void getOriginalFile_throws_NPE_when_file_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("file can't be null"); - - underTest.getOriginalFile(null); + assertThatThrownBy(() -> underTest.getOriginalFile(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("file can't be null"); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/filemove/SourceSimilarityImplTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/filemove/SourceSimilarityImplTest.java index 25df46a487e..e25d6221bc7 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/filemove/SourceSimilarityImplTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/filemove/SourceSimilarityImplTest.java @@ -22,9 +22,7 @@ package org.sonar.ce.task.projectanalysis.filemove; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; @@ -32,8 +30,6 @@ import static org.assertj.core.api.Assertions.assertThat; public class SourceSimilarityImplTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private SourceSimilarityImpl underTest = new SourceSimilarityImpl(); diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/formula/AverageFormulaTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/formula/AverageFormulaTest.java index 3565188fbbc..f4b14823745 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/formula/AverageFormulaTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/formula/AverageFormulaTest.java @@ -20,15 +20,14 @@ package org.sonar.ce.task.projectanalysis.formula; import java.util.Optional; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import org.sonar.ce.task.projectanalysis.measure.Measure; import org.sonar.ce.task.projectanalysis.metric.Metric; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -49,43 +48,44 @@ public class AverageFormulaTest { CreateMeasureContext createMeasureContext = new DumbCreateMeasureContext( ReportComponent.builder(Component.Type.PROJECT, 1).build(), mock(Metric.class)); - @Rule - public ExpectedException thrown = ExpectedException.none(); @Test public void fail_with_NPE_when_building_formula_without_output_metric() { - thrown.expect(NullPointerException.class); - thrown.expectMessage("Output metric key cannot be null"); - - Builder.newBuilder() - .setOutputMetricKey(null) - .setMainMetricKey(COMPLEXITY_IN_FUNCTIONS_KEY) - .setByMetricKey(FUNCTIONS_KEY) - .build(); + assertThatThrownBy(() -> { + Builder.newBuilder() + .setOutputMetricKey(null) + .setMainMetricKey(COMPLEXITY_IN_FUNCTIONS_KEY) + .setByMetricKey(FUNCTIONS_KEY) + .build(); + }) + .isInstanceOf(NullPointerException.class) + .hasMessage("Output metric key cannot be null"); } @Test public void fail_with_NPE_when_building_formula_without_main_metric() { - thrown.expect(NullPointerException.class); - thrown.expectMessage("Main metric Key cannot be null"); - - Builder.newBuilder() - .setOutputMetricKey(FUNCTION_COMPLEXITY_KEY) - .setMainMetricKey(null) - .setByMetricKey(FUNCTIONS_KEY) - .build(); + assertThatThrownBy(() -> { + Builder.newBuilder() + .setOutputMetricKey(FUNCTION_COMPLEXITY_KEY) + .setMainMetricKey(null) + .setByMetricKey(FUNCTIONS_KEY) + .build(); + }) + .isInstanceOf(NullPointerException.class) + .hasMessage("Main metric Key cannot be null"); } @Test public void fail_with_NPE_when_building_formula_without_by_metric() { - thrown.expect(NullPointerException.class); - thrown.expectMessage("By metric Key cannot be null"); - - Builder.newBuilder() - .setOutputMetricKey(FUNCTION_COMPLEXITY_KEY) - .setMainMetricKey(COMPLEXITY_IN_FUNCTIONS_KEY) - .setByMetricKey(null) - .build(); + assertThatThrownBy(() -> { + Builder.newBuilder() + .setOutputMetricKey(FUNCTION_COMPLEXITY_KEY) + .setMainMetricKey(COMPLEXITY_IN_FUNCTIONS_KEY) + .setByMetricKey(null) + .build(); + }) + .isInstanceOf(NullPointerException.class) + .hasMessage("By metric Key cannot be null"); } @Test @@ -163,15 +163,16 @@ public class AverageFormulaTest { @Test public void fail_with_IAE_when_aggregate_from_component_and_context_with_not_numeric_measures() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Measure of type 'STRING' are not supported"); - - AverageFormula.AverageCounter counter = BASIC_AVERAGE_FORMULA.createNewCounter(); - addMeasure(COMPLEXITY_IN_FUNCTIONS_KEY, 10L); - when(counterInitializationContext.getMeasure(FUNCTIONS_KEY)).thenReturn(Optional.of(Measure.newMeasureBuilder().create("data"))); - counter.initialize(counterInitializationContext); - - BASIC_AVERAGE_FORMULA.createMeasure(counter, createMeasureContext); + assertThatThrownBy(() -> { + AverageFormula.AverageCounter counter = BASIC_AVERAGE_FORMULA.createNewCounter(); + addMeasure(COMPLEXITY_IN_FUNCTIONS_KEY, 10L); + when(counterInitializationContext.getMeasure(FUNCTIONS_KEY)).thenReturn(Optional.of(Measure.newMeasureBuilder().create("data"))); + counter.initialize(counterInitializationContext); + + BASIC_AVERAGE_FORMULA.createMeasure(counter, createMeasureContext); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Measure of type 'STRING' are not supported"); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/formula/DistributionFormulaTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/formula/DistributionFormulaTest.java index 47d8e987c81..fc223ab4511 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/formula/DistributionFormulaTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/formula/DistributionFormulaTest.java @@ -20,15 +20,14 @@ package org.sonar.ce.task.projectanalysis.formula; import java.util.Optional; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import org.sonar.ce.task.projectanalysis.measure.Measure; import org.sonar.ce.task.projectanalysis.metric.Metric; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.api.measures.CoreMetrics.FUNCTION_COMPLEXITY_DISTRIBUTION_KEY; @@ -37,8 +36,6 @@ public class DistributionFormulaTest { private static final DistributionFormula BASIC_DISTRIBUTION_FORMULA = new DistributionFormula(FUNCTION_COMPLEXITY_DISTRIBUTION_KEY); - @Rule - public ExpectedException thrown = ExpectedException.none(); CounterInitializationContext counterInitializationContext = mock(CounterInitializationContext.class); CreateMeasureContext projectCreateMeasureContext = new DumbCreateMeasureContext( @@ -53,10 +50,9 @@ public class DistributionFormulaTest { @Test public void fail_with_NPE_when_creating_counter_with_null_metric() { - thrown.expect(NullPointerException.class); - thrown.expectMessage("Metric key cannot be null"); - - new DistributionFormula(null); + assertThatThrownBy(() -> new DistributionFormula(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("Metric key cannot be null"); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/formula/IntSumFormulaTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/formula/IntSumFormulaTest.java index 3a3e6a103e9..1731e8d4000 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/formula/IntSumFormulaTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/formula/IntSumFormulaTest.java @@ -21,9 +21,7 @@ package org.sonar.ce.task.projectanalysis.formula; import java.util.Optional; import javax.annotation.Nullable; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import org.sonar.ce.task.projectanalysis.formula.SumFormula.IntSumFormula; @@ -32,6 +30,7 @@ import org.sonar.ce.task.projectanalysis.measure.Measure; import org.sonar.ce.task.projectanalysis.metric.Metric; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.api.measures.CoreMetrics.LINES_KEY; @@ -43,8 +42,6 @@ public class IntSumFormulaTest { private static final IntSumFormula INT_SUM_FORMULA_NULL_DEFAULT_INPUT_VALUE = createIntSumFormula(LINES_KEY, null); private static final IntSumFormula INT_SUM_FORMULA_DEFAULT_INPUT_VALUE_15 = createIntSumFormula(LINES_KEY, 15); - @Rule - public ExpectedException thrown = ExpectedException.none(); CreateMeasureContext projectCreateMeasureContext = new DumbCreateMeasureContext( ReportComponent.builder(Component.Type.PROJECT, 1).build(), mock(Metric.class)); @@ -58,10 +55,9 @@ public class IntSumFormulaTest { @Test public void fail_with_NPE_when_creating_formula_with_null_metric() { - thrown.expect(NullPointerException.class); - thrown.expectMessage("Metric key cannot be null"); - - createIntSumFormula(null); + assertThatThrownBy(() -> createIntSumFormula(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("Metric key cannot be null"); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/formula/LongSumFormulaTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/formula/LongSumFormulaTest.java index 267a63bcad8..77ff2c02254 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/formula/LongSumFormulaTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/formula/LongSumFormulaTest.java @@ -21,9 +21,7 @@ package org.sonar.ce.task.projectanalysis.formula; import java.util.Optional; import javax.annotation.Nullable; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import org.sonar.ce.task.projectanalysis.formula.counter.LongSumCounter; @@ -31,6 +29,7 @@ import org.sonar.ce.task.projectanalysis.measure.Measure; import org.sonar.ce.task.projectanalysis.metric.Metric; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.api.measures.CoreMetrics.LINES_KEY; @@ -42,8 +41,6 @@ public class LongSumFormulaTest { private static final SumFormula.LongSumFormula LONG_SUM_FORMULA_NULL_DEFAULT_INPUT_VALUE = createLongSumFormula(LINES_KEY, null); private static final SumFormula.LongSumFormula LONG_SUM_FORMULA_DEFAULT_INPUT_VALUE_15 = createLongSumFormula(LINES_KEY, 15L); - @Rule - public ExpectedException thrown = ExpectedException.none(); CreateMeasureContext projectCreateMeasureContext = new DumbCreateMeasureContext( ReportComponent.builder(Component.Type.PROJECT, 1).build(), mock(Metric.class)); @@ -57,10 +54,9 @@ public class LongSumFormulaTest { @Test public void fail_with_NPE_when_creating_formula_with_null_metric() { - thrown.expect(NullPointerException.class); - thrown.expectMessage("Metric key cannot be null"); - - createLongSumFormula(null); + assertThatThrownBy(() -> createLongSumFormula(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("Metric key cannot be null"); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/formula/ReportFormulaExecutorComponentVisitorTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/formula/ReportFormulaExecutorComponentVisitorTest.java index 84d7699afaa..895771874cd 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/formula/ReportFormulaExecutorComponentVisitorTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/formula/ReportFormulaExecutorComponentVisitorTest.java @@ -23,7 +23,6 @@ import com.google.common.collect.ImmutableList; import java.util.Optional; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.measures.CoreMetrics; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.PathAwareCrawler; @@ -36,6 +35,7 @@ import org.sonar.ce.task.projectanalysis.metric.Metric; import org.sonar.ce.task.projectanalysis.metric.MetricRepositoryRule; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.measures.CoreMetrics.LINES_KEY; import static org.sonar.api.measures.CoreMetrics.NCLOC_KEY; import static org.sonar.api.measures.CoreMetrics.NEW_COVERAGE_KEY; @@ -46,7 +46,6 @@ import static org.sonar.ce.task.projectanalysis.component.ReportComponent.builde import static org.sonar.ce.task.projectanalysis.measure.Measure.newMeasureBuilder; import static org.sonar.ce.task.projectanalysis.measure.MeasureRepoEntry.entryOf; import static org.sonar.ce.task.projectanalysis.measure.MeasureRepoEntry.toEntries; -import static org.sonar.test.ExceptionCauseMatcher.hasType; public class ReportFormulaExecutorComponentVisitorTest { private static final int ROOT_REF = 1; @@ -69,8 +68,6 @@ public class ReportFormulaExecutorComponentVisitorTest { .build()) .build(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule(); @Rule @@ -222,11 +219,13 @@ public class ReportFormulaExecutorComponentVisitorTest { treeRootHolder.setRoot(root); measureRepository.addRawMeasure(FILE_1_REF, NCLOC_KEY, newMeasureBuilder().create(2)); - expectedException.expectCause(hasType(UnsupportedOperationException.class) - .andMessage(String.format("A measure can only be set once for Component (ref=%s), Metric (key=%s)", FILE_1_REF, NCLOC_KEY))); +// expectedException.expectCause( +// hasType(UnsupportedOperationException.class) +// .andMessage(String.format("A measure can only be set once for Component (ref=%s), Metric (key=%s)", FILE_1_REF, NCLOC_KEY)) +// ); - new PathAwareCrawler<>(formulaExecutorComponentVisitor(new FakeFormula())) - .visit(root); + assertThatThrownBy(() -> new PathAwareCrawler<>(formulaExecutorComponentVisitor(new FakeFormula())).visit(root)) + .hasCause( new UnsupportedOperationException(String.format("A measure can only be set once for Component (ref=%s), Metric (key=%s)", FILE_1_REF, NCLOC_KEY))); } @Test @@ -235,11 +234,14 @@ public class ReportFormulaExecutorComponentVisitorTest { treeRootHolder.setRoot(root); measureRepository.addRawMeasure(ROOT_REF, NCLOC_KEY, newMeasureBuilder().create(10)); - expectedException.expectCause(hasType(UnsupportedOperationException.class) - .andMessage(String.format("A measure can only be set once for Component (ref=%s), Metric (key=%s)", ROOT_REF, NCLOC_KEY))); +// expectedException.expectCause(hasType(UnsupportedOperationException.class) +// .andMessage(String.format("A measure can only be set once for Component (ref=%s), Metric (key=%s)", ROOT_REF, NCLOC_KEY))); - new PathAwareCrawler<>(formulaExecutorComponentVisitor(new FakeFormula())) - .visit(root); + assertThatThrownBy(() -> { + new PathAwareCrawler<>(formulaExecutorComponentVisitor(new FakeFormula())) + .visit(root); + }) + .hasCause(new UnsupportedOperationException(String.format("A measure can only be set once for Component (ref=%s), Metric (key=%s)", ROOT_REF, NCLOC_KEY))); } private FormulaExecutorComponentVisitor formulaExecutorComponentVisitor(Formula formula) { diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/formula/coverage/CoverageUtilsTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/formula/coverage/CoverageUtilsTest.java index 48017f576d5..b03c77bc5e2 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/formula/coverage/CoverageUtilsTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/formula/coverage/CoverageUtilsTest.java @@ -24,7 +24,6 @@ import java.util.Map; import java.util.Optional; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.ExternalResource; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.formula.CounterInitializationContext; @@ -33,6 +32,7 @@ import org.sonar.ce.task.projectanalysis.measure.Measure; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.ce.task.projectanalysis.formula.coverage.CoverageUtils.getLongMeasureValue; import static org.sonar.ce.task.projectanalysis.formula.coverage.CoverageUtils.getMeasureVariations; import static org.sonar.ce.task.projectanalysis.measure.Measure.newMeasureBuilder; @@ -44,8 +44,6 @@ public class CoverageUtilsTest { @Rule public CounterInitializationContextRule fileAggregateContext = new CounterInitializationContextRule(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void verify_calculate_coverage() { @@ -80,12 +78,12 @@ public class CoverageUtilsTest { @Test public void getLongMeasureValue_throws_ISE_if_measure_is_DOUBLE() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("value can not be converted to long because current value type is a DOUBLE"); - - fileAggregateContext.put(SOME_METRIC_KEY, newMeasureBuilder().create(152d, 1)); - - getLongMeasureValue(fileAggregateContext, SOME_METRIC_KEY); + assertThatThrownBy(() -> { + fileAggregateContext.put(SOME_METRIC_KEY, newMeasureBuilder().create(152d, 1)); + getLongMeasureValue(fileAggregateContext, SOME_METRIC_KEY); + }) + .isInstanceOf(IllegalStateException.class) + .hasMessage("value can not be converted to long because current value type is a DOUBLE"); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/ComponentIssuesLoaderTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/ComponentIssuesLoaderTest.java index d5b39e40586..4b5f6e2302b 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/ComponentIssuesLoaderTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/ComponentIssuesLoaderTest.java @@ -33,7 +33,6 @@ import java.util.stream.IntStream; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.api.config.Configuration; import org.sonar.api.config.internal.MapSettings; @@ -66,8 +65,6 @@ public class ComponentIssuesLoaderTest { @Rule public DbTester db = DbTester.create(System2.INSTANCE); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private DbClient dbClient = db.getDbClient(); private System2 system2 = mock(System2.class); diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/ComponentIssuesRepositoryImplTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/ComponentIssuesRepositoryImplTest.java index 596332f497b..b7501ea91d2 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/ComponentIssuesRepositoryImplTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/ComponentIssuesRepositoryImplTest.java @@ -22,17 +22,15 @@ package org.sonar.ce.task.projectanalysis.issue; import java.util.Arrays; import java.util.Collections; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.core.issue.DefaultIssue; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.ce.task.projectanalysis.component.ReportComponent.builder; public class ComponentIssuesRepositoryImplTest { - @org.junit.Rule - public ExpectedException thrown = ExpectedException.none(); static final Component FILE_1 = builder(Component.Type.FILE, 1).build(); static final Component FILE_2 = builder(Component.Type.FILE, 2).build(); @@ -62,34 +60,34 @@ public class ComponentIssuesRepositoryImplTest { @Test public void fail_with_NPE_when_setting_issues_with_null_component() { - thrown.expect(NullPointerException.class); - thrown.expectMessage("component cannot be null"); - - sut.setIssues(null, Arrays.asList(DUMB_ISSUE)); + assertThatThrownBy(() -> sut.setIssues(null, Arrays.asList(DUMB_ISSUE))) + .isInstanceOf(NullPointerException.class) + .hasMessage("component cannot be null"); } @Test public void fail_with_NPE_when_setting_issues_with_null_issues() { - thrown.expect(NullPointerException.class); - thrown.expectMessage("issues cannot be null"); - - sut.setIssues(FILE_1, null); + assertThatThrownBy(() -> sut.setIssues(FILE_1, null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("issues cannot be null"); } @Test public void fail_with_IAE_when_getting_issues_on_different_component() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Only issues from component '1' are available, but wanted component is '2'."); - - sut.setIssues(FILE_1, Arrays.asList(DUMB_ISSUE)); - sut.getIssues(FILE_2); + assertThatThrownBy(() -> { + sut.setIssues(FILE_1, Arrays.asList(DUMB_ISSUE)); + sut.getIssues(FILE_2); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Only issues from component '1' are available, but wanted component is '2'."); } @Test public void fail_with_ISE_when_getting_issues_but_issues_are_null() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Issues have not been initialized"); - - sut.getIssues(FILE_1); + assertThatThrownBy(() -> { + sut.getIssues(FILE_1); + }) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Issues have not been initialized"); } } diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/ComponentsWithUnprocessedIssuesTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/ComponentsWithUnprocessedIssuesTest.java index a82ef480b35..7f97e1f36be 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/ComponentsWithUnprocessedIssuesTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/ComponentsWithUnprocessedIssuesTest.java @@ -20,17 +20,14 @@ package org.sonar.ce.task.projectanalysis.issue; import java.util.Set; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static com.google.common.collect.Sets.newHashSet; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class ComponentsWithUnprocessedIssuesTest { - @Rule - public ExpectedException thrown = ExpectedException.none(); ComponentsWithUnprocessedIssues sut = new ComponentsWithUnprocessedIssues(); @@ -55,19 +52,19 @@ public class ComponentsWithUnprocessedIssuesTest { @Test public void fail_with_NPE_when_setting_null_uuids() { - thrown.expect(NullPointerException.class); - thrown.expectMessage("Uuids cannot be null"); - - sut.setUuids(null); + assertThatThrownBy(() -> sut.setUuids(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("Uuids cannot be null"); } @Test public void fail_with_ISE_when_setting_uuids_twice() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Uuids have already been initialized"); - - sut.setUuids(newHashSet("ABCD")); - sut.setUuids(newHashSet("EFGH")); + assertThatThrownBy(() -> { + sut.setUuids(newHashSet("ABCD")); + sut.setUuids(newHashSet("EFGH")); + }) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Uuids have already been initialized"); } @Test @@ -80,17 +77,15 @@ public class ComponentsWithUnprocessedIssuesTest { @Test public void fail_with_ISE_when_removing_uuid_and_not_initialized() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Uuids have not been initialized yet"); - - sut.remove("ABCD"); + assertThatThrownBy(() -> sut.remove("ABCD")) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Uuids have not been initialized yet"); } @Test public void fail_with_ISE_when_getting_uuid_and_not_initialized() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Uuids have not been initialized yet"); - - sut.getUuids(); + assertThatThrownBy(() -> sut.getUuids()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Uuids have not been initialized yet"); } } diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/DebtCalculatorTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/DebtCalculatorTest.java index 04373006779..8d375515062 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/DebtCalculatorTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/DebtCalculatorTest.java @@ -28,6 +28,7 @@ import org.sonar.core.issue.DefaultIssue; import org.sonar.db.rule.RuleTesting; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class DebtCalculatorTest { @@ -92,13 +93,14 @@ public class DebtCalculatorTest { assertThat(underTest.calculate(issue).toMinutes()).isEqualTo(2); } - @Test(expected = IllegalArgumentException.class) + @Test public void effort_to_fix_must_not_be_set_with_constant_function() { int constant = 2; issue.setGap(3.0); rule.setFunction(new DefaultDebtRemediationFunction(DebtRemediationFunction.Type.CONSTANT_ISSUE, null, constant + "min")); - underTest.calculate(issue); + assertThatThrownBy(() -> underTest.calculate(issue)) + .isInstanceOf(IllegalArgumentException.class); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/IssueCreationDateCalculatorTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/IssueCreationDateCalculatorTest.java index 4e90f12b32a..34495070a89 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/IssueCreationDateCalculatorTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/IssueCreationDateCalculatorTest.java @@ -32,7 +32,6 @@ import java.util.stream.Stream; import org.apache.commons.lang.ArrayUtils; import org.junit.Before; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.api.rule.RuleKey; import org.sonar.ce.task.projectanalysis.analysis.Analysis; @@ -54,6 +53,7 @@ import org.sonar.db.protobuf.DbIssues.Location; import org.sonar.db.protobuf.DbIssues.Locations.Builder; import org.sonar.server.issue.IssueFieldsSetter; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.same; @@ -71,8 +71,6 @@ public class IssueCreationDateCalculatorTest { @org.junit.Rule public AnalysisMetadataHolderRule analysisMetadataHolder = new AnalysisMetadataHolderRule(); - @org.junit.Rule - public ExpectedException exception = ExpectedException.none(); private ScmInfoRepository scmInfoRepository = mock(ScmInfoRepository.class); private IssueFieldsSetter issueUpdater = mock(IssueFieldsSetter.class); @@ -192,9 +190,9 @@ public class IssueCreationDateCalculatorTest { when(ruleRepository.findByKey(ruleKey)).thenReturn(Optional.empty()); makeIssueNew(); - exception.expect(IllegalStateException.class); - exception.expectMessage("The rule with key 'reop:rule' raised an issue, but no rule with that key was found"); - run(); + assertThatThrownBy(this::run) + .isInstanceOf(IllegalStateException.class) + .hasMessage("The rule with key 'reop:rule' raised an issue, but no rule with that key was found"); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/MovedIssueVisitorTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/MovedIssueVisitorTest.java index d02c347f6a4..6386040a66e 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/MovedIssueVisitorTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/MovedIssueVisitorTest.java @@ -23,7 +23,6 @@ import java.util.Date; import java.util.Optional; import org.junit.Before; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule; import org.sonar.ce.task.projectanalysis.component.Component; @@ -34,6 +33,7 @@ import org.sonar.core.issue.IssueChangeContext; import org.sonar.server.issue.IssueFieldsSetter; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; @@ -51,8 +51,6 @@ public class MovedIssueVisitorTest { .setUuid(FILE_UUID) .build(); - @org.junit.Rule - public ExpectedException expectedException = ExpectedException.none(); @org.junit.Rule public AnalysisMetadataHolderRule analysisMetadataHolder = new AnalysisMetadataHolderRule(); @@ -88,11 +86,10 @@ public class MovedIssueVisitorTest { DefaultIssue issue = mockIssue("other component uuid"); when(issue.toString()).thenReturn("[bad issue, bad!]"); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Issue [bad issue, bad!] for component ReportComponent{ref=1, key='key_1', type=FILE} " + - "has a different component key but no original file exist in MovedFilesRepository"); - - underTest.onIssue(FILE, issue); + assertThatThrownBy(() -> underTest.onIssue(FILE, issue)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Issue [bad issue, bad!] for component ReportComponent{ref=1, key='key_1', type=FILE} " + + "has a different component key but no original file exist in MovedFilesRepository"); } @Test @@ -102,11 +99,10 @@ public class MovedIssueVisitorTest { when(movedFilesRepository.getOriginalFile(FILE)) .thenReturn(Optional.of(new MovedFilesRepository.OriginalFile("original uuid", "original key"))); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Issue [bad issue, bad!] doesn't belong to file original uuid registered as original " + - "file of current file ReportComponent{ref=1, key='key_1', type=FILE}"); - - underTest.onIssue(FILE, issue); + assertThatThrownBy(() -> underTest.onIssue(FILE, issue)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Issue [bad issue, bad!] doesn't belong to file original uuid registered as original " + + "file of current file ReportComponent{ref=1, key='key_1', type=FILE}"); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/NewAdHocRuleTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/NewAdHocRuleTest.java index 766f63c7055..56adca43ae2 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/NewAdHocRuleTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/NewAdHocRuleTest.java @@ -20,21 +20,18 @@ package org.sonar.ce.task.projectanalysis.issue; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.scanner.protocol.output.ScannerReport; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class NewAdHocRuleTest { - @org.junit.Rule - public ExpectedException exception = ExpectedException.none(); @Test public void fail_if_engine_id_is_not_set() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("'engine id' not expected to be null for an ad hoc rule"); - - new NewAdHocRule(ScannerReport.ExternalIssue.newBuilder().build()); + assertThatThrownBy(() -> new NewAdHocRule(ScannerReport.ExternalIssue.newBuilder().build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("'engine id' not expected to be null for an ad hoc rule"); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/RuleRepositoryImplTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/RuleRepositoryImplTest.java index 1d6a4ab4ef0..318c0261bbf 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/RuleRepositoryImplTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/RuleRepositoryImplTest.java @@ -22,14 +22,13 @@ package org.sonar.ce.task.projectanalysis.issue; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import java.util.Optional; +import org.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.junit.Before; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.rule.RuleKey; import org.sonar.api.rule.RuleStatus; import org.sonar.api.rules.RuleType; import org.sonar.api.utils.System2; -import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule; import org.sonar.core.util.SequenceUuidFactory; import org.sonar.db.DbClient; import org.sonar.db.DbSession; @@ -42,9 +41,9 @@ import org.sonar.scanner.protocol.output.ScannerReport; import org.sonar.server.rule.index.RuleIndexer; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; -import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.verify; @@ -60,8 +59,6 @@ public class RuleRepositoryImplTest { private static final RuleKey AC_RULE_KEY = RuleKey.of("a", "c"); private static final String AC_RULE_UUID = "uuid-684"; - @org.junit.Rule - public ExpectedException expectedException = ExpectedException.none(); @org.junit.Rule public DbTester db = DbTester.create(System2.INSTANCE); @@ -139,9 +136,7 @@ public class RuleRepositoryImplTest { @Test public void getByKey_throws_NPE_if_key_argument_is_null() { - expectNullRuleKeyNPE(); - - underTest.getByKey(null); + expectNullRuleKeyNPE(() -> underTest.getByKey(null)); } @Test @@ -169,28 +164,23 @@ public class RuleRepositoryImplTest { @Test public void getByKey_throws_IAE_if_rules_does_not_exist_in_DB() { - expectIAERuleNotFound(AC_RULE_KEY); - - underTest.getByKey(AC_RULE_KEY); + expectIAERuleNotFound(() -> underTest.getByKey(AC_RULE_KEY), AC_RULE_KEY); } @Test public void getByKey_throws_IAE_if_argument_is_deprecated_key_in_DB_of_non_existing_rule() { - expectIAERuleNotFound(DEPRECATED_KEY_OF_NON_EXITING_RULE); - - underTest.getByKey(DEPRECATED_KEY_OF_NON_EXITING_RULE); + expectIAERuleNotFound(() -> underTest.getByKey(DEPRECATED_KEY_OF_NON_EXITING_RULE), DEPRECATED_KEY_OF_NON_EXITING_RULE); } - private void expectIAERuleNotFound(RuleKey ruleKey) { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Can not find rule for key " + ruleKey.toString() + ". This rule does not exist in DB"); + private void expectIAERuleNotFound(ThrowingCallable callback, RuleKey ruleKey) { + assertThatThrownBy(callback) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Can not find rule for key " + ruleKey.toString() + ". This rule does not exist in DB"); } @Test public void findByKey_throws_NPE_if_key_argument_is_null() { - expectNullRuleKeyNPE(); - - underTest.findByKey(null); + expectNullRuleKeyNPE(() -> underTest.findByKey(null)); } @Test @@ -239,10 +229,9 @@ public class RuleRepositoryImplTest { @Test public void getByUuid_throws_IAE_if_rules_does_not_exist_in_DB() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Can not find rule for uuid " + AC_RULE_UUID + ". This rule does not exist in DB"); - - underTest.getByUuid(AC_RULE_UUID); + assertThatThrownBy(() -> underTest.getByUuid(AC_RULE_UUID)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Can not find rule for uuid " + AC_RULE_UUID + ". This rule does not exist in DB"); } @Test @@ -293,9 +282,10 @@ public class RuleRepositoryImplTest { verify(ruleIndexer).commitAndIndex(db.getSession(), ruleDefinitionDto.get().getUuid()); } - private void expectNullRuleKeyNPE() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("RuleKey can not be null"); + private void expectNullRuleKeyNPE(ThrowingCallable callback) { + assertThatThrownBy(callback) + .isInstanceOf(NullPointerException.class) + .hasMessage("RuleKey can not be null"); } private void verifyNoMethodCallTriggersCallToDB() { diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/commonrule/CommentDensityRuleTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/commonrule/CommentDensityRuleTest.java index c37129f9448..e847f1589c8 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/commonrule/CommentDensityRuleTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/commonrule/CommentDensityRuleTest.java @@ -22,7 +22,6 @@ package org.sonar.ce.task.projectanalysis.issue.commonrule; import com.google.common.collect.ImmutableMap; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.measures.CoreMetrics; import org.sonar.api.rule.RuleKey; import org.sonar.api.rule.Severity; @@ -39,6 +38,7 @@ import org.sonar.core.issue.DefaultIssue; import org.sonar.server.rule.CommonRuleKeys; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.ce.task.projectanalysis.component.ReportComponent.DUMB_PROJECT; public class CommentDensityRuleTest { @@ -56,8 +56,6 @@ public class CommentDensityRuleTest { .setFileAttributes(new FileAttributes(true, PLUGIN_KEY, 1)) .build(); - @Rule - public ExpectedException thrown = ExpectedException.none(); @Rule public ActiveRulesHolderRule activeRuleHolder = new ActiveRulesHolderRule(); @@ -127,12 +125,12 @@ public class CommentDensityRuleTest { */ @Test public void fail_if_min_density_is_100() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Minimum density of rule [common-java:InsufficientCommentDensity] is incorrect. Got [100] but must be strictly less than 100."); - - prepareForIssue("100", FILE, 0.0, 0, 1); - - underTest.processFile(FILE, PLUGIN_KEY); + assertThatThrownBy(() -> { + prepareForIssue("100", FILE, 0.0, 0, 1); + underTest.processFile(FILE, PLUGIN_KEY); + }) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Minimum density of rule [common-java:InsufficientCommentDensity] is incorrect. Got [100] but must be strictly less than 100."); } private void prepareForIssue(String minDensity, ReportComponent file, double commentLineDensity, int commentLines, int ncloc) { diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/commonrule/CommonRuleTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/commonrule/CommonRuleTest.java index a0ce70d3438..7068ea504b4 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/commonrule/CommonRuleTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/commonrule/CommonRuleTest.java @@ -20,22 +20,19 @@ package org.sonar.ce.task.projectanalysis.issue.commonrule; import com.google.common.collect.ImmutableMap; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.rule.Severity; import org.sonar.ce.task.projectanalysis.qualityprofile.ActiveRule; import org.sonar.db.rule.RuleTesting; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class CommonRuleTest { private static final String PLUGIN_KEY = "java"; private static final String QP_KEY = "qp1"; - @Rule - public ExpectedException thrown = ExpectedException.none(); @Test public void test_getMinDensityParam() { @@ -47,28 +44,31 @@ public class CommonRuleTest { @Test public void getMinDensityParam_fails_if_param_value_is_absent() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Required parameter [minDensity] is missing on rule [xoo:x1]"); - - ActiveRule activeRule = new ActiveRule(RuleTesting.XOO_X1, Severity.MAJOR, ImmutableMap.of(), 1_000L, PLUGIN_KEY, QP_KEY); - CommonRule.getMinDensityParam(activeRule, "minDensity"); + assertThatThrownBy(() -> { + ActiveRule activeRule = new ActiveRule(RuleTesting.XOO_X1, Severity.MAJOR, ImmutableMap.of(), 1_000L, PLUGIN_KEY, QP_KEY); + CommonRule.getMinDensityParam(activeRule, "minDensity"); + }) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Required parameter [minDensity] is missing on rule [xoo:x1]"); } @Test public void getMinDensityParam_fails_if_param_value_is_negative() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Minimum density of rule [xoo:x1] is incorrect. Got [-30.5] but must be between 0 and 100."); - - ActiveRule activeRule = new ActiveRule(RuleTesting.XOO_X1, Severity.MAJOR, ImmutableMap.of("minDensity", "-30.5"), 1_000L, PLUGIN_KEY, QP_KEY); - CommonRule.getMinDensityParam(activeRule, "minDensity"); + assertThatThrownBy(() -> { + ActiveRule activeRule = new ActiveRule(RuleTesting.XOO_X1, Severity.MAJOR, ImmutableMap.of("minDensity", "-30.5"), 1_000L, PLUGIN_KEY, QP_KEY); + CommonRule.getMinDensityParam(activeRule, "minDensity"); + }) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Minimum density of rule [xoo:x1] is incorrect. Got [-30.5] but must be between 0 and 100."); } @Test public void getMinDensityParam_fails_if_param_value_is_greater_than_100() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Minimum density of rule [xoo:x1] is incorrect. Got [305] but must be between 0 and 100."); - - ActiveRule activeRule = new ActiveRule(RuleTesting.XOO_X1, Severity.MAJOR, ImmutableMap.of("minDensity", "305"), 1_000L, PLUGIN_KEY, QP_KEY); - CommonRule.getMinDensityParam(activeRule, "minDensity"); + assertThatThrownBy(() -> { + ActiveRule activeRule = new ActiveRule(RuleTesting.XOO_X1, Severity.MAJOR, ImmutableMap.of("minDensity", "305"), 1_000L, PLUGIN_KEY, QP_KEY); + CommonRule.getMinDensityParam(activeRule, "minDensity"); + }) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Minimum density of rule [xoo:x1] is incorrect. Got [305] but must be between 0 and 100."); } } diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/filter/IssueFilterTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/filter/IssueFilterTest.java index 2e688657769..cd41532a92b 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/filter/IssueFilterTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/filter/IssueFilterTest.java @@ -25,9 +25,8 @@ import java.util.Collections; import java.util.List; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.sonar.api.config.internal.Settings; import org.sonar.api.config.internal.MapSettings; +import org.sonar.api.config.internal.Settings; import org.sonar.api.rule.RuleKey; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.ConfigurationRepository; @@ -36,6 +35,7 @@ import org.sonar.core.issue.DefaultIssue; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.ce.task.projectanalysis.component.Component.Type.FILE; @@ -43,8 +43,6 @@ import static org.sonar.ce.task.projectanalysis.component.ReportComponent.builde public class IssueFilterTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); static final RuleKey XOO_X1 = RuleKey.of("xoo", "x1"); static final RuleKey XOO_X2 = RuleKey.of("xoo", "x2"); @@ -166,18 +164,16 @@ public class IssueFilterTest { @Test public void fail_when_only_rule_key_parameter() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("File path pattern cannot be empty. Please check 'sonar.issue.ignore.multicriteria' settings"); - - newIssueFilter(newSettings(asList("xoo:x1", ""), Collections.emptyList())); + assertThatThrownBy(() -> newIssueFilter(newSettings(asList("xoo:x1", ""), Collections.emptyList()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("File path pattern cannot be empty. Please check 'sonar.issue.ignore.multicriteria' settings"); } @Test public void fail_when_only_path_parameter() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Rule key pattern cannot be empty. Please check 'sonar.issue.enforce.multicriteria' settings"); - - newIssueFilter(newSettings(Collections.emptyList(), asList("", "**"))); + assertThatThrownBy(() -> newIssueFilter(newSettings(Collections.emptyList(), asList("", "**")))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Rule key pattern cannot be empty. Please check 'sonar.issue.enforce.multicriteria' settings"); } private IssueFilter newIssueFilter(MapSettings settings) { diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/language/LanguageRepositoryImplTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/language/LanguageRepositoryImplTest.java index ec5ce38145e..d98333f56e6 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/language/LanguageRepositoryImplTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/language/LanguageRepositoryImplTest.java @@ -24,6 +24,7 @@ import org.junit.Test; import org.sonar.api.resources.Language; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class LanguageRepositoryImplTest { @@ -31,9 +32,10 @@ public class LanguageRepositoryImplTest { private static final String SOME_LANGUAGE_KEY = "SoMe language_Key"; private static final Language SOME_LANGUAGE = createLanguage(SOME_LANGUAGE_KEY, "_name"); - @Test(expected = IllegalArgumentException.class) + @Test public void constructor_fails_is_language_have_the_same_key() { - new LanguageRepositoryImpl(createLanguage(SOME_LANGUAGE_KEY, " 1"), createLanguage(SOME_LANGUAGE_KEY, " 2")); + assertThatThrownBy(() -> new LanguageRepositoryImpl(createLanguage(SOME_LANGUAGE_KEY, " 1"), createLanguage(SOME_LANGUAGE_KEY, " 2"))) + .isInstanceOf(IllegalArgumentException.class); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/BatchMeasureToMeasureTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/BatchMeasureToMeasureTest.java index 22a59bde7cf..efe52ccdb96 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/BatchMeasureToMeasureTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/BatchMeasureToMeasureTest.java @@ -34,6 +34,7 @@ import org.sonar.scanner.protocol.output.ScannerReport.Measure.LongValue; import org.sonar.scanner.protocol.output.ScannerReport.Measure.StringValue; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; @RunWith(DataProviderRunner.class) public class BatchMeasureToMeasureTest { @@ -54,14 +55,16 @@ public class BatchMeasureToMeasureTest { assertThat(underTest.toMeasure(null, SOME_INT_METRIC)).isNotPresent(); } - @Test(expected = NullPointerException.class) + @Test public void toMeasure_throws_NPE_if_metric_argument_is_null() { - underTest.toMeasure(EMPTY_BATCH_MEASURE, null); + assertThatThrownBy(() -> underTest.toMeasure(EMPTY_BATCH_MEASURE, null)) + .isInstanceOf(NullPointerException.class); } - @Test(expected = NullPointerException.class) + @Test public void toMeasure_throws_NPE_if_both_arguments_are_null() { - underTest.toMeasure(null, null); + assertThatThrownBy(() -> underTest.toMeasure(null, null)) + .isInstanceOf(NullPointerException.class); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/LiveMeasureDtoToMeasureTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/LiveMeasureDtoToMeasureTest.java index fed8783a3c7..7677858d438 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/LiveMeasureDtoToMeasureTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/LiveMeasureDtoToMeasureTest.java @@ -24,9 +24,7 @@ import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.Optional; import org.assertj.core.data.Offset; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.ce.task.projectanalysis.measure.Measure.Level; import org.sonar.ce.task.projectanalysis.metric.Metric; @@ -34,6 +32,7 @@ import org.sonar.ce.task.projectanalysis.metric.MetricImpl; import org.sonar.db.measure.LiveMeasureDto; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; @RunWith(DataProviderRunner.class) public class LiveMeasureDtoToMeasureTest { @@ -48,8 +47,6 @@ public class LiveMeasureDtoToMeasureTest { private static final String SOME_ALERT_TEXT = "some alert text_be_careFul!"; private static final LiveMeasureDto EMPTY_MEASURE_DTO = new LiveMeasureDto(); - @Rule - public final ExpectedException expectedException = ExpectedException.none(); private LiveMeasureDtoToMeasure underTest = new LiveMeasureDtoToMeasure(); @@ -58,14 +55,16 @@ public class LiveMeasureDtoToMeasureTest { assertThat(underTest.toMeasure(null, SOME_INT_METRIC)).isNotPresent(); } - @Test(expected = NullPointerException.class) + @Test public void toMeasure_throws_NPE_if_metric_argument_is_null() { - underTest.toMeasure(EMPTY_MEASURE_DTO, null); + assertThatThrownBy(() -> underTest.toMeasure(EMPTY_MEASURE_DTO, null)) + .isInstanceOf(NullPointerException.class); } - @Test(expected = NullPointerException.class) + @Test public void toMeasure_throws_NPE_if_both_arguments_are_null() { - underTest.toMeasure(null, null); + assertThatThrownBy(() -> underTest.toMeasure(null, null)) + .isInstanceOf(NullPointerException.class); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/MapBasedRawMeasureRepositoryTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/MapBasedRawMeasureRepositoryTest.java index 79bcec907c7..ea292c95d5d 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/MapBasedRawMeasureRepositoryTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/MapBasedRawMeasureRepositoryTest.java @@ -28,7 +28,6 @@ import java.util.Optional; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.api.utils.System2; import org.sonar.ce.task.projectanalysis.batch.BatchReportReader; @@ -43,6 +42,7 @@ import org.sonar.db.DbTester; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyNoMoreInteractions; @@ -52,8 +52,6 @@ import static org.mockito.Mockito.when; public class MapBasedRawMeasureRepositoryTest { @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private static final String FILE_COMPONENT_KEY = "file cpt key"; private static final ReportComponent FILE_COMPONENT = ReportComponent.builder(Component.Type.FILE, 1) @@ -92,45 +90,53 @@ public class MapBasedRawMeasureRepositoryTest { when(metricRepository.getByKey(METRIC_KEY_2)).thenReturn(metric2); } - @Test(expected = NullPointerException.class) + @Test public void add_throws_NPE_if_Component_argument_is_null() { - underTest.add(null, metric1, SOME_MEASURE); + assertThatThrownBy(() -> underTest.add(null, metric1, SOME_MEASURE)) + .isInstanceOf(NullPointerException.class); } - @Test(expected = NullPointerException.class) + @Test public void add_throws_NPE_if_Component_metric_is_null() { - underTest.add(FILE_COMPONENT, null, SOME_MEASURE); + assertThatThrownBy(() -> underTest.add(FILE_COMPONENT, null, SOME_MEASURE)) + .isInstanceOf(NullPointerException.class); } - @Test(expected = NullPointerException.class) + @Test public void add_throws_NPE_if_Component_measure_is_null() { - underTest.add(FILE_COMPONENT, metric1, null); + assertThatThrownBy(() -> underTest.add(FILE_COMPONENT, metric1, null)) + .isInstanceOf(NullPointerException.class); } - @Test(expected = UnsupportedOperationException.class) + @Test public void add_throws_UOE_if_measure_already_exists() { underTest.add(FILE_COMPONENT, metric1, SOME_MEASURE); - underTest.add(FILE_COMPONENT, metric1, SOME_MEASURE); + assertThatThrownBy(() -> underTest.add(FILE_COMPONENT, metric1, SOME_MEASURE)) + .isInstanceOf(UnsupportedOperationException.class); } - @Test(expected = NullPointerException.class) + @Test public void update_throws_NPE_if_Component_argument_is_null() { - underTest.update(null, metric1, SOME_MEASURE); + assertThatThrownBy(() -> underTest.update(null, metric1, SOME_MEASURE)) + .isInstanceOf(NullPointerException.class); } - @Test(expected = NullPointerException.class) + @Test public void update_throws_NPE_if_Component_metric_is_null() { - underTest.update(FILE_COMPONENT, null, SOME_MEASURE); + assertThatThrownBy(() -> underTest.update(FILE_COMPONENT, null, SOME_MEASURE)) + .isInstanceOf(NullPointerException.class); } - @Test(expected = NullPointerException.class) + @Test public void update_throws_NPE_if_Component_measure_is_null() { - underTest.update(FILE_COMPONENT, metric1, null); + assertThatThrownBy(() -> underTest.update(FILE_COMPONENT, metric1, null)) + .isInstanceOf(NullPointerException.class); } - @Test(expected = UnsupportedOperationException.class) + @Test public void update_throws_UOE_if_measure_does_not_exists() { - underTest.update(FILE_COMPONENT, metric1, SOME_MEASURE); + assertThatThrownBy(() -> underTest.update(FILE_COMPONENT, metric1, SOME_MEASURE)) + .isInstanceOf(UnsupportedOperationException.class); } private static final List MEASURES = ImmutableList.of( diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/MeasureComputersHolderImplTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/MeasureComputersHolderImplTest.java index 20eb8c9c95c..668be0e16d7 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/MeasureComputersHolderImplTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/MeasureComputersHolderImplTest.java @@ -21,18 +21,15 @@ package org.sonar.ce.task.projectanalysis.measure; import com.google.common.collect.ImmutableList; import java.util.Collections; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.ce.task.projectanalysis.api.measurecomputer.MeasureComputerWrapper; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; public class MeasureComputersHolderImplTest { - @Rule - public ExpectedException thrown = ExpectedException.none(); private MeasureComputersHolderImpl underTest = new MeasureComputersHolderImpl(); @@ -46,10 +43,9 @@ public class MeasureComputersHolderImplTest { @Test public void get_measure_computers_throws_ISE_if_not_initialized() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Measure computers have not been initialized yet"); - - underTest.getMeasureComputers(); + assertThatThrownBy(() -> underTest.getMeasureComputers()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Measure computers have not been initialized yet"); } @Test @@ -61,12 +57,13 @@ public class MeasureComputersHolderImplTest { @Test public void set_measure_computers_throws_ISE_if_already_initialized() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Measure computers have already been initialized"); - - MeasureComputerWrapper measureComputer = mock(MeasureComputerWrapper.class); - underTest.setMeasureComputers(Collections.singletonList(measureComputer)); - underTest.setMeasureComputers(Collections.singletonList(measureComputer)); + assertThatThrownBy(() -> { + MeasureComputerWrapper measureComputer = mock(MeasureComputerWrapper.class); + underTest.setMeasureComputers(Collections.singletonList(measureComputer)); + underTest.setMeasureComputers(Collections.singletonList(measureComputer)); + }) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Measure computers have already been initialized"); } } diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/MeasureDtoToMeasureTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/MeasureDtoToMeasureTest.java index cfc4d78f5bf..16d4aeb6f74 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/MeasureDtoToMeasureTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/MeasureDtoToMeasureTest.java @@ -24,9 +24,7 @@ import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.Optional; import org.assertj.core.data.Offset; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.ce.task.projectanalysis.measure.Measure.Level; import org.sonar.ce.task.projectanalysis.metric.Metric; @@ -34,6 +32,7 @@ import org.sonar.ce.task.projectanalysis.metric.MetricImpl; import org.sonar.db.measure.MeasureDto; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; @RunWith(DataProviderRunner.class) public class MeasureDtoToMeasureTest { @@ -48,8 +47,6 @@ public class MeasureDtoToMeasureTest { private static final String SOME_ALERT_TEXT = "some alert text_be_careFul!"; private static final MeasureDto EMPTY_MEASURE_DTO = new MeasureDto(); - @Rule - public final ExpectedException expectedException = ExpectedException.none(); private MeasureDtoToMeasure underTest = new MeasureDtoToMeasure(); @@ -58,14 +55,16 @@ public class MeasureDtoToMeasureTest { assertThat(underTest.toMeasure(null, SOME_INT_METRIC)).isNotPresent(); } - @Test(expected = NullPointerException.class) + @Test public void toMeasure_throws_NPE_if_metric_argument_is_null() { - underTest.toMeasure(EMPTY_MEASURE_DTO, null); + assertThatThrownBy(() -> underTest.toMeasure(EMPTY_MEASURE_DTO, null)) + .isInstanceOf(NullPointerException.class); } - @Test(expected = NullPointerException.class) + @Test public void toMeasure_throws_NPE_if_both_arguments_are_null() { - underTest.toMeasure(null, null); + assertThatThrownBy(() -> underTest.toMeasure(null, null)) + .isInstanceOf(NullPointerException.class); } @Test @@ -137,14 +136,16 @@ public class MeasureDtoToMeasureTest { assertThat(measure.get().getQualityGateStatus().getText()).isEqualTo(SOME_ALERT_TEXT); } - @Test(expected = IllegalStateException.class) + @Test public void toMeasure_for_LEVEL_Metric_ignores_data() { MeasureDto measureDto = new MeasureDto().setAlertStatus(Level.ERROR.name()).setData(SOME_DATA); Optional measure = underTest.toMeasure(measureDto, SOME_LEVEL_METRIC); assertThat(measure).isPresent(); - measure.get().getStringValue(); + + assertThatThrownBy(() ->measure.get().getStringValue()) + .isInstanceOf(IllegalStateException.class); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/MeasureRepositoryImplTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/MeasureRepositoryImplTest.java index 7476da047db..aa3e4d6db16 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/MeasureRepositoryImplTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/MeasureRepositoryImplTest.java @@ -31,7 +31,6 @@ import javax.annotation.Nullable; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.api.utils.System2; import org.sonar.ce.task.projectanalysis.batch.BatchReportReader; @@ -55,6 +54,7 @@ import org.sonar.scanner.protocol.output.ScannerReport.Measure.StringValue; import static com.google.common.collect.FluentIterable.from; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyNoMoreInteractions; @@ -65,8 +65,6 @@ import static org.sonar.db.component.ComponentTesting.newFileDto; @RunWith(DataProviderRunner.class) public class MeasureRepositoryImplTest { - @Rule - public final ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); @@ -167,52 +165,52 @@ public class MeasureRepositoryImplTest { @Test public void add_throws_NPE_if_Component_argument_is_null() { - expectedException.expect(NullPointerException.class); - underTest.add(null, metric1, SOME_MEASURE); + assertThatThrownBy(() -> underTest.add(null, metric1, SOME_MEASURE)) + .isInstanceOf(NullPointerException.class); } @Test public void add_throws_NPE_if_Component_metric_is_null() { - expectedException.expect(NullPointerException.class); - underTest.add(FILE_COMPONENT, null, SOME_MEASURE); + assertThatThrownBy(() -> underTest.add(FILE_COMPONENT, null, SOME_MEASURE)) + .isInstanceOf(NullPointerException.class); } @Test public void add_throws_NPE_if_Component_measure_is_null() { - expectedException.expect(NullPointerException.class); - underTest.add(FILE_COMPONENT, metric1, null); + assertThatThrownBy(() -> underTest.add(FILE_COMPONENT, metric1, null)) + .isInstanceOf(NullPointerException.class); } @Test public void add_throws_UOE_if_measure_already_exists() { - expectedException.expect(UnsupportedOperationException.class); - underTest.add(FILE_COMPONENT, metric1, SOME_MEASURE); - underTest.add(FILE_COMPONENT, metric1, SOME_MEASURE); + assertThatThrownBy(() -> { + underTest.add(FILE_COMPONENT, metric1, SOME_MEASURE); + underTest.add(FILE_COMPONENT, metric1, SOME_MEASURE); + }) + .isInstanceOf(UnsupportedOperationException.class); } @Test public void update_throws_NPE_if_Component_argument_is_null() { - expectedException.expect(NullPointerException.class); - underTest.update(null, metric1, SOME_MEASURE); + } @Test public void update_throws_NPE_if_Component_metric_is_null() { - expectedException.expect(NullPointerException.class); - underTest.update(FILE_COMPONENT, null, SOME_MEASURE); + assertThatThrownBy(() -> underTest.update(FILE_COMPONENT, null, SOME_MEASURE)) + .isInstanceOf(NullPointerException.class); } @Test public void update_throws_NPE_if_Component_measure_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expect(NullPointerException.class); - underTest.update(FILE_COMPONENT, metric1, null); + assertThatThrownBy(() -> underTest.update(FILE_COMPONENT, metric1, null)) + .isInstanceOf(NullPointerException.class); } @Test public void update_throws_UOE_if_measure_does_not_exists() { - expectedException.expect(UnsupportedOperationException.class); - underTest.update(FILE_COMPONENT, metric1, SOME_MEASURE); + assertThatThrownBy(() -> underTest.update(FILE_COMPONENT, metric1, SOME_MEASURE)) + .isInstanceOf(UnsupportedOperationException.class); } private static final List MEASURES = ImmutableList.of( diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/MeasureTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/MeasureTest.java index a0db538c998..597e4ec6f34 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/MeasureTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/MeasureTest.java @@ -24,14 +24,13 @@ import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.List; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.ce.task.projectanalysis.measure.Measure.ValueType; import org.sonar.ce.task.projectanalysis.util.WrapInSingleElementArray; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.ce.task.projectanalysis.measure.Measure.newMeasureBuilder; @RunWith(DataProviderRunner.class) @@ -49,8 +48,6 @@ public class MeasureTest { private static final List MEASURES = ImmutableList.of( INT_MEASURE, LONG_MEASURE, DOUBLE_MEASURE, STRING_MEASURE, TRUE_MEASURE, FALSE_MEASURE, NO_VALUE_MEASURE, LEVEL_MEASURE); - @Rule - public final ExpectedException expectedException = ExpectedException.none(); @DataProvider public static Object[][] all_but_INT_MEASURE() { @@ -94,9 +91,10 @@ public class MeasureTest { .toArray(Object[][]::new); } - @Test(expected = NullPointerException.class) + @Test public void create_from_String_throws_NPE_if_arg_is_null() { - newMeasureBuilder().create((String) null); + assertThatThrownBy(() -> newMeasureBuilder().create((String) null)) + .isInstanceOf(NullPointerException.class); } @Test @@ -125,10 +123,11 @@ public class MeasureTest { assertThat(STRING_MEASURE.getValueType()).isEqualTo(ValueType.STRING); } - @Test(expected = IllegalStateException.class) + @Test @UseDataProvider("all_but_INT_MEASURE") public void getIntValue_throws_ISE_for_all_value_types_except_INT(Measure measure) { - measure.getIntValue(); + assertThatThrownBy(measure::getIntValue) + .isInstanceOf(IllegalStateException.class); } @Test @@ -136,10 +135,11 @@ public class MeasureTest { assertThat(INT_MEASURE.getIntValue()).isEqualTo(1); } - @Test(expected = IllegalStateException.class) + @Test @UseDataProvider("all_but_LONG_MEASURE") public void getLongValue_throws_ISE_for_all_value_types_except_LONG(Measure measure) { - measure.getLongValue(); + assertThatThrownBy(measure::getLongValue) + .isInstanceOf(IllegalStateException.class); } @Test @@ -147,10 +147,11 @@ public class MeasureTest { assertThat(LONG_MEASURE.getLongValue()).isEqualTo(1); } - @Test(expected = IllegalStateException.class) + @Test @UseDataProvider("all_but_DOUBLE_MEASURE") public void getDoubleValue_throws_ISE_for_all_value_types_except_DOUBLE(Measure measure) { - measure.getDoubleValue(); + assertThatThrownBy(measure::getDoubleValue) + .isInstanceOf(IllegalStateException.class); } @Test @@ -158,10 +159,11 @@ public class MeasureTest { assertThat(DOUBLE_MEASURE.getDoubleValue()).isEqualTo(1d); } - @Test(expected = IllegalStateException.class) + @Test @UseDataProvider("all_but_BOOLEAN_MEASURE") public void getBooleanValue_throws_ISE_for_all_value_types_except_BOOLEAN(Measure measure) { - measure.getBooleanValue(); + assertThatThrownBy(measure::getBooleanValue) + .isInstanceOf(IllegalStateException.class); } @Test @@ -170,16 +172,18 @@ public class MeasureTest { assertThat(FALSE_MEASURE.getBooleanValue()).isFalse(); } - @Test(expected = IllegalStateException.class) + @Test @UseDataProvider("all_but_STRING_MEASURE") public void getStringValue_throws_ISE_for_all_value_types_except_STRING(Measure measure) { - measure.getStringValue(); + assertThatThrownBy(measure::getStringValue) + .isInstanceOf(IllegalStateException.class); } - @Test(expected = IllegalStateException.class) + @Test @UseDataProvider("all_but_LEVEL_MEASURE") public void getLevelValue_throws_ISE_for_all_value_types_except_LEVEL(Measure measure) { - measure.getLevelValue(); + assertThatThrownBy(measure::getLevelValue) + .isInstanceOf(IllegalStateException.class); } @Test @@ -204,10 +208,11 @@ public class MeasureTest { assertThat(measure.hasQualityGateStatus()).isFalse(); } - @Test(expected = IllegalStateException.class) + @Test @UseDataProvider("all") public void getAlertStatus_throws_ISE_for_all_value_types_when_not_set(Measure measure) { - measure.getQualityGateStatus(); + assertThatThrownBy(measure::getQualityGateStatus) + .isInstanceOf(IllegalStateException.class); } @Test @@ -223,26 +228,33 @@ public class MeasureTest { assertThat(newMeasureBuilder().setQualityGateStatus(someStatus).create(Measure.Level.OK).getQualityGateStatus()).isEqualTo(someStatus); } - @Test(expected = NullPointerException.class) + @Test public void newMeasureBuilder_setQualityGateStatus_throws_NPE_if_arg_is_null() { - newMeasureBuilder().setQualityGateStatus(null); + assertThatThrownBy(() -> newMeasureBuilder().setQualityGateStatus(null)) + .isInstanceOf(NullPointerException.class); } - @Test(expected = NullPointerException.class) + @Test public void updateMeasureBuilder_setQualityGateStatus_throws_NPE_if_arg_is_null() { - Measure.updatedMeasureBuilder(newMeasureBuilder().createNoValue()).setQualityGateStatus(null); + assertThatThrownBy(() -> { + Measure.updatedMeasureBuilder(newMeasureBuilder().createNoValue()).setQualityGateStatus(null); + }) + .isInstanceOf(NullPointerException.class); } - @Test(expected = UnsupportedOperationException.class) + @Test public void updateMeasureBuilder_setQualityGateStatus_throws_USO_if_measure_already_has_a_QualityGateStatus() { - QualityGateStatus qualityGateStatus = new QualityGateStatus(Measure.Level.ERROR); - - Measure.updatedMeasureBuilder(newMeasureBuilder().setQualityGateStatus(qualityGateStatus).createNoValue()).setQualityGateStatus(qualityGateStatus); + assertThatThrownBy(() -> { + QualityGateStatus qualityGateStatus = new QualityGateStatus(Measure.Level.ERROR); + Measure.updatedMeasureBuilder(newMeasureBuilder().setQualityGateStatus(qualityGateStatus).createNoValue()).setQualityGateStatus(qualityGateStatus); + }) + .isInstanceOf(UnsupportedOperationException.class); } - @Test(expected = UnsupportedOperationException.class) + @Test public void updateMeasureBuilder_setVariations_throws_USO_if_measure_already_has_Variations() { - Measure.updatedMeasureBuilder(newMeasureBuilder().setVariation(1d).createNoValue()).setVariation(2d); + assertThatThrownBy(() -> Measure.updatedMeasureBuilder(newMeasureBuilder().setVariation(1d).createNoValue()).setVariation(2d)) + .isInstanceOf(UnsupportedOperationException.class); } @Test @@ -281,18 +293,16 @@ public class MeasureTest { @Test public void create_with_double_value_throws_IAE_if_value_is_NaN() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("NaN is not allowed as a Measure value"); - - newMeasureBuilder().create(Double.NaN, 1); + assertThatThrownBy(() -> newMeasureBuilder().create(Double.NaN, 1)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("NaN is not allowed as a Measure value"); } @Test public void create_with_double_value_data_throws_IAE_if_value_is_NaN() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("NaN is not allowed as a Measure value"); - - newMeasureBuilder().create(Double.NaN, 1, "some data"); + assertThatThrownBy(() -> newMeasureBuilder().create(Double.NaN, 1, "some data")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("NaN is not allowed as a Measure value"); } } diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/MeasureToMeasureDtoTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/MeasureToMeasureDtoTest.java index 3fd2916344a..5773cd52374 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/MeasureToMeasureDtoTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/MeasureToMeasureDtoTest.java @@ -36,6 +36,7 @@ import org.sonar.db.measure.LiveMeasureDto; import org.sonar.db.measure.MeasureDto; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; @RunWith(DataProviderRunner.class) public class MeasureToMeasureDtoTest { @@ -65,14 +66,16 @@ public class MeasureToMeasureDtoTest { analysisMetadataHolder.setUuid(ANALYSIS_UUID); } - @Test(expected = NullPointerException.class) + @Test public void toMeasureDto_throws_NPE_if_Measure_arg_is_null() { - underTest.toMeasureDto(null, SOME_METRIC, SOME_COMPONENT); + assertThatThrownBy(() -> underTest.toMeasureDto(null, SOME_METRIC, SOME_COMPONENT)) + .isInstanceOf(NullPointerException.class); } - @Test(expected = NullPointerException.class) + @Test public void toMeasureDto_throws_NPE_if_Metric_arg_is_null() { - underTest.toMeasureDto(Measure.newMeasureBuilder().createNoValue(), null, SOME_COMPONENT); + assertThatThrownBy(() -> underTest.toMeasureDto(Measure.newMeasureBuilder().createNoValue(), null, SOME_COMPONENT)) + .isInstanceOf(NullPointerException.class); } @DataProvider diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/PostMeasuresComputationChecksStepTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/PostMeasuresComputationChecksStepTest.java index cf9529770bc..a9d8bb93a34 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/PostMeasuresComputationChecksStepTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/PostMeasuresComputationChecksStepTest.java @@ -21,7 +21,6 @@ package org.sonar.ce.task.projectanalysis.measure; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; import org.mockito.InOrder; import org.sonar.api.measures.CoreMetrics; @@ -54,8 +53,6 @@ public class PostMeasuresComputationChecksStepTest { public MeasureRepositoryRule measureRepository = MeasureRepositoryRule.create(treeRootHolder, metricRepository); @Rule public AnalysisMetadataHolderRule analysisMetadataHolder = new AnalysisMetadataHolderRule(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void execute_extensions() { diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/QualityGateStatusTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/QualityGateStatusTest.java index dc651379e52..45418c0228c 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/QualityGateStatusTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/QualityGateStatusTest.java @@ -22,19 +22,22 @@ package org.sonar.ce.task.projectanalysis.measure; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class QualityGateStatusTest { private static final String SOME_TEXT = "some text"; - @Test(expected = NullPointerException.class) + @Test public void one_arg_constructor_throws_NPE_if_Level_arg_is_null() { - new QualityGateStatus(null); + assertThatThrownBy(() -> new QualityGateStatus(null)) + .isInstanceOf(NullPointerException.class); } - @Test(expected = NullPointerException.class) + @Test public void two_args_constructor_throws_NPE_if_Level_arg_is_null() { - new QualityGateStatus(null, SOME_TEXT); + assertThatThrownBy(() -> new QualityGateStatus(null, SOME_TEXT)) + .isInstanceOf(NullPointerException.class); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/qualitygatedetails/EvaluatedConditionTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/qualitygatedetails/EvaluatedConditionTest.java index 3ad2788035c..84136205e2a 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/qualitygatedetails/EvaluatedConditionTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/qualitygatedetails/EvaluatedConditionTest.java @@ -25,6 +25,7 @@ import org.sonar.ce.task.projectanalysis.metric.Metric; import org.sonar.ce.task.projectanalysis.qualitygate.Condition; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -38,14 +39,16 @@ public class EvaluatedConditionTest { private static final Measure.Level SOME_LEVEL = Measure.Level.OK; private static final String SOME_VALUE = "some value"; - @Test(expected = NullPointerException.class) + @Test public void constructor_throws_NPE_if_Condition_arg_is_null() { - new EvaluatedCondition(null, SOME_LEVEL, SOME_VALUE); + assertThatThrownBy(() -> new EvaluatedCondition(null, SOME_LEVEL, SOME_VALUE)) + .isInstanceOf(NullPointerException.class); } - @Test(expected = NullPointerException.class) + @Test public void constructor_throws_NPE_if_Level_arg_is_null() { - new EvaluatedCondition(SOME_CONDITION, null, SOME_VALUE); + assertThatThrownBy(() -> new EvaluatedCondition(SOME_CONDITION, null, SOME_VALUE)) + .isInstanceOf(NullPointerException.class); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/qualitygatedetails/QualityGateDetailsDataTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/qualitygatedetails/QualityGateDetailsDataTest.java index 7ec8ff3db7b..ce03de5f3d5 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/qualitygatedetails/QualityGateDetailsDataTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/qualitygatedetails/QualityGateDetailsDataTest.java @@ -28,15 +28,19 @@ import org.sonar.ce.task.projectanalysis.metric.MetricImpl; import org.sonar.ce.task.projectanalysis.qualitygate.Condition; import org.sonar.test.JsonAssert; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + public class QualityGateDetailsDataTest { - @Test(expected = NullPointerException.class) + @Test public void constructor_throws_NPE_if_Level_arg_is_null() { - new QualityGateDetailsData(null, Collections.emptyList(), false); + assertThatThrownBy(() -> new QualityGateDetailsData(null, Collections.emptyList(), false)) + .isInstanceOf(NullPointerException.class); } - @Test(expected = NullPointerException.class) + @Test public void constructor_throws_NPE_if_Iterable_arg_is_null() { - new QualityGateDetailsData(Measure.Level.OK, null, false); + assertThatThrownBy(() -> new QualityGateDetailsData(Measure.Level.OK, null, false)) + .isInstanceOf(NullPointerException.class); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/metric/MetricDtoToMetricTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/metric/MetricDtoToMetricTest.java index 4cc4bb5f88d..d122152e0c8 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/metric/MetricDtoToMetricTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/metric/MetricDtoToMetricTest.java @@ -23,6 +23,7 @@ import org.junit.Test; import org.sonar.db.metric.MetricDto; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class MetricDtoToMetricTest { @@ -30,9 +31,10 @@ public class MetricDtoToMetricTest { private MetricDtoToMetric underTest = MetricDtoToMetric.INSTANCE; - @Test(expected = NullPointerException.class) + @Test public void apply_throws_NPE_if_arg_is_null() { - underTest.apply(null); + assertThatThrownBy(() -> underTest.apply(null)) + .isInstanceOf(NullPointerException.class); } @Test @@ -57,9 +59,10 @@ public class MetricDtoToMetricTest { assertThat(underTest.apply(createMetricDto(Metric.MetricType.INT).setOptimizedBestValue(true)).isBestValueOptimized()).isTrue(); } - @Test(expected = IllegalArgumentException.class) + @Test public void apply_throws_IAE_if_valueType_can_not_be_parsed() { - underTest.apply(new MetricDto().setUuid("1").setKey("key").setValueType("trololo")); + assertThatThrownBy(() -> underTest.apply(new MetricDto().setUuid("1").setKey("key").setValueType("trololo"))) + .isInstanceOf(IllegalArgumentException.class); } private static MetricDto createMetricDto(Metric.MetricType metricType) { diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/metric/MetricImplTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/metric/MetricImplTest.java index f24a68bdb3f..ac63bf3763e 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/metric/MetricImplTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/metric/MetricImplTest.java @@ -19,41 +19,40 @@ */ package org.sonar.ce.task.projectanalysis.metric; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class MetricImplTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private static final String SOME_UUID = "uuid"; private static final String SOME_KEY = "key"; private static final String SOME_NAME = "name"; - @Test(expected = NullPointerException.class) + @Test public void constructor_throws_NPE_if_key_arg_is_null() { - new MetricImpl(SOME_UUID, null, SOME_NAME, Metric.MetricType.BOOL); + assertThatThrownBy(() -> new MetricImpl(SOME_UUID, null, SOME_NAME, Metric.MetricType.BOOL)) + .isInstanceOf(NullPointerException.class); } - @Test(expected = NullPointerException.class) + @Test public void constructor_throws_NPE_if_name_arg_is_null() { - new MetricImpl(SOME_UUID, SOME_KEY, null, Metric.MetricType.BOOL); + assertThatThrownBy(() -> new MetricImpl(SOME_UUID, SOME_KEY, null, Metric.MetricType.BOOL)) + .isInstanceOf(NullPointerException.class); } - @Test(expected = NullPointerException.class) + @Test public void constructor_throws_NPE_if_valueType_arg_is_null() { - new MetricImpl(SOME_UUID, SOME_KEY, SOME_NAME, null); + assertThatThrownBy(() -> new MetricImpl(SOME_UUID, SOME_KEY, SOME_NAME, null)) + .isInstanceOf(NullPointerException.class); } @Test public void constructor_throws_IAE_if_bestValueOptimized_is_true_but_bestValue_is_null() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("A BestValue must be specified if Metric is bestValueOptimized"); - - new MetricImpl(SOME_UUID, SOME_KEY, SOME_NAME, Metric.MetricType.INT, 1, null, true, false); + assertThatThrownBy(() -> new MetricImpl(SOME_UUID, SOME_KEY, SOME_NAME, Metric.MetricType.INT, 1, null, true, false)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("A BestValue must be specified if Metric is bestValueOptimized"); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/metric/MetricRepositoryImplTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/metric/MetricRepositoryImplTest.java index fe2f5866c95..c6b63ea2fd0 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/metric/MetricRepositoryImplTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/metric/MetricRepositoryImplTest.java @@ -19,19 +19,19 @@ */ package org.sonar.ce.task.projectanalysis.metric; +import java.util.List; +import java.util.Random; +import java.util.stream.Collectors; +import java.util.stream.IntStream; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.utils.System2; import org.sonar.db.DbClient; import org.sonar.db.DbTester; import org.sonar.db.metric.MetricDto; import static org.assertj.core.api.Assertions.assertThat; -import java.util.List; -import java.util.Random; -import java.util.stream.Collectors; -import java.util.stream.IntStream; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class MetricRepositoryImplTest { private static final String SOME_KEY = "some_key"; @@ -39,33 +39,31 @@ public class MetricRepositoryImplTest { @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); - @Rule - public final ExpectedException expectedException = ExpectedException.none(); private DbClient dbClient = dbTester.getDbClient(); private MetricRepositoryImpl underTest = new MetricRepositoryImpl(dbClient); - @Test(expected = NullPointerException.class) + @Test public void getByKey_throws_NPE_if_arg_is_null() { - underTest.getByKey(null); + assertThatThrownBy(() -> underTest.getByKey(null)) + .isInstanceOf(NullPointerException.class); } @Test public void getByKey_throws_ISE_if_start_has_not_been_called() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Metric cache has not been initialized"); - - underTest.getByKey(SOME_KEY); + assertThatThrownBy(() -> underTest.getByKey(SOME_KEY)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Metric cache has not been initialized"); } @Test public void getByKey_throws_ISE_of_Metric_does_not_exist() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage(String.format("Metric with key '%s' does not exist", SOME_KEY)); - - underTest.start(); - - underTest.getByKey(SOME_KEY); + assertThatThrownBy(() -> { + underTest.start(); + underTest.getByKey(SOME_KEY); + }) + .isInstanceOf(IllegalStateException.class) + .hasMessage(String.format("Metric with key '%s' does not exist", SOME_KEY)); } @Test @@ -74,10 +72,9 @@ public class MetricRepositoryImplTest { underTest.start(); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage(String.format("Metric with key '%s' does not exist", "complexity")); - - underTest.getByKey("complexity"); + assertThatThrownBy(() -> underTest.getByKey("complexity")) + .isInstanceOf(IllegalStateException.class) + .hasMessage(String.format("Metric with key '%s' does not exist", "complexity")); } @Test @@ -93,20 +90,18 @@ public class MetricRepositoryImplTest { @Test public void getById_throws_ISE_if_start_has_not_been_called() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Metric cache has not been initialized"); - - underTest.getByUuid(SOME_UUID); + assertThatThrownBy(() -> underTest.getByUuid(SOME_UUID)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Metric cache has not been initialized"); } @Test public void getById_throws_ISE_of_Metric_does_not_exist() { underTest.start(); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage(String.format("Metric with uuid '%s' does not exist", SOME_UUID)); - - underTest.getByUuid(SOME_UUID); + assertThatThrownBy(() -> underTest.getByUuid(SOME_UUID)) + .isInstanceOf(IllegalStateException.class) + .hasMessage(String.format("Metric with uuid '%s' does not exist", SOME_UUID)); } @Test @@ -115,10 +110,9 @@ public class MetricRepositoryImplTest { underTest.start(); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage(String.format("Metric with uuid '%s' does not exist", SOME_UUID)); - - underTest.getByUuid(SOME_UUID); + assertThatThrownBy(() -> underTest.getByUuid(SOME_UUID)) + .isInstanceOf(IllegalStateException.class) + .hasMessage(String.format("Metric with uuid '%s' does not exist", SOME_UUID)); } @Test @@ -134,10 +128,9 @@ public class MetricRepositoryImplTest { @Test public void getOptionalById_throws_ISE_if_start_has_not_been_called() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Metric cache has not been initialized"); - - underTest.getOptionalByUuid(SOME_UUID); + assertThatThrownBy(() -> underTest.getOptionalByUuid(SOME_UUID)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Metric cache has not been initialized"); } @Test @@ -214,9 +207,8 @@ public class MetricRepositoryImplTest { @Test public void getMetricsByType_givenMetricsAreNull_throwException() { - expectedException.expect(IllegalStateException.class); - - underTest.getMetricsByType(Metric.MetricType.RATING); + assertThatThrownBy(() -> underTest.getMetricsByType(Metric.MetricType.RATING)) + .isInstanceOf(IllegalStateException.class); } } diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/notification/NotificationFactoryTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/notification/NotificationFactoryTest.java index fe860ea0521..eeab88e4b12 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/notification/NotificationFactoryTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/notification/NotificationFactoryTest.java @@ -34,7 +34,6 @@ import java.util.stream.IntStream; import java.util.stream.Stream; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.sonar.api.rule.RuleKey; @@ -62,6 +61,7 @@ import org.sonar.server.issue.notification.NewIssuesNotification.RuleDefinition; import static java.util.Collections.emptyMap; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -81,8 +81,6 @@ public class NotificationFactoryTest { public RuleRepositoryRule ruleRepository = new RuleRepositoryRule(); @Rule public AnalysisMetadataHolderRule analysisMetadata = new AnalysisMetadataHolderRule(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private Durations durations = new Durations(); private IssuesChangesNotificationSerializer issuesChangesSerializer = mock(IssuesChangesNotificationSerializer.class); @@ -90,18 +88,16 @@ public class NotificationFactoryTest { @Test public void newMyNewIssuesNotification_throws_NPE_if_assigneesByUuid_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("assigneesByUuid can't be null"); - - underTest.newMyNewIssuesNotification(null); + assertThatThrownBy(() -> underTest.newMyNewIssuesNotification(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("assigneesByUuid can't be null"); } @Test public void newNewIssuesNotification_throws_NPE_if_assigneesByUuid_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("assigneesByUuid can't be null"); - - underTest.newNewIssuesNotification(null); + assertThatThrownBy(() -> underTest.newNewIssuesNotification(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("assigneesByUuid can't be null"); } @Test @@ -124,10 +120,9 @@ public class NotificationFactoryTest { DetailsSupplier detailsSupplier = readDetailsSupplier(underTest); - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("uuid can't be null"); - - detailsSupplier.getUserNameByUuid(null); + assertThatThrownBy(() -> detailsSupplier.getUserNameByUuid(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("uuid can't be null"); } @Test @@ -169,10 +164,9 @@ public class NotificationFactoryTest { DetailsSupplier detailsSupplier = readDetailsSupplier(underTest); - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("uuid can't be null"); - - detailsSupplier.getUserNameByUuid(null); + assertThatThrownBy(() -> detailsSupplier.getUserNameByUuid(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("uuid can't be null"); } @Test @@ -214,10 +208,9 @@ public class NotificationFactoryTest { DetailsSupplier detailsSupplier = readDetailsSupplier(underTest); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Holder has not been initialized yet"); - - detailsSupplier.getComponentNameByUuid("foo"); + assertThatThrownBy(() -> detailsSupplier.getComponentNameByUuid("foo")) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Holder has not been initialized yet"); } @Test @@ -228,10 +221,9 @@ public class NotificationFactoryTest { DetailsSupplier detailsSupplier = readDetailsSupplier(underTest); - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("uuid can't be null"); - - detailsSupplier.getComponentNameByUuid(null); + assertThatThrownBy(() -> detailsSupplier.getComponentNameByUuid(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("uuid can't be null"); } @Test @@ -275,10 +267,9 @@ public class NotificationFactoryTest { DetailsSupplier detailsSupplier = readDetailsSupplier(underTest); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Holder has not been initialized yet"); - - detailsSupplier.getComponentNameByUuid("foo"); + assertThatThrownBy(() -> detailsSupplier.getComponentNameByUuid("foo")) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Holder has not been initialized yet"); } @Test @@ -288,10 +279,9 @@ public class NotificationFactoryTest { DetailsSupplier detailsSupplier = readDetailsSupplier(underTest); - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("uuid can't be null"); - - detailsSupplier.getComponentNameByUuid(null); + assertThatThrownBy(() -> detailsSupplier.getComponentNameByUuid(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("uuid can't be null"); } @Test @@ -336,10 +326,9 @@ public class NotificationFactoryTest { DetailsSupplier detailsSupplier = readDetailsSupplier(underTest); - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("ruleKey can't be null"); - - detailsSupplier.getRuleDefinitionByRuleKey(null); + assertThatThrownBy(() -> detailsSupplier.getRuleDefinitionByRuleKey(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("ruleKey can't be null"); } @Test @@ -381,10 +370,9 @@ public class NotificationFactoryTest { DetailsSupplier detailsSupplier = readDetailsSupplier(underTest); - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("ruleKey can't be null"); - - detailsSupplier.getRuleDefinitionByRuleKey(null); + assertThatThrownBy(() -> detailsSupplier.getRuleDefinitionByRuleKey(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("ruleKey can't be null"); } @Test @@ -427,10 +415,9 @@ public class NotificationFactoryTest { .collect(Collectors.toSet()); Map assigneesByUuid = nonEmptyAssigneesByUuid(); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Analysis date has not been set"); - - underTest.newIssuesChangesNotification(issues, assigneesByUuid); + assertThatThrownBy(() -> underTest.newIssuesChangesNotification(issues, assigneesByUuid)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Analysis date has not been set"); } @Test @@ -438,10 +425,9 @@ public class NotificationFactoryTest { analysisMetadata.setAnalysisDate(new Random().nextLong()); Map assigneesByUuid = nonEmptyAssigneesByUuid(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("issues can't be empty"); - - underTest.newIssuesChangesNotification(Collections.emptySet(), assigneesByUuid); + assertThatThrownBy(() -> underTest.newIssuesChangesNotification(Collections.emptySet(), assigneesByUuid)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("issues can't be empty"); } @Test @@ -450,9 +436,8 @@ public class NotificationFactoryTest { Map assigneesByUuid = nonEmptyAssigneesByUuid(); analysisMetadata.setAnalysisDate(new Random().nextLong()); - expectedException.expect(NullPointerException.class); - - underTest.newIssuesChangesNotification(ImmutableSet.of(issue), assigneesByUuid); + assertThatThrownBy(() -> underTest.newIssuesChangesNotification(ImmutableSet.of(issue), assigneesByUuid)) + .isInstanceOf(NullPointerException.class); } @Test @@ -463,10 +448,9 @@ public class NotificationFactoryTest { Map assigneesByUuid = nonEmptyAssigneesByUuid(); analysisMetadata.setAnalysisDate(new Random().nextLong()); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Can not find rule " + ruleKey + " in RuleRepository"); - - underTest.newIssuesChangesNotification(ImmutableSet.of(issue), assigneesByUuid); + assertThatThrownBy(() -> underTest.newIssuesChangesNotification(ImmutableSet.of(issue), assigneesByUuid)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Can not find rule " + ruleKey + " in RuleRepository"); } @Test @@ -478,10 +462,9 @@ public class NotificationFactoryTest { ruleRepository.add(ruleKey); analysisMetadata.setAnalysisDate(new Random().nextLong()); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Holder has not been initialized yet"); - - underTest.newIssuesChangesNotification(ImmutableSet.of(issue), assigneesByUuid); + assertThatThrownBy(() -> underTest.newIssuesChangesNotification(ImmutableSet.of(issue), assigneesByUuid)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Holder has not been initialized yet"); } @Test @@ -494,10 +477,9 @@ public class NotificationFactoryTest { analysisMetadata.setAnalysisDate(new Random().nextLong()); treeRootHolder.setRoot(ReportComponent.builder(PROJECT, 1).build()); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Branch has not been set"); - - underTest.newIssuesChangesNotification(ImmutableSet.of(issue), assigneesByUuid); + assertThatThrownBy(() -> underTest.newIssuesChangesNotification(ImmutableSet.of(issue), assigneesByUuid)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Branch has not been set"); } @Test @@ -511,10 +493,9 @@ public class NotificationFactoryTest { analysisMetadata.setAnalysisDate(new Random().nextLong()); analysisMetadata.setBranch(mock(Branch.class)); - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("key can't be null"); - - underTest.newIssuesChangesNotification(ImmutableSet.of(issue), assigneesByUuid); + assertThatThrownBy(() -> underTest.newIssuesChangesNotification(ImmutableSet.of(issue), assigneesByUuid)) + .isInstanceOf(NullPointerException.class) + .hasMessage("key can't be null"); } @Test @@ -529,10 +510,9 @@ public class NotificationFactoryTest { analysisMetadata.setAnalysisDate(new Random().nextLong()); analysisMetadata.setBranch(mock(Branch.class)); - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("newStatus can't be null"); - - underTest.newIssuesChangesNotification(ImmutableSet.of(issue), assigneesByUuid); + assertThatThrownBy(() -> underTest.newIssuesChangesNotification(ImmutableSet.of(issue), assigneesByUuid)) + .isInstanceOf(NullPointerException.class) + .hasMessage("newStatus can't be null"); } @Test @@ -652,10 +632,9 @@ public class NotificationFactoryTest { analysisMetadata.setAnalysisDate(new Random().nextLong()); analysisMetadata.setBranch(newNonMainBranch(BranchType.BRANCH, randomAlphabetic(12))); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Can not find DTO for assignee uuid " + assigneeUuid); - - underTest.newIssuesChangesNotification(ImmutableSet.of(issue), assigneesByUuid); + assertThatThrownBy(() -> underTest.newIssuesChangesNotification(ImmutableSet.of(issue), assigneesByUuid)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Can not find DTO for assignee uuid " + assigneeUuid); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/period/PeriodHolderImplTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/period/PeriodHolderImplTest.java index a47ba6df607..ab608a7c5b4 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/period/PeriodHolderImplTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/period/PeriodHolderImplTest.java @@ -19,16 +19,13 @@ */ package org.sonar.ce.task.projectanalysis.period; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class PeriodHolderImplTest { - @Rule - public ExpectedException thrown = ExpectedException.none(); private PeriodHolderImpl underTest = new PeriodHolderImpl(); @@ -42,19 +39,19 @@ public class PeriodHolderImplTest { @Test public void get_period_throws_illegal_state_exception_if_not_initialized() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Period have not been initialized yet"); - - new PeriodHolderImpl().getPeriod(); + assertThatThrownBy(() -> new PeriodHolderImpl().getPeriod()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Period have not been initialized yet"); } @Test public void setPeriod_throws_ISE_if_already_initialized() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Period have already been initialized"); - - underTest.setPeriod(createPeriod()); - underTest.setPeriod(createPeriod()); + assertThatThrownBy(() -> { + underTest.setPeriod(createPeriod()); + underTest.setPeriod(createPeriod()); + }) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Period have already been initialized"); } @Test @@ -79,10 +76,9 @@ public class PeriodHolderImplTest { @Test public void hasPeriod_throws_ISE_if_not_initialized() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Period have not been initialized yet"); - - underTest.hasPeriod(); + assertThatThrownBy(() -> underTest.hasPeriod()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Period have not been initialized yet"); } private static Period createPeriod() { diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/period/PeriodTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/period/PeriodTest.java index e51ad7528da..4881ea3cfda 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/period/PeriodTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/period/PeriodTest.java @@ -19,9 +19,7 @@ */ package org.sonar.ce.task.projectanalysis.period; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.db.newcodeperiod.NewCodePeriodType; import static org.assertj.core.api.Assertions.assertThat; @@ -31,8 +29,6 @@ public class PeriodTest { private static final String SOME_MODE_PARAM = "mode_para"; private static final long SOME_SNAPSHOT_DATE = 1000L; - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void test_some_setters_and_getters() { diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitygate/ConditionEvaluatorTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitygate/ConditionEvaluatorTest.java index 60df6c8bf85..a52bbe14a4d 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitygate/ConditionEvaluatorTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitygate/ConditionEvaluatorTest.java @@ -23,9 +23,7 @@ import com.google.common.collect.ImmutableSet; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.ce.task.projectanalysis.measure.Measure; import org.sonar.ce.task.projectanalysis.metric.Metric; @@ -35,10 +33,11 @@ import static com.google.common.base.Predicates.in; import static com.google.common.base.Predicates.not; import static com.google.common.collect.FluentIterable.from; import static java.util.Arrays.asList; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.fail; +import static org.sonar.ce.task.projectanalysis.measure.Measure.newMeasureBuilder; import static org.sonar.ce.task.projectanalysis.measure.Measure.Level.ERROR; import static org.sonar.ce.task.projectanalysis.measure.Measure.Level.OK; -import static org.sonar.ce.task.projectanalysis.measure.Measure.newMeasureBuilder; import static org.sonar.ce.task.projectanalysis.metric.Metric.MetricType; import static org.sonar.ce.task.projectanalysis.metric.Metric.MetricType.BOOL; import static org.sonar.ce.task.projectanalysis.metric.Metric.MetricType.DATA; @@ -57,8 +56,6 @@ import static org.sonar.ce.task.projectanalysis.qualitygate.EvaluationResultAsse @RunWith(DataProviderRunner.class) public class ConditionEvaluatorTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private ConditionEvaluator underTest = new ConditionEvaluator(); @@ -114,10 +111,9 @@ public class ConditionEvaluatorTest { Metric metric = createMetric(WORK_DUR); Measure measure = newMeasureBuilder().create(60l, null); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Quality Gate: Unable to parse value 'polop' to compare against name"); - - underTest.evaluate(createCondition(metric, LESS_THAN, "polop"), measure); + assertThatThrownBy(() -> underTest.evaluate(createCondition(metric, LESS_THAN, "polop"), measure)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Quality Gate: Unable to parse value 'polop' to compare against name"); } @Test @@ -147,10 +143,9 @@ public class ConditionEvaluatorTest { Metric metric = createMetric(metricType); Measure measure = newMeasureBuilder().create("3.14159265358"); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(String.format("Conditions on MetricType %s are not supported", metricType)); - - underTest.evaluate(createCondition(metric, LESS_THAN, "1.60217657"), measure); + assertThatThrownBy(() -> underTest.evaluate(createCondition(metric, LESS_THAN, "1.60217657"), measure)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage(String.format("Conditions on MetricType %s are not supported", metricType)); } @DataProvider @@ -196,10 +191,9 @@ public class ConditionEvaluatorTest { Metric metric = createNewMetric(LEVEL); Measure measure = newMeasureBuilder().setVariation(0d).createNoValue(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Unsupported metric type LEVEL"); - - underTest.evaluate(new Condition(metric, LESS_THAN.getDbValue(), "3"), measure); + assertThatThrownBy(() -> underTest.evaluate(new Condition(metric, LESS_THAN.getDbValue(), "3"), measure)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Unsupported metric type LEVEL"); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitygate/ConditionStatusTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitygate/ConditionStatusTest.java index b7fc04d2ede..15e9f629396 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitygate/ConditionStatusTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitygate/ConditionStatusTest.java @@ -22,12 +22,11 @@ package org.sonar.ce.task.projectanalysis.qualitygate; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.ce.task.projectanalysis.qualitygate.ConditionStatus.EvaluationStatus.NO_VALUE; import static org.sonar.ce.task.projectanalysis.qualitygate.ConditionStatus.EvaluationStatus.OK; import static org.sonar.ce.task.projectanalysis.qualitygate.ConditionStatus.EvaluationStatus.values; @@ -36,32 +35,27 @@ import static org.sonar.ce.task.projectanalysis.qualitygate.ConditionStatus.Eval public class ConditionStatusTest { private static final String SOME_VALUE = "value"; - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void create_throws_NPE_if_status_argument_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("status can not be null"); - - ConditionStatus.create(null, SOME_VALUE); + assertThatThrownBy(() -> ConditionStatus.create(null, SOME_VALUE)) + .isInstanceOf(NullPointerException.class) + .hasMessage("status can not be null"); } @Test public void create_throws_IAE_if_status_argument_is_NO_VALUE() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("EvaluationStatus 'NO_VALUE' can not be used with this method, use constant ConditionStatus.NO_VALUE_STATUS instead."); - - ConditionStatus.create(NO_VALUE, SOME_VALUE); + assertThatThrownBy(() -> ConditionStatus.create(NO_VALUE, SOME_VALUE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("EvaluationStatus 'NO_VALUE' can not be used with this method, use constant ConditionStatus.NO_VALUE_STATUS instead."); } @Test @UseDataProvider("allStatusesButNO_VALUE") public void create_throws_NPE_if_value_is_null_and_status_argument_is_not_NO_VALUE(ConditionStatus.EvaluationStatus status) { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("value can not be null"); - - ConditionStatus.create(status, null); + assertThatThrownBy(() -> ConditionStatus.create(status, null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("value can not be null"); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitygate/ConditionTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitygate/ConditionTest.java index 29876999e6b..c5d9c06a19d 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitygate/ConditionTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitygate/ConditionTest.java @@ -20,19 +20,16 @@ package org.sonar.ce.task.projectanalysis.qualitygate; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.ce.task.projectanalysis.metric.Metric; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class ConditionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private static final Metric SOME_METRIC = mock(Metric.class); private static final String SOME_OPERATOR = "LT"; @@ -42,22 +39,23 @@ public class ConditionTest { when(SOME_METRIC.getKey()).thenReturn("dummy key"); } - @Test(expected = NullPointerException.class) + @Test public void constructor_throws_NPE_for_null_metric_argument() { - new Condition(null, SOME_OPERATOR, null); + assertThatThrownBy(() -> new Condition(null, SOME_OPERATOR, null)) + .isInstanceOf(NullPointerException.class); } - @Test(expected = NullPointerException.class) + @Test public void constructor_throws_NPE_for_null_operator_argument() { - new Condition(SOME_METRIC, null, null); + assertThatThrownBy(() -> new Condition(SOME_METRIC, null, null)) + .isInstanceOf(NullPointerException.class); } @Test public void constructor_throws_IAE_if_operator_is_not_valid() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Unsupported operator value: 'troloto'"); - - new Condition(SOME_METRIC, "troloto", null); + assertThatThrownBy(() -> new Condition(SOME_METRIC, "troloto", null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Unsupported operator value: 'troloto'"); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitygate/EvaluationResultTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitygate/EvaluationResultTest.java index 996419838b3..f10e645473d 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitygate/EvaluationResultTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitygate/EvaluationResultTest.java @@ -23,11 +23,13 @@ import org.junit.Test; import org.sonar.ce.task.projectanalysis.measure.Measure; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class EvaluationResultTest { - @Test(expected = NullPointerException.class) + @Test public void constructor_throws_NPE_if_Level_arg_is_null() { - new EvaluationResult(null, 11); + assertThatThrownBy(() -> new EvaluationResult(null, 11)) + .isInstanceOf(NullPointerException.class); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitygate/EvaluationResultTextConverterTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitygate/EvaluationResultTextConverterTest.java index ace8b973742..757eb8cf5bd 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitygate/EvaluationResultTextConverterTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitygate/EvaluationResultTextConverterTest.java @@ -34,6 +34,7 @@ import org.sonar.ce.task.projectanalysis.metric.MetricImpl; import org.sonar.core.i18n.I18n; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.ce.task.projectanalysis.measure.Measure.Level.ERROR; @@ -50,14 +51,16 @@ public class EvaluationResultTextConverterTest { private Durations durations = mock(Durations.class); private EvaluationResultTextConverter underTest = new EvaluationResultTextConverterImpl(i18n, durations); - @Test(expected = NullPointerException.class) + @Test public void evaluate_throws_NPE_if_Condition_arg_is_null() { - underTest.asText(null, OK_EVALUATION_RESULT); + assertThatThrownBy(() -> underTest.asText(null, OK_EVALUATION_RESULT)) + .isInstanceOf(NullPointerException.class); } - @Test(expected = NullPointerException.class) + @Test public void evaluate_throws_NPE_if_EvaluationResult_arg_is_null() { - underTest.asText(LT_10_CONDITION, null); + assertThatThrownBy(() -> underTest.asText(LT_10_CONDITION, null)) + .isInstanceOf(NullPointerException.class); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitygate/QualityGateHolderImplTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitygate/QualityGateHolderImplTest.java index 00550e12d13..45ffa2d2c6f 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitygate/QualityGateHolderImplTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitygate/QualityGateHolderImplTest.java @@ -24,28 +24,34 @@ import org.sonar.server.qualitygate.EvaluatedQualityGate; import static java.util.Collections.emptyList; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; public class QualityGateHolderImplTest { private static final QualityGate QUALITY_GATE = new QualityGate("4612", "name", emptyList()); - @Test(expected = IllegalStateException.class) + @Test public void getQualityGate_throws_ISE_if_QualityGate_not_set() { - new QualityGateHolderImpl().getQualityGate(); + assertThatThrownBy(() -> new QualityGateHolderImpl().getQualityGate()) + .isInstanceOf(IllegalStateException.class); } - @Test(expected = NullPointerException.class) + @Test public void setQualityGate_throws_NPE_if_argument_is_null() { - new QualityGateHolderImpl().setQualityGate(null); + assertThatThrownBy(() -> new QualityGateHolderImpl().setQualityGate(null)) + .isInstanceOf(NullPointerException.class); } - @Test(expected = IllegalStateException.class) + @Test public void setQualityGate_throws_ISE_if_called_twice() { - QualityGateHolderImpl holder = new QualityGateHolderImpl(); + assertThatThrownBy(() -> { + QualityGateHolderImpl holder = new QualityGateHolderImpl(); - holder.setQualityGate(QUALITY_GATE); - holder.setQualityGate(QUALITY_GATE); + holder.setQualityGate(QUALITY_GATE); + holder.setQualityGate(QUALITY_GATE); + }) + .isInstanceOf(IllegalStateException.class); } @Test @@ -57,23 +63,28 @@ public class QualityGateHolderImplTest { assertThat(holder.getQualityGate().get()).isSameAs(QUALITY_GATE); } - @Test(expected = IllegalStateException.class) + @Test public void getEvaluation_throws_ISE_if_QualityGate_not_set() { - new QualityGateHolderImpl().getEvaluation(); + assertThatThrownBy(() -> new QualityGateHolderImpl().getEvaluation()) + .isInstanceOf(IllegalStateException.class); } - @Test(expected = NullPointerException.class) + @Test public void setEvaluation_throws_NPE_if_argument_is_null() { - new QualityGateHolderImpl().setEvaluation(null); + assertThatThrownBy(() -> new QualityGateHolderImpl().setEvaluation(null)) + .isInstanceOf(NullPointerException.class); } - @Test(expected = IllegalStateException.class) + @Test public void setEvaluation_throws_ISE_if_called_twice() { - QualityGateHolderImpl holder = new QualityGateHolderImpl(); - - EvaluatedQualityGate evaluation = mock(EvaluatedQualityGate.class); - holder.setEvaluation(evaluation); - holder.setEvaluation(evaluation); + assertThatThrownBy(() -> { + QualityGateHolderImpl holder = new QualityGateHolderImpl(); + + EvaluatedQualityGate evaluation = mock(EvaluatedQualityGate.class); + holder.setEvaluation(evaluation); + holder.setEvaluation(evaluation); + }) + .isInstanceOf(IllegalStateException.class); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitygate/QualityGateServiceImplTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitygate/QualityGateServiceImplTest.java index 71238508647..4a117899121 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitygate/QualityGateServiceImplTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitygate/QualityGateServiceImplTest.java @@ -36,6 +36,7 @@ import org.sonar.db.qualitygate.QualityGateDto; import org.sonar.server.project.Project; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; @@ -124,11 +125,12 @@ public class QualityGateServiceImplTest { new Condition(METRIC_2, CONDITION_2.getOperator(), CONDITION_2.getErrorThreshold())); } - @Test(expected = IllegalStateException.class) + @Test public void findDefaultQualityGate_by_property_not_found() { when(propertiesDao.selectGlobalProperty(any(), any())).thenReturn(null); - underTest.findDefaultQualityGate(); + assertThatThrownBy(() -> underTest.findDefaultQualityGate()) + .isInstanceOf(IllegalStateException.class); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitygate/QualityGateStatusHolderImplTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitygate/QualityGateStatusHolderImplTest.java index 3a7c2228a64..afa697acc3a 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitygate/QualityGateStatusHolderImplTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitygate/QualityGateStatusHolderImplTest.java @@ -24,12 +24,12 @@ import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.Collections; import java.util.Map; -import org.junit.Rule; +import org.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; @RunWith(DataProviderRunner.class) @@ -37,42 +37,35 @@ public class QualityGateStatusHolderImplTest { private static final Map SOME_STATUS_PER_CONDITION = Collections.singletonMap( mock(Condition.class), ConditionStatus.create(ConditionStatus.EvaluationStatus.OK, "val")); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private QualityGateStatusHolderImpl underTest = new QualityGateStatusHolderImpl(); @Test public void setStatus_throws_NPE_if_globalStatus_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("global status can not be null"); - - underTest.setStatus(null, SOME_STATUS_PER_CONDITION); + assertThatThrownBy(() -> underTest.setStatus(null, SOME_STATUS_PER_CONDITION)) + .isInstanceOf(NullPointerException.class) + .hasMessage("global status can not be null"); } @Test public void setStatus_throws_NPE_if_statusPerCondition_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("status per condition can not be null"); - - underTest.setStatus(QualityGateStatus.OK, null); + assertThatThrownBy(() -> underTest.setStatus(QualityGateStatus.OK, null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("status per condition can not be null"); } @Test public void setStatus_throws_ISE_if_called_twice() { underTest.setStatus(QualityGateStatus.OK, SOME_STATUS_PER_CONDITION); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Quality gate status has already been set in the holder"); - - underTest.setStatus(null, null); + assertThatThrownBy(() -> underTest.setStatus(null, null)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Quality gate status has already been set in the holder"); } @Test public void getStatus_throws_ISE_if_setStatus_not_called_yet() { - expectQGNotSetYetISE(); - - underTest.getStatus(); + expectQGNotSetYetISE(() -> underTest.getStatus()); } @Test @@ -85,9 +78,7 @@ public class QualityGateStatusHolderImplTest { @Test public void getStatusPerConditions_throws_ISE_if_setStatus_not_called_yet() { - expectQGNotSetYetISE(); - - underTest.getStatusPerConditions(); + expectQGNotSetYetISE(() -> underTest.getStatusPerConditions()); } @Test @@ -99,9 +90,10 @@ public class QualityGateStatusHolderImplTest { assertThat(underTest.getStatusPerConditions()).isNotSameAs(SOME_STATUS_PER_CONDITION); } - private void expectQGNotSetYetISE() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Quality gate status has not been set yet"); + private void expectQGNotSetYetISE(ThrowingCallable callback) { + assertThatThrownBy(callback) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Quality gate status has not been set yet"); } @DataProvider diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitymodel/RatingSettingsTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitymodel/RatingSettingsTest.java index 64a49e3cb4a..c244be643af 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitymodel/RatingSettingsTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitymodel/RatingSettingsTest.java @@ -19,9 +19,7 @@ */ package org.sonar.ce.task.projectanalysis.qualitymodel; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.CoreProperties; import org.sonar.api.config.PropertyDefinitions; import org.sonar.api.config.internal.MapSettings; @@ -31,6 +29,7 @@ import org.sonar.api.utils.System2; import org.sonar.core.config.CorePropertyDefinitions; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.CoreProperties.DEVELOPMENT_COST; import static org.sonar.api.CoreProperties.LANGUAGE_SPECIFIC_PARAMETERS; import static org.sonar.api.CoreProperties.LANGUAGE_SPECIFIC_PARAMETERS_LANGUAGE_KEY; @@ -40,8 +39,6 @@ public class RatingSettingsTest { private MapSettings settings = new MapSettings(new PropertyDefinitions(System2.INSTANCE, CorePropertyDefinitions.all())); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void load_rating_grid() { @@ -86,10 +83,12 @@ public class RatingSettingsTest { @Test public void fail_on_invalid_rating_grid_configuration() { - expectedException.expect(IllegalArgumentException.class); - settings.setProperty(CoreProperties.RATING_GRID, "a b c"); + assertThatThrownBy(() -> { + settings.setProperty(CoreProperties.RATING_GRID, "a b c"); + new RatingSettings(settings.asConfig()); + }) + .isInstanceOf(IllegalArgumentException.class); - new RatingSettings(settings.asConfig()); } @Test @@ -112,10 +111,9 @@ public class RatingSettingsTest { settings.setProperty(LANGUAGE_SPECIFIC_PARAMETERS, "0"); settings.setProperty(LANGUAGE_SPECIFIC_PARAMETERS + "." + "0" + "." + LANGUAGE_SPECIFIC_PARAMETERS_MAN_DAYS_KEY, "40"); - expectedException.expect(MessageException.class); - expectedException.expectMessage("Technical debt configuration is corrupted. At least one language specific parameter has no Language key. " + - "Contact your administrator to update this configuration in the global administration section of SonarQube."); - - new RatingSettings(settings.asConfig()); + assertThatThrownBy(() -> new RatingSettings(settings.asConfig())) + .isInstanceOf(MessageException.class) + .hasMessage("Technical debt configuration is corrupted. At least one language specific parameter has no Language key. " + + "Contact your administrator to update this configuration in the global administration section of SonarQube."); } } diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualityprofile/ActiveRulesHolderImplTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualityprofile/ActiveRulesHolderImplTest.java index 95789aede3c..6c54e24c888 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualityprofile/ActiveRulesHolderImplTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualityprofile/ActiveRulesHolderImplTest.java @@ -21,14 +21,13 @@ package org.sonar.ce.task.projectanalysis.qualityprofile; import java.util.Collections; import java.util.Optional; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.rule.RuleKey; import org.sonar.api.rule.Severity; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class ActiveRulesHolderImplTest { @@ -39,8 +38,6 @@ public class ActiveRulesHolderImplTest { static final RuleKey RULE_KEY = RuleKey.of("squid", "S001"); private static final String QP_KEY = "qp1"; - @Rule - public ExpectedException thrown = ExpectedException.none(); ActiveRulesHolderImpl underTest = new ActiveRulesHolderImpl(); @@ -63,29 +60,29 @@ public class ActiveRulesHolderImplTest { @Test public void can_not_set_twice() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Active rules have already been initialized"); - - underTest.set(asList(new ActiveRule(RULE_KEY, Severity.BLOCKER, Collections.emptyMap(), SOME_DATE, PLUGIN_KEY, QP_KEY))); - underTest.set(Collections.emptyList()); - + assertThatThrownBy(() -> { + underTest.set(asList(new ActiveRule(RULE_KEY, Severity.BLOCKER, Collections.emptyMap(), SOME_DATE, PLUGIN_KEY, QP_KEY))); + underTest.set(Collections.emptyList()); + }) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Active rules have already been initialized"); } @Test public void can_not_get_if_not_initialized() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Active rules have not been initialized yet"); - - underTest.get(RULE_KEY); + assertThatThrownBy(() -> underTest.get(RULE_KEY)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Active rules have not been initialized yet"); } @Test public void can_not_set_duplicated_rules() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Active rule must not be declared multiple times: squid:S001"); - - underTest.set(asList( - new ActiveRule(RULE_KEY, Severity.BLOCKER, Collections.emptyMap(), SOME_DATE, PLUGIN_KEY, QP_KEY), - new ActiveRule(RULE_KEY, Severity.MAJOR, Collections.emptyMap(), SOME_DATE, PLUGIN_KEY, QP_KEY))); + assertThatThrownBy(() -> { + underTest.set(asList( + new ActiveRule(RULE_KEY, Severity.BLOCKER, Collections.emptyMap(), SOME_DATE, PLUGIN_KEY, QP_KEY), + new ActiveRule(RULE_KEY, Severity.MAJOR, Collections.emptyMap(), SOME_DATE, PLUGIN_KEY, QP_KEY))); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Active rule must not be declared multiple times: squid:S001"); } } diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualityprofile/QProfileStatusRepositoryImplTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualityprofile/QProfileStatusRepositoryImplTest.java index adb9b007db2..7445abe535e 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualityprofile/QProfileStatusRepositoryImplTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualityprofile/QProfileStatusRepositoryImplTest.java @@ -25,18 +25,15 @@ import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.Optional; import java.util.stream.Stream; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; @RunWith(DataProviderRunner.class) public class QProfileStatusRepositoryImplTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private QProfileStatusRepositoryImpl underTest; @Before @@ -68,28 +65,26 @@ public class QProfileStatusRepositoryImplTest { @Test @UseDataProvider("qualityProfileStatuses") public void register_fails_with_NPE_if_qpKey_is_null(QProfileStatusRepository.Status status) { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("qpKey can't be null"); - - underTest.register(null, status); + assertThatThrownBy(() -> underTest.register(null, status)) + .isInstanceOf(NullPointerException.class) + .hasMessage("qpKey can't be null"); } @Test public void register_fails_with_NPE_if_status_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("status can't be null"); - - underTest.register("key", null); + assertThatThrownBy(() -> underTest.register("key", null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("status can't be null"); } @Test @UseDataProvider("qualityProfileStatuses") public void register_fails_with_ISE_if_qp_is_already_registered(QProfileStatusRepository.Status status) { underTest.register("key", status); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Quality Profile 'key' is already registered"); - underTest.register("key", status); + assertThatThrownBy(() -> underTest.register("key", status)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Quality Profile 'key' is already registered"); } @DataProvider diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/scm/ChangesetTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/scm/ChangesetTest.java index bf3363aeb6b..73b1c158b5c 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/scm/ChangesetTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/scm/ChangesetTest.java @@ -19,16 +19,13 @@ */ package org.sonar.ce.task.projectanalysis.scm; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class ChangesetTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void create_changeset() { @@ -56,21 +53,21 @@ public class ChangesetTest { @Test public void fail_with_NPE_when_setting_null_date() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("Date cannot be null"); - - Changeset.newChangesetBuilder().setDate(null); + assertThatThrownBy(() -> Changeset.newChangesetBuilder().setDate(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("Date cannot be null"); } @Test public void fail_with_NPE_when_building_without_date() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("Date cannot be null"); - - Changeset.newChangesetBuilder() - .setAuthor("john") - .setRevision("rev-1") - .build(); + assertThatThrownBy(() -> { + Changeset.newChangesetBuilder() + .setAuthor("john") + .setRevision("rev-1") + .build(); + }) + .isInstanceOf(NullPointerException.class) + .hasMessage("Date cannot be null"); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/scm/DbScmInfoTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/scm/DbScmInfoTest.java index 4a53d0dc65a..66ca4bc7e33 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/scm/DbScmInfoTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/scm/DbScmInfoTest.java @@ -19,9 +19,7 @@ */ package org.sonar.ce.task.projectanalysis.scm; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.db.protobuf.DbFileSources; import static org.assertj.core.api.Assertions.assertThat; @@ -29,8 +27,6 @@ import static org.sonar.server.source.index.FileSourceTesting.newFakeData; public class DbScmInfoTest { - @Rule - public ExpectedException thrown = ExpectedException.none(); @Test public void create_scm_info_with_some_changesets() { diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/scm/ReportScmInfoTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/scm/ReportScmInfoTest.java index a5c3e37311a..11310008459 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/scm/ReportScmInfoTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/scm/ReportScmInfoTest.java @@ -19,18 +19,14 @@ */ package org.sonar.ce.task.projectanalysis.scm; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.scanner.protocol.output.ScannerReport; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class ReportScmInfoTest { - @Rule - public ExpectedException thrown = ExpectedException.none(); - static final int FILE_REF = 1; @Test @@ -112,46 +108,47 @@ public class ReportScmInfoTest { @Test public void fail_with_ISE_when_no_changeset() { - thrown.expect(IllegalStateException.class); - - ReportScmInfo.create(ScannerReport.Changesets.newBuilder().build()); + assertThatThrownBy(() -> ReportScmInfo.create(ScannerReport.Changesets.newBuilder().build())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ScmInfo cannot be empty"); } @Test public void fail_with_NPE_when_report_is_null() { - thrown.expect(NullPointerException.class); - - ReportScmInfo.create(null); + assertThatThrownBy(() -> ReportScmInfo.create(null)) + .isInstanceOf(NullPointerException.class); } @Test public void fail_with_ISE_when_changeset_has_no_revision() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Changeset on line 1 must have a revision"); - - ReportScmInfo.create(ScannerReport.Changesets.newBuilder() - .setComponentRef(FILE_REF) - .addChangeset(ScannerReport.Changesets.Changeset.newBuilder() - .setAuthor("john") - .setDate(123456789L) - .build()) - .addChangesetIndexByLine(0) - .build()); + assertThatThrownBy(() -> { + ReportScmInfo.create(ScannerReport.Changesets.newBuilder() + .setComponentRef(FILE_REF) + .addChangeset(ScannerReport.Changesets.Changeset.newBuilder() + .setAuthor("john") + .setDate(123456789L) + .build()) + .addChangesetIndexByLine(0) + .build()); + }) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Changeset on line 1 must have a revision"); } @Test public void fail_with_ISE_when_changeset_has_no_date() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Changeset on line 1 must have a date"); - - ReportScmInfo.create(ScannerReport.Changesets.newBuilder() - .setComponentRef(FILE_REF) - .addChangeset(ScannerReport.Changesets.Changeset.newBuilder() - .setAuthor("john") - .setRevision("rev-1") - .build()) - .addChangesetIndexByLine(0) - .build()); + assertThatThrownBy(() -> { + ReportScmInfo.create(ScannerReport.Changesets.newBuilder() + .setComponentRef(FILE_REF) + .addChangeset(ScannerReport.Changesets.Changeset.newBuilder() + .setAuthor("john") + .setRevision("rev-1") + .build()) + .addChangesetIndexByLine(0) + .build()); + }) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Changeset on line 1 must have a date"); } } diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/scm/ScmInfoImplTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/scm/ScmInfoImplTest.java index ccb15ea05d5..8c471771f98 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/scm/ScmInfoImplTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/scm/ScmInfoImplTest.java @@ -19,16 +19,13 @@ */ package org.sonar.ce.task.projectanalysis.scm; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class ScmInfoImplTest { - @Rule - public ExpectedException thrown = ExpectedException.none(); static final Changeset CHANGESET_1 = Changeset.newChangesetBuilder() .setAuthor("john") @@ -76,28 +73,29 @@ public class ScmInfoImplTest { @Test public void fail_with_ISE_on_empty_changeset() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("ScmInfo cannot be empty"); - - new ScmInfoImpl(new Changeset[0]); + assertThatThrownBy(() -> new ScmInfoImpl(new Changeset[0])) + .isInstanceOf(IllegalStateException.class) + .hasMessage("ScmInfo cannot be empty"); } @Test public void fail_with_IAE_when_line_is_smaller_than_one() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("There's no changeset on line 0"); - - ScmInfo scmInfo = createScmInfoWithTwoChangestOnFourLines(); - scmInfo.getChangesetForLine(0); + assertThatThrownBy(() -> { + ScmInfo scmInfo = createScmInfoWithTwoChangestOnFourLines(); + scmInfo.getChangesetForLine(0); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("There's no changeset on line 0"); } @Test public void fail_with_IAE_when_line_is_bigger_than_changetset_size() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("There's no changeset on line 5"); - - ScmInfo scmInfo = createScmInfoWithTwoChangestOnFourLines(); - scmInfo.getChangesetForLine(5); + assertThatThrownBy(() -> { + ScmInfo scmInfo = createScmInfoWithTwoChangestOnFourLines(); + scmInfo.getChangesetForLine(5); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("There's no changeset on line 5"); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/scm/ScmInfoRepositoryImplTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/scm/ScmInfoRepositoryImplTest.java index 809d9a526af..c6f4a5fef6d 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/scm/ScmInfoRepositoryImplTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/scm/ScmInfoRepositoryImplTest.java @@ -31,7 +31,6 @@ import java.util.Optional; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.api.utils.log.LogTester; import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule; @@ -50,6 +49,7 @@ import org.sonar.scanner.protocol.output.ScannerReport; import org.sonar.scanner.protocol.output.ScannerReport.Changesets; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; @@ -67,8 +67,6 @@ public class ScmInfoRepositoryImplTest { static final long DATE_1 = 123456789L; static final long DATE_2 = 1234567810L; - @Rule - public ExpectedException thrown = ExpectedException.none(); @Rule public LogTester logTester = new LogTester(); @Rule @@ -222,10 +220,9 @@ public class ScmInfoRepositoryImplTest { @Test public void fail_with_NPE_when_component_is_null() { - thrown.expect(NullPointerException.class); - thrown.expectMessage("Component cannot be null"); - - underTest.getScmInfo(null); + assertThatThrownBy(() -> underTest.getScmInfo(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("Component cannot be null"); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/DbLineHashVersionTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/DbLineHashVersionTest.java index 63f87b1ce5c..33b5e7e15b5 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/DbLineHashVersionTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/DbLineHashVersionTest.java @@ -22,7 +22,6 @@ package org.sonar.ce.task.projectanalysis.source; import org.junit.Rule; import org.junit.Test; import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder; -import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.ReferenceBranchComponentUuids; import org.sonar.ce.task.projectanalysis.component.ReportComponent; diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/FileSourceDataWarningsTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/FileSourceDataWarningsTest.java index d36ce663db0..244b6a4d066 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/FileSourceDataWarningsTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/FileSourceDataWarningsTest.java @@ -26,9 +26,7 @@ import java.util.Arrays; import java.util.Random; import java.util.stream.Collectors; import java.util.stream.IntStream; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.api.utils.System2; import org.sonar.ce.task.log.CeTaskMessages; @@ -37,6 +35,7 @@ import org.sonar.ce.task.projectanalysis.component.ReportComponent; import org.sonar.ce.task.projectanalysis.source.linereader.LineReader; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -47,8 +46,6 @@ import static org.sonar.ce.task.projectanalysis.source.linereader.LineReader.Dat @RunWith(DataProviderRunner.class) public class FileSourceDataWarningsTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private CeTaskMessages taskMessages = mock(CeTaskMessages.class); private System2 system2 = mock(System2.class); @@ -63,40 +60,36 @@ public class FileSourceDataWarningsTest { public void addWarning_fails_with_NPE_if_file_is_null() { LineReader.ReadError readError = new LineReader.ReadError(HIGHLIGHTING, 2); - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("file can't be null"); - - underTest.addWarning(null, readError); + assertThatThrownBy(() -> underTest.addWarning(null, readError)) + .isInstanceOf(NullPointerException.class) + .hasMessage("file can't be null"); } @Test public void addWarning_fails_with_NPE_if_readError_is_null() { Component component = mock(Component.class); - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("readError can't be null"); - - underTest.addWarning(component, null); + assertThatThrownBy(() -> underTest.addWarning(component, null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("readError can't be null"); } @Test public void addWarnings_fails_with_ISE_if_called_after_commitWarnings() { underTest.commitWarnings(); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("warnings already commit"); - - underTest.addWarning(null /*doesn't matter*/, null /*doesn't matter*/); + assertThatThrownBy(() -> underTest.addWarning(null /*doesn't matter*/, null /*doesn't matter*/)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("warnings already commit"); } @Test public void commitWarnings_fails_with_ISE_if_called_after_commitWarnings() { underTest.commitWarnings(); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("warnings already commit"); - - underTest.commitWarnings(); + assertThatThrownBy(() -> underTest.commitWarnings()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("warnings already commit"); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/PersistFileSourcesStepTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/PersistFileSourcesStepTest.java index 74d50985059..5e03cfd893c 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/PersistFileSourcesStepTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/PersistFileSourcesStepTest.java @@ -27,7 +27,6 @@ import org.apache.commons.codec.digest.DigestUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.Mockito; import org.sonar.api.utils.System2; import org.sonar.ce.task.projectanalysis.component.Component; @@ -63,8 +62,6 @@ public class PersistFileSourcesStepTest extends BaseStepTest { private System2 system2 = mock(System2.class); - @Rule - public ExpectedException thrown = ExpectedException.none(); @Rule public DbTester dbTester = DbTester.create(system2); @Rule diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/RangeOffsetConverterTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/RangeOffsetConverterTest.java index 010c35dcb67..704653f291f 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/RangeOffsetConverterTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/RangeOffsetConverterTest.java @@ -19,19 +19,16 @@ */ package org.sonar.ce.task.projectanalysis.source; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.ce.task.projectanalysis.source.linereader.RangeOffsetConverter; import org.sonar.ce.task.projectanalysis.source.linereader.RangeOffsetConverter.RangeOffsetConverterException; import org.sonar.scanner.protocol.output.ScannerReport; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class RangeOffsetConverterTest { - @Rule - public ExpectedException thrown = ExpectedException.none(); static final int LINE_1 = 1; static final int LINE_2 = 2; @@ -91,29 +88,23 @@ public class RangeOffsetConverterTest { @Test public void fail_when_end_offset_is_before_start_offset() { - thrown.expect(RangeOffsetConverterException.class); - thrown.expectMessage("End offset 2 cannot be defined before start offset 4 on line 1"); - - underTest.offsetToString(createTextRange(LINE_1, LINE_1, OFFSET_4, OFFSET_2), - LINE_1, DEFAULT_LINE_LENGTH); + assertThatThrownBy(() -> underTest.offsetToString(createTextRange(LINE_1, LINE_1, OFFSET_4, OFFSET_2), LINE_1, DEFAULT_LINE_LENGTH)) + .isInstanceOf(RangeOffsetConverterException.class) + .hasMessage("End offset 2 cannot be defined before start offset 4 on line 1"); } @Test public void fail_when_end_offset_is_higher_than_line_length() { - thrown.expect(RangeOffsetConverterException.class); - thrown.expectMessage("End offset 10 is defined outside the length (5) of the line 1"); - - underTest.offsetToString(createTextRange(LINE_1, LINE_1, OFFSET_4, BIG_OFFSET), - LINE_1, DEFAULT_LINE_LENGTH); + assertThatThrownBy(() -> underTest.offsetToString(createTextRange(LINE_1, LINE_1, OFFSET_4, BIG_OFFSET), LINE_1, DEFAULT_LINE_LENGTH)) + .isInstanceOf(RangeOffsetConverterException.class) + .hasMessage("End offset 10 is defined outside the length (5) of the line 1"); } @Test public void fail_when_start_offset_is_higher_than_line_length() { - thrown.expect(RangeOffsetConverterException.class); - thrown.expectMessage("Start offset 10 is defined outside the length (5) of the line 1"); - - underTest.offsetToString(createTextRange(LINE_1, LINE_1, BIG_OFFSET, BIG_OFFSET + 1), - LINE_1, DEFAULT_LINE_LENGTH); + assertThatThrownBy(() -> underTest.offsetToString(createTextRange(LINE_1, LINE_1, BIG_OFFSET, BIG_OFFSET + 1), LINE_1, DEFAULT_LINE_LENGTH)) + .isInstanceOf(RangeOffsetConverterException.class) + .hasMessage("Start offset 10 is defined outside the length (5) of the line 1"); } private static ScannerReport.TextRange createTextRange(int startLine, int enLine, int startOffset, int endOffset) { diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/ReportIteratorTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/ReportIteratorTest.java index e41e881df55..9a251227ca0 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/ReportIteratorTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/ReportIteratorTest.java @@ -32,6 +32,7 @@ import org.sonar.scanner.protocol.output.ScannerReportWriter; import static com.google.common.collect.Lists.newArrayList; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class ReportIteratorTest { @@ -77,13 +78,16 @@ public class ReportIteratorTest { assertThat(underTest.hasNext()).isFalse(); } - @Test(expected = NoSuchElementException.class) + @Test public void test_error() { underTest = new ReportIterator<>(file, ScannerReport.LineCoverage.parser()); underTest.next(); - // fail ! - underTest.next(); + assertThatThrownBy(() -> { + // fail ! + underTest.next(); + }) + .isInstanceOf(NoSuchElementException.class); } } diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/SignificantCodeRepositoryTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/SignificantCodeRepositoryTest.java index a08457ba9ca..7257dbc4103 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/SignificantCodeRepositoryTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/SignificantCodeRepositoryTest.java @@ -23,7 +23,6 @@ import java.util.ArrayList; import java.util.List; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.ce.task.projectanalysis.batch.BatchReportReaderRule; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.FileAttributes; @@ -39,8 +38,6 @@ public class SignificantCodeRepositoryTest { private static final String FILE_KEY = "FILE_KEY"; private static final int FILE_REF = 2; - @Rule - public ExpectedException thrown = ExpectedException.none(); @Rule public BatchReportReaderRule reportReader = new BatchReportReaderRule(); diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/SourceHashRepositoryImplTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/SourceHashRepositoryImplTest.java index 6f6bf6b003f..6d81571f88a 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/SourceHashRepositoryImplTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/SourceHashRepositoryImplTest.java @@ -29,7 +29,6 @@ import java.util.Arrays; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.ReportComponent; @@ -38,6 +37,7 @@ import org.sonar.core.hash.SourceHashComputer; import org.sonar.core.util.CloseableIterator; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -52,8 +52,6 @@ public class SourceHashRepositoryImplTest { @Rule public SourceLinesRepositoryRule sourceLinesRepository = new SourceLinesRepositoryRule(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private SourceLinesRepository mockedSourceLinesRepository = mock(SourceLinesRepository.class); @@ -62,19 +60,17 @@ public class SourceHashRepositoryImplTest { @Test public void getRawSourceHash_throws_NPE_if_Component_argument_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("Specified component can not be null"); - - underTest.getRawSourceHash(null); + assertThatThrownBy(() -> underTest.getRawSourceHash(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("Specified component can not be null"); } @Test @UseDataProvider("componentsOfAllTypesButFile") public void getRawSourceHash_throws_IAE_if_Component_argument_is_not_FILE(Component component) { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("File source information can only be retrieved from FILE components (got " + component.getType() + ")"); - - underTest.getRawSourceHash(component); + assertThatThrownBy(() -> underTest.getRawSourceHash(component)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("File source information can only be retrieved from FILE components (got " + component.getType() + ")"); } @DataProvider @@ -141,9 +137,8 @@ public class SourceHashRepositoryImplTest { IllegalArgumentException thrown = new IllegalArgumentException("this IAE will cause the hash computation to fail"); when(mockedSourceLinesRepository.readLines(FILE_COMPONENT)).thenThrow(thrown); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(thrown.getMessage()); - - mockedUnderTest.getRawSourceHash(FILE_COMPONENT); + assertThatThrownBy(() -> mockedUnderTest.getRawSourceHash(FILE_COMPONENT)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage(thrown.getMessage()); } } diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/SourceLinesHashCacheTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/SourceLinesHashCacheTest.java index a44c165d4fd..f93f4f899e0 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/SourceLinesHashCacheTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/SourceLinesHashCacheTest.java @@ -25,12 +25,12 @@ import java.util.function.Function; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.impl.utils.JUnitTempFolder; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -42,8 +42,6 @@ public class SourceLinesHashCacheTest { @Rule public JUnitTempFolder tempFolder = new JUnitTempFolder(); - @Rule - public ExpectedException exception = ExpectedException.none(); private SourceLinesHashCache underTest; @@ -73,9 +71,9 @@ public class SourceLinesHashCacheTest { public void get_throws_ISE_if_not_cached() { Component component = createComponent(1); - exception.expect(IllegalStateException.class); - exception.expectMessage("Source line hashes for component ReportComponent{ref=1, key='FILE_KEY', type=FILE} not cached"); - underTest.get(component); + assertThatThrownBy(() -> underTest.get(component)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Source line hashes for component ReportComponent{ref=1, key='FILE_KEY', type=FILE} not cached"); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/SourceLinesRepositoryImplTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/SourceLinesRepositoryImplTest.java index 87ca84a0faf..7fc2c514cb4 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/SourceLinesRepositoryImplTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/SourceLinesRepositoryImplTest.java @@ -21,13 +21,13 @@ package org.sonar.ce.task.projectanalysis.source; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.ce.task.projectanalysis.batch.BatchReportReaderRule; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.FileAttributes; import org.sonar.core.util.CloseableIterator; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.ce.task.projectanalysis.component.ReportComponent.builder; public class SourceLinesRepositoryImplTest { @@ -36,8 +36,6 @@ public class SourceLinesRepositoryImplTest { private static final String FILE_KEY = "FILE_KEY"; private static final int FILE_REF = 2; - @Rule - public ExpectedException thrown = ExpectedException.none(); @Rule public BatchReportReaderRule reportReader = new BatchReportReaderRule(); @@ -62,47 +60,44 @@ public class SourceLinesRepositoryImplTest { public void read_lines_throws_ISE_when_sourceLine_has_less_elements_then_lineCount_minus_1() { reportReader.putFileSourceLines(FILE_REF, "line1", "line2"); - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Source of file 'ReportComponent{ref=2, key='FILE_KEY', type=FILE}' has less lines (2) than the expected number (10)"); - - consume(underTest.readLines(createComponent(10))); + assertThatThrownBy(() -> consume(underTest.readLines(createComponent(10)))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Source of file 'ReportComponent{ref=2, key='FILE_KEY', type=FILE}' has less lines (2) than the expected number (10)"); } @Test public void read_lines_throws_ISE_when_sourceLines_has_more_elements_then_lineCount() { reportReader.putFileSourceLines(FILE_REF, "line1", "line2", "line3"); - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Source of file 'ReportComponent{ref=2, key='FILE_KEY', type=FILE}' has at least one more line than the expected number (2)"); - - consume(underTest.readLines(createComponent(2))); + assertThatThrownBy(() -> consume(underTest.readLines(createComponent(2)))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Source of file 'ReportComponent{ref=2, key='FILE_KEY', type=FILE}' has at least one more line than the expected number (2)"); } @Test public void fail_with_ISE_when_file_has_no_source() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("File 'ReportComponent{ref=2, key='FILE_KEY', type=FILE}' has no source code"); - - underTest.readLines(builder(Component.Type.FILE, FILE_REF) - .setKey(FILE_KEY) - .setUuid(FILE_UUID) - .build()); + assertThatThrownBy(() -> { + underTest.readLines(builder(Component.Type.FILE, FILE_REF) + .setKey(FILE_KEY) + .setUuid(FILE_UUID) + .build()); + }) + .isInstanceOf(IllegalStateException.class) + .hasMessage("File 'ReportComponent{ref=2, key='FILE_KEY', type=FILE}' has no source code"); } @Test public void fail_with_NPE_to_read_lines_on_null_component() { - thrown.expect(NullPointerException.class); - thrown.expectMessage("Component should not be null"); - - underTest.readLines(null); + assertThatThrownBy(() -> underTest.readLines(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("Component should not be null"); } @Test public void fail_with_IAE_to_read_lines_on_not_file_component() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Component 'ReportComponent{ref=123, key='NotFile', type=PROJECT}' is not a file"); - - underTest.readLines(builder(Component.Type.PROJECT, 123).setKey("NotFile").build()); + assertThatThrownBy(() -> underTest.readLines(builder(Component.Type.PROJECT, 123).setKey("NotFile").build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Component 'ReportComponent{ref=123, key='NotFile', type=PROJECT}' is not a file"); } private static Component createComponent(int lineCount) { diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/BuildComponentTreeStepTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/BuildComponentTreeStepTest.java index 7865510cf97..d0758cb671b 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/BuildComponentTreeStepTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/BuildComponentTreeStepTest.java @@ -51,6 +51,7 @@ import org.sonar.server.project.Project; import static java.util.Optional.ofNullable; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -96,11 +97,12 @@ public class BuildComponentTreeStepTest { private DbClient dbClient = dbTester.getDbClient(); private BuildComponentTreeStep underTest = new BuildComponentTreeStep(dbClient, reportReader, treeRootHolder, analysisMetadataHolder, reportModulesPath); - @Test(expected = NullPointerException.class) + @Test public void fails_if_root_component_does_not_exist_in_reportReader() { setAnalysisMetadataHolder(); - underTest.execute(new TestComputationStepContext()); + assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext())) + .isInstanceOf(NullPointerException.class); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/ComputeQProfileMeasureStepTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/ComputeQProfileMeasureStepTest.java index 3d7cb92cd01..9ecea186d76 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/ComputeQProfileMeasureStepTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/ComputeQProfileMeasureStepTest.java @@ -25,7 +25,6 @@ import java.util.Date; import java.util.List; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.FileAttributes; @@ -74,8 +73,6 @@ public class ComputeQProfileMeasureStepTest { .build()) .build(); - @Rule - public ExpectedException thrown = ExpectedException.none(); @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule(); diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/ExtractReportStepTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/ExtractReportStepTest.java index 09ecd5d1ee8..b9168dd1066 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/ExtractReportStepTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/ExtractReportStepTest.java @@ -25,7 +25,6 @@ import java.io.InputStream; import org.apache.commons.io.FileUtils; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.impl.utils.JUnitTempFolder; import org.sonar.api.utils.MessageException; import org.sonar.api.utils.System2; @@ -40,6 +39,7 @@ import org.sonar.db.DbTester; import org.sonar.db.ce.CeTaskTypes; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class ExtractReportStepTest { @@ -51,8 +51,6 @@ public class ExtractReportStepTest { @Rule public LogTester logTester = new LogTester(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); @@ -67,10 +65,9 @@ public class ExtractReportStepTest { @Test public void fail_if_report_zip_does_not_exist() { - expectedException.expect(MessageException.class); - expectedException.expectMessage("Analysis report 1 is missing in database"); - - underTest.execute(new TestComputationStepContext()); + assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext())) + .isInstanceOf(MessageException.class) + .hasMessage("Analysis report 1 is missing in database"); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/LoadCrossProjectDuplicationsRepositoryStepTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/LoadCrossProjectDuplicationsRepositoryStepTest.java index 8ebfa9eaeb3..6363a20b3b0 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/LoadCrossProjectDuplicationsRepositoryStepTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/LoadCrossProjectDuplicationsRepositoryStepTest.java @@ -27,7 +27,6 @@ import java.util.Map; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; import org.sonar.api.utils.System2; import org.sonar.ce.task.projectanalysis.analysis.Analysis; @@ -67,8 +66,6 @@ import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT public class LoadCrossProjectDuplicationsRepositoryStepTest { - @Rule - public ExpectedException thrown = ExpectedException.none(); private static final String XOO_LANGUAGE = "xoo"; private static final int PROJECT_REF = 1; diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/LoadDuplicationsFromReportStepTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/LoadDuplicationsFromReportStepTest.java index 1dfecf7a3ae..ab263098084 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/LoadDuplicationsFromReportStepTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/LoadDuplicationsFromReportStepTest.java @@ -22,7 +22,6 @@ package org.sonar.ce.task.projectanalysis.step; import java.util.Arrays; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule; import org.sonar.ce.task.projectanalysis.analysis.Branch; import org.sonar.ce.task.projectanalysis.batch.BatchReportReaderRule; @@ -42,12 +41,12 @@ import org.sonar.db.component.BranchType; import org.sonar.scanner.protocol.output.ScannerReport; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.ce.task.projectanalysis.component.Component.Type.FILE; import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT; import static org.sonar.ce.task.projectanalysis.component.ReportComponent.builder; -import static org.sonar.test.ExceptionCauseMatcher.hasType; public class LoadDuplicationsFromReportStepTest { private static final int LINE = 2; @@ -69,8 +68,6 @@ public class LoadDuplicationsFromReportStepTest { @Rule public DuplicationRepositoryRule duplicationRepository = DuplicationRepositoryRule.create(treeRootHolder); @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Rule public AnalysisMetadataHolderRule analysisMetadataHolder = new AnalysisMetadataHolderRule(); private LoadDuplicationsFromReportStep underTest = new LoadDuplicationsFromReportStep(treeRootHolder, analysisMetadataHolder, @@ -187,10 +184,10 @@ public class LoadDuplicationsFromReportStepTest { int line = 2; reportReader.putDuplications(FILE_1_REF, createDuplication(singleLineTextRange(line), createInProjectDuplicate(666, line + 1))); - expectedException.expect(VisitException.class); - expectedException.expectCause(hasType(IllegalArgumentException.class).andMessage("Component with ref '666' can't be found")); - - underTest.execute(new TestComputationStepContext()); + assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext())) + .isInstanceOf(VisitException.class) + .hasCauseInstanceOf(IllegalArgumentException.class) + .hasRootCauseMessage("Component with ref '666' can't be found"); } @Test @@ -198,10 +195,10 @@ public class LoadDuplicationsFromReportStepTest { int line = 2; reportReader.putDuplications(FILE_1_REF, createDuplication(singleLineTextRange(line), createInProjectDuplicate(FILE_1_REF, line + 1))); - expectedException.expect(VisitException.class); - expectedException.expectCause(hasType(IllegalArgumentException.class).andMessage("file and otherFile references can not be the same")); - - underTest.execute(new TestComputationStepContext()); + assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext())) + .isInstanceOf(VisitException.class) + .hasCauseInstanceOf(IllegalArgumentException.class) + .hasRootCauseMessage("file and otherFile references can not be the same"); } private void assertDuplications(int fileRef, TextBlock original, Duplicate... duplicates) { diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/LoadMeasureComputersStepTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/LoadMeasureComputersStepTest.java index 0fca1cdd083..fff23bd142c 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/LoadMeasureComputersStepTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/LoadMeasureComputersStepTest.java @@ -24,9 +24,7 @@ import com.google.common.collect.Lists; import java.util.Collections; import java.util.List; import java.util.Set; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.ce.measure.MeasureComputer; import org.sonar.api.measures.Metric; import org.sonar.api.measures.Metrics; @@ -37,6 +35,7 @@ import org.sonar.ce.task.step.TestComputationStepContext; import static com.google.common.collect.Lists.newArrayList; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.util.Arrays.array; import static org.sonar.api.measures.CoreMetrics.CLASSES_KEY; import static org.sonar.api.measures.CoreMetrics.NCLOC_KEY; @@ -47,8 +46,6 @@ import static org.sonar.api.measures.Metric.ValueType.MILLISEC; public class LoadMeasureComputersStepTest { - @Rule - public ExpectedException thrown = ExpectedException.none(); private static final String NEW_METRIC_1 = "metric1"; private static final String NEW_METRIC_2 = "metric2"; @@ -117,32 +114,35 @@ public class LoadMeasureComputersStepTest { @Test public void fail_with_ISE_when_input_metric_is_unknown() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Metric 'unknown' cannot be used as an input metric as it's not a core metric and no plugin declare this metric"); - - MeasureComputer[] computers = new MeasureComputer[] {newMeasureComputer(array("unknown"), array(NEW_METRIC_4))}; - ComputationStep underTest = new LoadMeasureComputersStep(holder, array(new TestMetrics()), computers); - underTest.execute(new TestComputationStepContext()); + assertThatThrownBy(() -> { + MeasureComputer[] computers = new MeasureComputer[] {newMeasureComputer(array("unknown"), array(NEW_METRIC_4))}; + ComputationStep underTest = new LoadMeasureComputersStep(holder, array(new TestMetrics()), computers); + underTest.execute(new TestComputationStepContext()); + }) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Metric 'unknown' cannot be used as an input metric as it's not a core metric and no plugin declare this metric"); } @Test public void fail_with_ISE_when_output_metric_is_not_define_by_plugin() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Metric 'unknown' cannot be used as an output metric because no plugins declare this metric"); - - MeasureComputer[] computers = new MeasureComputer[] {newMeasureComputer(array(NEW_METRIC_4), array("unknown"))}; - ComputationStep underTest = new LoadMeasureComputersStep(holder, array(new TestMetrics()), computers); - underTest.execute(new TestComputationStepContext()); + assertThatThrownBy(() -> { + MeasureComputer[] computers = new MeasureComputer[] {newMeasureComputer(array(NEW_METRIC_4), array("unknown"))}; + ComputationStep underTest = new LoadMeasureComputersStep(holder, array(new TestMetrics()), computers); + underTest.execute(new TestComputationStepContext()); + }) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Metric 'unknown' cannot be used as an output metric because no plugins declare this metric"); } @Test public void fail_with_ISE_when_output_metric_is_a_core_metric() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Metric 'ncloc' cannot be used as an output metric because it's a core metric"); - - MeasureComputer[] computers = new MeasureComputer[] {newMeasureComputer(array(NEW_METRIC_4), array(NCLOC_KEY))}; - ComputationStep underTest = new LoadMeasureComputersStep(holder, array(new TestMetrics()), computers); - underTest.execute(new TestComputationStepContext()); + assertThatThrownBy(() -> { + MeasureComputer[] computers = new MeasureComputer[] {newMeasureComputer(array(NEW_METRIC_4), array(NCLOC_KEY))}; + ComputationStep underTest = new LoadMeasureComputersStep(holder, array(new TestMetrics()), computers); + underTest.execute(new TestComputationStepContext()); + }) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Metric 'ncloc' cannot be used as an output metric because it's a core metric"); } @Test @@ -172,56 +172,59 @@ public class LoadMeasureComputersStepTest { @Test public void fail_with_ISE_when_no_metrics_are_defined_by_plugin_but_measure_computer_use_a_new_metric() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Metric 'metric1' cannot be used as an output metric because no plugins declare this metric"); - - MeasureComputer[] computers = new MeasureComputer[] {newMeasureComputer(array(NCLOC_KEY), array(NEW_METRIC_1))}; - ComputationStep underTest = new LoadMeasureComputersStep(holder, computers); - underTest.execute(new TestComputationStepContext()); + assertThatThrownBy(() -> { + MeasureComputer[] computers = new MeasureComputer[] {newMeasureComputer(array(NCLOC_KEY), array(NEW_METRIC_1))}; + ComputationStep underTest = new LoadMeasureComputersStep(holder, computers); + underTest.execute(new TestComputationStepContext()); + }) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Metric 'metric1' cannot be used as an output metric because no plugins declare this metric"); } @Test public void fail_with_ISE_when_two_measure_computers_generate_the_same_output_metric() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Output metric 'metric1' is already defined by another measure computer 'TestMeasureComputer'"); - - MeasureComputer[] computers = new MeasureComputer[] {newMeasureComputer(array(NCLOC_KEY), array(NEW_METRIC_1)), newMeasureComputer(array(CLASSES_KEY), array(NEW_METRIC_1))}; - ComputationStep underTest = new LoadMeasureComputersStep(holder, array(new TestMetrics()), computers); - underTest.execute(new TestComputationStepContext()); + assertThatThrownBy(() -> { + MeasureComputer[] computers = new MeasureComputer[] {newMeasureComputer(array(NCLOC_KEY), array(NEW_METRIC_1)), newMeasureComputer(array(CLASSES_KEY), array(NEW_METRIC_1))}; + ComputationStep underTest = new LoadMeasureComputersStep(holder, array(new TestMetrics()), computers); + underTest.execute(new TestComputationStepContext()); + }) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Output metric 'metric1' is already defined by another measure computer 'TestMeasureComputer'"); } @Test public void fail_with_IAE_when_creating_measure_computer_definition_without_using_the_builder_and_with_invalid_output_metrics() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("At least one output metric must be defined"); - - MeasureComputer measureComputer = new MeasureComputer() { - @Override - public MeasureComputerDefinition define(MeasureComputerDefinitionContext defContext) { - // Create a instance of MeasureComputerDefinition without using the builder - return new MeasureComputer.MeasureComputerDefinition() { - @Override - public Set getInputMetrics() { - return ImmutableSet.of(NCLOC_KEY); - } - - @Override - public Set getOutputMetrics() { - // Empty output metric is not allowed ! - return Collections.emptySet(); - } - }; - } - - @Override - public void compute(MeasureComputerContext context) { - // Nothing needs to be done as we're only testing metada - } - }; - - MeasureComputer[] computers = new MeasureComputer[] {measureComputer}; - ComputationStep underTest = new LoadMeasureComputersStep(holder, array(new TestMetrics()), computers); - underTest.execute(new TestComputationStepContext()); + assertThatThrownBy(() -> { + MeasureComputer measureComputer = new MeasureComputer() { + @Override + public MeasureComputerDefinition define(MeasureComputerDefinitionContext defContext) { + // Create a instance of MeasureComputerDefinition without using the builder + return new MeasureComputer.MeasureComputerDefinition() { + @Override + public Set getInputMetrics() { + return ImmutableSet.of(NCLOC_KEY); + } + + @Override + public Set getOutputMetrics() { + // Empty output metric is not allowed ! + return Collections.emptySet(); + } + }; + } + + @Override + public void compute(MeasureComputerContext context) { + // Nothing needs to be done as we're only testing metada + } + }; + + MeasureComputer[] computers = new MeasureComputer[] {measureComputer}; + ComputationStep underTest = new LoadMeasureComputersStep(holder, array(new TestMetrics()), computers); + underTest.execute(new TestComputationStepContext()); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("At least one output metric must be defined"); } private static MeasureComputer newMeasureComputer(final String[] inputMetrics, final String[] outputMetrics) { diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/LoadPeriodsStepTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/LoadPeriodsStepTest.java index 54ac010f729..21b35f7ea81 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/LoadPeriodsStepTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/LoadPeriodsStepTest.java @@ -33,7 +33,6 @@ import javax.annotation.Nullable; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.api.utils.MessageException; import org.sonar.api.utils.System2; @@ -61,6 +60,7 @@ import org.sonar.server.project.Project; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -79,8 +79,6 @@ public class LoadPeriodsStepTest extends BaseStepTest { public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule(); @Rule public LogTester logTester = new LogTester(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private AnalysisMetadataHolder analysisMetadataHolder = mock(AnalysisMetadataHolder.class); private PeriodHolderImpl periodsHolder = new PeriodHolderImpl(); @@ -229,20 +227,18 @@ public class LoadPeriodsStepTest extends BaseStepTest { setupRoot(project); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Attempting to resolve period while no analysis exist"); - - underTest.execute(new TestComputationStepContext()); + assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Attempting to resolve period while no analysis exist"); } @Test public void throw_ISE_if_no_analysis_found_with_default() { setupRoot(project); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Attempting to resolve period while no analysis exist"); - - underTest.execute(new TestComputationStepContext()); + assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Attempting to resolve period while no analysis exist"); } @Test @@ -268,10 +264,9 @@ public class LoadPeriodsStepTest extends BaseStepTest { setProjectPeriod(project.uuid(), NewCodePeriodType.SPECIFIC_ANALYSIS, "nonexistent"); setupRoot(project); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Analysis 'nonexistent' of project '" + project.uuid() + "' defined as the baseline does not exist"); - - underTest.execute(new TestComputationStepContext()); + assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Analysis 'nonexistent' of project '" + project.uuid() + "' defined as the baseline does not exist"); } @Test @@ -281,11 +276,9 @@ public class LoadPeriodsStepTest extends BaseStepTest { setBranchPeriod(project.uuid(), project.uuid(), NewCodePeriodType.SPECIFIC_ANALYSIS, otherProjectAnalysis.getUuid()); setupRoot(project); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Analysis '" + otherProjectAnalysis.getUuid() + "' of project '" + project.uuid() - + "' defined as the baseline does not exist"); - - underTest.execute(new TestComputationStepContext()); + assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Analysis '" + otherProjectAnalysis.getUuid() + "' of project '" + project.uuid() + "' defined as the baseline does not exist"); } @Test @@ -295,11 +288,9 @@ public class LoadPeriodsStepTest extends BaseStepTest { setBranchPeriod(project.uuid(), project.uuid(), NewCodePeriodType.SPECIFIC_ANALYSIS, otherBranchAnalysis.getUuid()); setupRoot(project); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Analysis '" + otherBranchAnalysis.getUuid() + "' of project '" + project.uuid() - + "' defined as the baseline does not exist"); - - underTest.execute(new TestComputationStepContext()); + assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Analysis '" + otherBranchAnalysis.getUuid() + "' of project '" + project.uuid() + "' defined as the baseline does not exist"); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/LoadQualityGateStepTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/LoadQualityGateStepTest.java index c9d48c3821f..9a834ca8151 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/LoadQualityGateStepTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/LoadQualityGateStepTest.java @@ -24,7 +24,6 @@ import java.util.Optional; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder; import org.sonar.ce.task.projectanalysis.metric.Metric; import org.sonar.ce.task.projectanalysis.metric.MetricImpl; @@ -43,8 +42,6 @@ import static org.mockito.Mockito.when; public class LoadQualityGateStepTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public MutableQualityGateHolderRule mutableQualityGateHolder = new MutableQualityGateHolderRule(); diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/LoadReportAnalysisMetadataHolderStepTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/LoadReportAnalysisMetadataHolderStepTest.java index da12b6a8941..816b8d9da9e 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/LoadReportAnalysisMetadataHolderStepTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/LoadReportAnalysisMetadataHolderStepTest.java @@ -28,7 +28,6 @@ import org.assertj.core.api.Assertions; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.api.Plugin; import org.sonar.api.utils.MessageException; @@ -50,6 +49,7 @@ import org.sonar.server.project.Project; import static java.util.Arrays.stream; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -66,8 +66,6 @@ public class LoadReportAnalysisMetadataHolderStepTest { public BatchReportReaderRule reportReader = new BatchReportReaderRule(); @Rule public MutableAnalysisMetadataHolderRule analysisMetadataHolder = new MutableAnalysisMetadataHolderRule(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private final DbClient dbClient = db.getDbClient(); private final TestPluginRepository pluginRepository = new TestPluginRepository(); @@ -176,10 +174,9 @@ public class LoadReportAnalysisMetadataHolderStepTest { ComputationStep underTest = createStep(res); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("component missing on ce task"); - - underTest.execute(new TestComputationStepContext()); + assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("component missing on ce task"); } @Test @@ -192,11 +189,9 @@ public class LoadReportAnalysisMetadataHolderStepTest { ComputationStep underTest = createStep(res); - expectedException.expect(MessageException.class); - expectedException - .expectMessage("Compute Engine task main component key is null. Project with UUID main_prj_uuid must have been deleted since report was uploaded. Can not proceed."); - - underTest.execute(new TestComputationStepContext()); + assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext())) + .isInstanceOf(MessageException.class) + .hasMessage("Compute Engine task main component key is null. Project with UUID main_prj_uuid must have been deleted since report was uploaded. Can not proceed."); } @Test @@ -209,10 +204,9 @@ public class LoadReportAnalysisMetadataHolderStepTest { ComputationStep underTest = createStep(res); - expectedException.expect(MessageException.class); - expectedException.expectMessage("Compute Engine task component key is null. Project with UUID prj_uuid must have been deleted since report was uploaded. Can not proceed."); - - underTest.execute(new TestComputationStepContext()); + assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext())) + .isInstanceOf(MessageException.class) + .hasMessage("Compute Engine task component key is null. Project with UUID prj_uuid must have been deleted since report was uploaded. Can not proceed."); } @Test @@ -223,11 +217,10 @@ public class LoadReportAnalysisMetadataHolderStepTest { .setProjectKey(otherProject.getDbKey()) .build()); - expectedException.expect(MessageException.class); - expectedException - .expectMessage("ProjectKey in report (" + otherProject.getDbKey() + ") is not consistent with projectKey under which the report has been submitted (" + PROJECT_KEY + ")"); + assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext())) + .isInstanceOf(MessageException.class) + .hasMessage("ProjectKey in report (" + otherProject.getDbKey() + ") is not consistent with projectKey under which the report has been submitted (" + PROJECT_KEY + ")"); - underTest.execute(new TestComputationStepContext()); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/PersistAdHocRulesStepTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/PersistAdHocRulesStepTest.java index 1ae5ce74a24..d0e1c0f8e72 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/PersistAdHocRulesStepTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/PersistAdHocRulesStepTest.java @@ -25,7 +25,6 @@ import org.junit.Rule; import org.junit.Test; import org.sonar.api.rule.RuleKey; import org.sonar.api.utils.System2; -import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule; import org.sonar.ce.task.projectanalysis.issue.AdHocRuleCreator; import org.sonar.ce.task.projectanalysis.issue.NewAdHocRule; import org.sonar.ce.task.projectanalysis.issue.RuleRepositoryImpl; diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/PersistComponentsStepTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/PersistComponentsStepTest.java index 3a7ab70f7f8..ef38e48c3a1 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/PersistComponentsStepTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/PersistComponentsStepTest.java @@ -19,9 +19,7 @@ */ package org.sonar.ce.task.projectanalysis.step; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.utils.System2; import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder; import org.sonar.ce.task.projectanalysis.component.BranchPersister; @@ -36,6 +34,7 @@ import org.sonar.db.component.ComponentDao; import static java.util.Collections.emptyList; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doReturn; @@ -43,9 +42,6 @@ import static org.mockito.Mockito.mock; public class PersistComponentsStepTest { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void should_fail_if_project_is_not_stored_in_database_yet() { TreeRootHolder treeRootHolder = mock(TreeRootHolder.class); @@ -59,16 +55,17 @@ public class PersistComponentsStepTest { doReturn(componentDao).when(dbClient).componentDao(); doReturn(emptyList()).when(componentDao).selectAllComponentsFromProjectKey(any(DbSession.class), eq(projectKey)); - thrown.expect(IllegalStateException.class); - thrown.expectMessage("The project '" + projectKey + "' is not stored in the database, during a project analysis"); - - new PersistComponentsStep( - dbClient, - treeRootHolder, - System2.INSTANCE, - mock(MutableDisabledComponentsHolder.class), - mock(AnalysisMetadataHolder.class), - mock(BranchPersister.class), - mock(ProjectPersister.class)).execute(new TestComputationStepContext()); + assertThatThrownBy(() -> { + new PersistComponentsStep( + dbClient, + treeRootHolder, + System2.INSTANCE, + mock(MutableDisabledComponentsHolder.class), + mock(AnalysisMetadataHolder.class), + mock(BranchPersister.class), + mock(ProjectPersister.class)).execute(new TestComputationStepContext()); + }) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("The project '" + projectKey + "' is not stored in the database, during a project analysis"); } } diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/PersistIssuesStepTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/PersistIssuesStepTest.java index 7f3e8fb6722..aeb1761c241 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/PersistIssuesStepTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/PersistIssuesStepTest.java @@ -31,7 +31,6 @@ import org.mockito.ArgumentCaptor; import org.sonar.api.rule.RuleKey; import org.sonar.api.rules.RuleType; import org.sonar.api.utils.System2; -import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule; import org.sonar.ce.task.projectanalysis.batch.BatchReportReaderRule; import org.sonar.ce.task.projectanalysis.issue.AdHocRuleCreator; import org.sonar.ce.task.projectanalysis.issue.ProtoIssueCache; diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/PersistProjectLinksStepTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/PersistProjectLinksStepTest.java index 2b9e20e80e5..70ed0e7fa23 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/PersistProjectLinksStepTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/PersistProjectLinksStepTest.java @@ -21,7 +21,6 @@ package org.sonar.ce.task.projectanalysis.step; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.Mockito; import org.sonar.api.utils.System2; import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule; @@ -44,6 +43,7 @@ import org.sonar.scanner.protocol.output.ScannerReport; import org.sonar.scanner.protocol.output.ScannerReport.Component.ComponentType; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyZeroInteractions; @@ -55,8 +55,6 @@ import static org.sonar.scanner.protocol.output.ScannerReport.ComponentLink.Comp public class PersistProjectLinksStepTest extends BaseStepTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public AnalysisMetadataHolderRule analysisMetadataHolder = new AnalysisMetadataHolderRule(); @Rule @@ -247,10 +245,9 @@ public class PersistProjectLinksStepTest extends BaseStepTest { .addLink(ScannerReport.ComponentLink.newBuilder().setType(HOME).setHref("http://www.sonarqube.org").build()) .build()); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Link of type 'homepage' has already been declared on component 'ABCD'"); - - underTest.execute(new TestComputationStepContext()); + assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Link of type 'homepage' has already been declared on component 'ABCD'"); } private void mockBranch(boolean isMain) { diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/QualityGateMeasuresStepTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/QualityGateMeasuresStepTest.java index db369844633..9953cf98088 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/QualityGateMeasuresStepTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/QualityGateMeasuresStepTest.java @@ -28,7 +28,6 @@ import org.assertj.core.api.AbstractAssert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.sonar.api.config.internal.ConfigurationBridge; @@ -57,13 +56,14 @@ import org.sonar.ce.task.projectanalysis.qualitygate.QualityGateStatusHolder; import org.sonar.ce.task.step.TestComputationStepContext; import static com.google.common.collect.ImmutableList.of; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.api.measures.CoreMetrics.ALERT_STATUS_KEY; +import static org.sonar.ce.task.projectanalysis.measure.Measure.newMeasureBuilder; import static org.sonar.ce.task.projectanalysis.measure.Measure.Level.ERROR; import static org.sonar.ce.task.projectanalysis.measure.Measure.Level.OK; -import static org.sonar.ce.task.projectanalysis.measure.Measure.newMeasureBuilder; import static org.sonar.ce.task.projectanalysis.measure.MeasureAssert.assertThat; public class QualityGateMeasuresStepTest { @@ -77,8 +77,6 @@ public class QualityGateMeasuresStepTest { private static final String SOME_QG_UUID = "7521551"; private static final String SOME_QG_NAME = "name"; - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule(); @Rule @@ -145,10 +143,9 @@ public class QualityGateMeasuresStepTest { underTest.execute(new TestComputationStepContext()); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Quality gate status has not been set yet"); - - qualityGateStatusHolder.getStatus(); + assertThatThrownBy(() -> qualityGateStatusHolder.getStatus()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Quality gate status has not been set yet"); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/RegisterQualityProfileStatusStepTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/RegisterQualityProfileStatusStepTest.java index d43e8caacca..e222024ffda 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/RegisterQualityProfileStatusStepTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/RegisterQualityProfileStatusStepTest.java @@ -46,7 +46,6 @@ import org.sonar.ce.task.step.TestComputationStepContext; import org.sonar.server.qualityprofile.QPMeasureData; import org.sonar.server.qualityprofile.QualityProfile; -import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/ReportComputationStepsTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/ReportComputationStepsTest.java index 8cb72a7b066..c7c2d83b765 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/ReportComputationStepsTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/ReportComputationStepsTest.java @@ -20,45 +20,44 @@ package org.sonar.ce.task.projectanalysis.step; import com.google.common.collect.Lists; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.ce.task.container.TaskContainerImpl; import org.sonar.core.platform.ComponentContainer; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; public class ReportComputationStepsTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void instances_throws_ISE_if_container_does_not_have_any_step() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Component not found: " + ExtractReportStep.class); - - TaskContainerImpl computeEngineContainer = new TaskContainerImpl(new ComponentContainer(), container -> { - // do nothing - }); - - Lists.newArrayList(new ReportComputationSteps(computeEngineContainer).instances()); + assertThatThrownBy(() -> { + TaskContainerImpl computeEngineContainer = new TaskContainerImpl(new ComponentContainer(), container -> { + // do nothing + }); + + Lists.newArrayList(new ReportComputationSteps(computeEngineContainer).instances()); + }) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Component not found: " + ExtractReportStep.class); } @Test public void instances_throws_ISE_if_container_does_not_have_second_step() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Component not found: class org.sonar.ce.task.projectanalysis.step.PersistScannerContextStep"); - - final ExtractReportStep reportExtractionStep = mock(ExtractReportStep.class); - ComponentContainer componentContainer = new ComponentContainer() { - { - addSingleton(reportExtractionStep); - } - }; - TaskContainerImpl computeEngineContainer = new TaskContainerImpl(componentContainer, container -> { - // do nothing - }); - - Lists.newArrayList(new ReportComputationSteps(computeEngineContainer).instances()); + assertThatThrownBy(() -> { + final ExtractReportStep reportExtractionStep = mock(ExtractReportStep.class); + ComponentContainer componentContainer = new ComponentContainer() { + { + addSingleton(reportExtractionStep); + } + }; + TaskContainerImpl computeEngineContainer = new TaskContainerImpl(componentContainer, container -> { + // do nothing + }); + + Lists.newArrayList(new ReportComputationSteps(computeEngineContainer).instances()); + }) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Component not found: class org.sonar.ce.task.projectanalysis.step.PersistScannerContextStep"); } } diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/SendIssueNotificationsStepTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/SendIssueNotificationsStepTest.java index 3a3f391e7fb..27916eb284e 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/SendIssueNotificationsStepTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/SendIssueNotificationsStepTest.java @@ -100,10 +100,10 @@ import static org.sonar.ce.task.projectanalysis.component.ReportComponent.builde import static org.sonar.ce.task.projectanalysis.step.SendIssueNotificationsStep.NOTIF_TYPES; import static org.sonar.db.component.BranchType.BRANCH; import static org.sonar.db.component.BranchType.PULL_REQUEST; +import static org.sonar.db.component.ComponentTesting.newBranchComponent; import static org.sonar.db.component.ComponentTesting.newBranchDto; import static org.sonar.db.component.ComponentTesting.newFileDto; import static org.sonar.db.component.ComponentTesting.newPrivateProjectDto; -import static org.sonar.db.component.ComponentTesting.newBranchComponent; import static org.sonar.db.issue.IssueTesting.newIssue; import static org.sonar.db.rule.RuleTesting.newRule; diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/UpdateQualityProfilesLastUsedDateStepTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/UpdateQualityProfilesLastUsedDateStepTest.java index e9ab08da8f6..5858b36b23d 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/UpdateQualityProfilesLastUsedDateStepTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/UpdateQualityProfilesLastUsedDateStepTest.java @@ -25,7 +25,6 @@ import java.util.stream.Collectors; import javax.annotation.CheckForNull; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.utils.System2; import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule; import org.sonar.ce.task.projectanalysis.component.Component; @@ -45,6 +44,7 @@ import org.sonar.server.qualityprofile.QPMeasureData; import org.sonar.server.qualityprofile.QualityProfile; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.measures.CoreMetrics.QUALITY_PROFILES; import static org.sonar.api.measures.CoreMetrics.QUALITY_PROFILES_KEY; import static org.sonar.db.qualityprofile.QualityProfileTesting.newQualityProfileDto; @@ -56,8 +56,6 @@ public class UpdateQualityProfilesLastUsedDateStepTest { private QProfileDto sonarWayPhp = newProfile("sonar-way-php"); private QProfileDto myQualityProfile = newProfile("my-qp"); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester db = DbTester.create(System2.INSTANCE); @@ -134,8 +132,8 @@ public class UpdateQualityProfilesLastUsedDateStepTest { measureRepository.addRawMeasure(1, QUALITY_PROFILES_KEY, Measure.newMeasureBuilder().create(toJson(currentProfile.getKee()))); - expectedException.expect(RowNotFoundException.class); - underTest.execute(new TestComputationStepContext()); + assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext())) + .isInstanceOf(RowNotFoundException.class); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/ViewsPersistAnalysisStepTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/ViewsPersistAnalysisStepTest.java index b27b7d851f6..ec84841e0ec 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/ViewsPersistAnalysisStepTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/ViewsPersistAnalysisStepTest.java @@ -47,8 +47,6 @@ import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT import static org.sonar.ce.task.projectanalysis.component.Component.Type.SUBVIEW; import static org.sonar.ce.task.projectanalysis.component.Component.Type.VIEW; import static org.sonar.db.component.ComponentTesting.newPrivateProjectDto; -import static org.sonar.db.component.ComponentTesting.newSubPortfolio; -import static org.sonar.db.component.ComponentTesting.newPortfolio; public class ViewsPersistAnalysisStepTest extends BaseStepTest { diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/taskprocessor/AuditPurgeTaskProcessorTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/taskprocessor/AuditPurgeTaskProcessorTest.java index 9e68167b02b..d803353693c 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/taskprocessor/AuditPurgeTaskProcessorTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/taskprocessor/AuditPurgeTaskProcessorTest.java @@ -31,7 +31,7 @@ import org.sonar.core.platform.ComponentContainer; import static org.mockito.ArgumentMatchers.any; import static org.sonar.ce.task.projectanalysis.taskprocessor.AuditPurgeTaskProcessor.AuditPurgeComputationSteps; import static org.sonar.db.ce.CeTaskTypes.AUDIT_PURGE; - +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class AuditPurgeTaskProcessorTest { private ComponentContainer ceEngineContainer = Mockito.mock(ComponentContainer.class); @@ -44,9 +44,10 @@ public class AuditPurgeTaskProcessorTest { Assertions.assertThat(underTest.getHandledCeTaskTypes()).containsExactly(AUDIT_PURGE); } - @Test(expected = NullPointerException.class) + @Test public void processThrowsNPEIfCeTaskIsNull() { - underTest.process(null); + assertThatThrownBy(() -> underTest.process(null)) + .isInstanceOf(NullPointerException.class); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/taskprocessor/IndexIssuesStepTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/taskprocessor/IndexIssuesStepTest.java index 00efde25fb5..b9dd3e65cb8 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/taskprocessor/IndexIssuesStepTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/taskprocessor/IndexIssuesStepTest.java @@ -22,7 +22,6 @@ package org.sonar.ce.task.projectanalysis.taskprocessor; import java.util.Optional; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.utils.System2; import org.sonar.ce.task.CeTask; import org.sonar.db.DbClient; @@ -32,6 +31,7 @@ import org.sonar.server.es.EsTester; import org.sonar.server.issue.index.IssueIndexer; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -41,8 +41,6 @@ public class IndexIssuesStepTest { private String BRANCH_UUID = "branch_uuid"; - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); @@ -111,10 +109,9 @@ public class IndexIssuesStepTest { .build(); IndexIssuesStep underTest = new IndexIssuesStep(ceTask, dbClient, issueIndexer); - expectedException.expect(UnsupportedOperationException.class); - expectedException.expectMessage("component not found in task"); - - underTest.execute(() -> null); + assertThatThrownBy(() -> underTest.execute(() -> null)) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessage("component not found in task"); } } diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/taskprocessor/IssueSyncTaskProcessorTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/taskprocessor/IssueSyncTaskProcessorTest.java index 2b92093116a..91f5c593ad5 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/taskprocessor/IssueSyncTaskProcessorTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/taskprocessor/IssueSyncTaskProcessorTest.java @@ -29,7 +29,7 @@ import org.sonar.ce.task.step.ComputationStep; import org.sonar.core.platform.ComponentContainer; import static org.mockito.ArgumentMatchers.any; -import static org.sonar.ce.task.projectanalysis.taskprocessor.IssueSyncTaskProcessor.*; +import static org.sonar.ce.task.projectanalysis.taskprocessor.IssueSyncTaskProcessor.SyncComputationSteps; import static org.sonar.db.ce.CeTaskTypes.BRANCH_ISSUE_SYNC; public class IssueSyncTaskProcessorTest { diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/util/cache/MemoryCacheTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/util/cache/MemoryCacheTest.java index a3e0051246d..95a224b90c6 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/util/cache/MemoryCacheTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/util/cache/MemoryCacheTest.java @@ -24,11 +24,10 @@ import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.anyCollection; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -36,8 +35,6 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class MemoryCacheTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private CacheLoader loader = mock(CacheLoader.class); private MemoryCache cache = new MemoryCache<>(loader); @@ -65,10 +62,9 @@ public class MemoryCacheTest { assertThat(cache.get("foo")).isEqualTo("bar"); verify(loader, times(1)).load("foo"); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("No cache entry found for key: not_exists"); - - cache.get("not_exists"); + assertThatThrownBy(() -> cache.get("not_exists")) + .isInstanceOf(IllegalStateException.class) + .hasMessage("No cache entry found for key: not_exists"); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/ProjectExportComputationStepsTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/ProjectExportComputationStepsTest.java index 94377d5169e..06c7fb916a7 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/ProjectExportComputationStepsTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/ProjectExportComputationStepsTest.java @@ -20,9 +20,7 @@ package org.sonar.ce.task.projectexport; import com.google.common.collect.Lists; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.ce.task.container.TaskContainer; import org.sonar.ce.task.container.TaskContainerImpl; import org.sonar.ce.task.projectanalysis.step.ComplexityMeasuresStep; @@ -31,11 +29,10 @@ import org.sonar.core.platform.ComponentContainer; import static com.google.common.collect.ImmutableList.copyOf; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; public class ProjectExportComputationStepsTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private TaskContainer container = mock(TaskContainer.class); private ProjectExportComputationSteps underTest = new ProjectExportComputationSteps(container); @@ -47,27 +44,29 @@ public class ProjectExportComputationStepsTest { @Test public void instances_throws_ISE_if_steps_do_not_exist_in_container() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Component not found: " + LoadProjectStep.class); - - copyOf(underTest.instances()); + assertThatThrownBy(() -> copyOf(underTest.instances())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Component not found: " + LoadProjectStep.class); } @Test public void instances_throws_ISE_if_container_does_not_have_second_step() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Component not found: class org.sonar.ce.task.projectexport.steps.LoadProjectStep"); + assertThatThrownBy(() -> { + final ComplexityMeasuresStep reportExtractionStep = mock(ComplexityMeasuresStep.class); + + ComponentContainer componentContainer = new ComponentContainer() { + { + addSingleton(reportExtractionStep); + } + }; + TaskContainerImpl computeEngineContainer = new TaskContainerImpl(componentContainer, container -> { + // do nothing + }); - final ComplexityMeasuresStep reportExtractionStep = mock(ComplexityMeasuresStep.class); - ComponentContainer componentContainer = new ComponentContainer() { - { - addSingleton(reportExtractionStep); - } - }; - TaskContainerImpl computeEngineContainer = new TaskContainerImpl(componentContainer, container -> { - // do nothing - }); + Lists.newArrayList(new ProjectExportComputationSteps(computeEngineContainer).instances()); + }) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Component not found: class org.sonar.ce.task.projectexport.steps.LoadProjectStep"); - Lists.newArrayList(new ProjectExportComputationSteps(computeEngineContainer).instances()); } } diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/analysis/ExportAnalysesStepTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/analysis/ExportAnalysesStepTest.java index 34d6fbf1fac..3325590918a 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/analysis/ExportAnalysesStepTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/analysis/ExportAnalysesStepTest.java @@ -28,7 +28,6 @@ import javax.annotation.Nullable; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.api.resources.Qualifiers; import org.sonar.api.resources.Scopes; @@ -47,6 +46,7 @@ import org.sonar.db.component.SnapshotDto; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.apache.commons.lang.StringUtils.defaultString; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.db.component.ComponentDto.UUID_PATH_OF_ROOT; @@ -103,8 +103,6 @@ public class ExportAnalysesStepTest { .setModuleUuidPath("." + PROJECT_UUID + ".MODULE_UUID.") .setProjectUuid(PROJECT_UUID); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); @Rule @@ -196,9 +194,9 @@ public class ExportAnalysesStepTest { dbTester.commit(); dumpWriter.failIfMoreThan(1, DumpElement.ANALYSES); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Analysis Export failed after processing 1 analyses successfully"); - underTest.execute(new TestComputationStepContext()); + assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Analysis Export failed after processing 1 analyses successfully"); } private static SnapshotDto newAnalysis(String uuid, long date, String componentUuid, @Nullable String version, boolean isLast, @Nullable String buildString, long buildDate) { diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/branches/ExportBranchesStepTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/branches/ExportBranchesStepTest.java index d31477b1754..ec6b964936a 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/branches/ExportBranchesStepTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/branches/ExportBranchesStepTest.java @@ -29,7 +29,6 @@ import org.apache.commons.lang.time.DateUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.resources.Qualifiers; import org.sonar.api.resources.Scopes; import org.sonar.api.utils.System2; @@ -47,6 +46,7 @@ import org.sonar.db.project.ProjectExportMapper; import static java.util.stream.Collectors.toMap; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.db.component.ComponentDto.UUID_PATH_OF_ROOT; @@ -68,8 +68,6 @@ public class ExportBranchesStepTest { .setModuleUuidPath("." + PROJECT_UUID + ".") .setProjectUuid(PROJECT_UUID); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester dbTester = DbTester.createWithExtensionMappers(System2.INSTANCE, ProjectExportMapper.class); @Rule @@ -149,9 +147,9 @@ public class ExportBranchesStepTest { public void throws_ISE_if_error() { dumpWriter.failIfMoreThan(1, DumpElement.BRANCHES); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Branch export failed after processing 1 branch(es) successfully"); - underTest.execute(new TestComputationStepContext()); + assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Branch export failed after processing 1 branch(es) successfully"); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/component/ComponentRepositoryImplTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/component/ComponentRepositoryImplTest.java index 317d0faf90b..57ab6bd54e6 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/component/ComponentRepositoryImplTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/component/ComponentRepositoryImplTest.java @@ -19,73 +19,64 @@ */ package org.sonar.ce.task.projectexport.component; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class ComponentRepositoryImplTest { private static final int SOME_REF = 121; private static final String SOME_UUID = "uuid"; - @Rule - public ExpectedException expectedException = ExpectedException.none(); private ComponentRepositoryImpl underTest = new ComponentRepositoryImpl(); @Test public void register_throws_NPE_if_uuid_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("uuid can not be null"); - - underTest.register(SOME_REF, null, true); + assertThatThrownBy(() -> underTest.register(SOME_REF, null, true)) + .isInstanceOf(NullPointerException.class) + .hasMessage("uuid can not be null"); } @Test public void register_throws_IAE_same_uuid_added_with_different_refs() { underTest.register(SOME_REF, SOME_UUID, true); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Uuid '" + SOME_UUID + "' already registered under ref '" + SOME_REF + "' in repository"); - - underTest.register(946512, SOME_UUID, true); + assertThatThrownBy(() -> underTest.register(946512, SOME_UUID, true)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Uuid '" + SOME_UUID + "' already registered under ref '" + SOME_REF + "' in repository"); } @Test public void register_throws_IAE_same_uuid_added_with_as_file() { underTest.register(SOME_REF, SOME_UUID, true); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Uuid '" + SOME_UUID + "' already registered but as a File"); - - underTest.register(SOME_REF, SOME_UUID, false); + assertThatThrownBy(() -> underTest.register(SOME_REF, SOME_UUID, false)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Uuid '" + SOME_UUID + "' already registered but as a File"); } @Test public void register_throws_IAE_same_uuid_added_with_as_not_file() { underTest.register(SOME_REF, SOME_UUID, false); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Uuid '" + SOME_UUID + "' already registered but not as a File"); - - underTest.register(SOME_REF, SOME_UUID, true); + assertThatThrownBy(() -> underTest.register(SOME_REF, SOME_UUID, true)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Uuid '" + SOME_UUID + "' already registered but not as a File"); } @Test public void getRef_throws_NPE_if_uuid_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("uuid can not be null"); - - underTest.getRef(null); + assertThatThrownBy(() -> underTest.getRef(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("uuid can not be null"); } @Test public void getRef_throws_ISE_if_uuid_not_in_repository() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("No reference registered in the repository for uuid '" + SOME_UUID + "'"); - - underTest.getRef(SOME_UUID); + assertThatThrownBy(() -> underTest.getRef(SOME_UUID)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("No reference registered in the repository for uuid '" + SOME_UUID + "'"); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/component/ExportComponentsStepTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/component/ExportComponentsStepTest.java index c24cd2c7a10..04a31bf19da 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/component/ExportComponentsStepTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/component/ExportComponentsStepTest.java @@ -26,7 +26,6 @@ import java.util.List; import org.junit.After; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.resources.Qualifiers; import org.sonar.api.resources.Scopes; import org.sonar.api.utils.System2; @@ -40,6 +39,7 @@ import org.sonar.db.DbTester; import org.sonar.db.component.ComponentDto; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -103,8 +103,6 @@ public class ExportComponentsStepTest { @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Rule public LogTester logTester = new LogTester(); private final FakeDumpWriter dumpWriter = new FakeDumpWriter(); @@ -158,9 +156,9 @@ public class ExportComponentsStepTest { when(projectHolder.projectDto()).thenReturn(dbTester.components().getProjectDto(PROJECT)); dumpWriter.failIfMoreThan(1, DumpElement.COMPONENTS); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Component Export failed after processing 1 components successfully"); - underTest.execute(new TestComputationStepContext()); + assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Component Export failed after processing 1 components successfully"); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/file/ExportLineHashesStepTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/file/ExportLineHashesStepTest.java index 9914c2edaf6..c54e5203628 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/file/ExportLineHashesStepTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/file/ExportLineHashesStepTest.java @@ -24,7 +24,6 @@ import java.util.List; import org.junit.After; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; import org.sonar.api.utils.System2; import org.sonar.api.utils.log.LogTester; @@ -54,8 +53,6 @@ public class ExportLineHashesStepTest { private static final String FILE_UUID = "file uuid"; private static final String FILE_UUID_2 = "file-2-uuid"; - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); @Rule diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/issue/ExportIssuesStepTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/issue/ExportIssuesStepTest.java index 0792c73f139..142823f70ba 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/issue/ExportIssuesStepTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/issue/ExportIssuesStepTest.java @@ -32,7 +32,6 @@ import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.api.issue.Issue; import org.sonar.api.rule.RuleKey; @@ -64,13 +63,13 @@ import org.sonar.db.rule.RuleDto.Scope; import static com.google.common.collect.Lists.newArrayList; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.api.issue.Issue.STATUS_CONFIRMED; import static org.sonar.api.issue.Issue.STATUS_OPEN; import static org.sonar.api.issue.Issue.STATUS_REOPENED; import static org.sonar.api.issue.Issue.STATUS_RESOLVED; -import static org.sonar.test.ExceptionCauseMatcher.hasType; @RunWith(DataProviderRunner.class) public class ExportIssuesStepTest { @@ -82,8 +81,6 @@ public class ExportIssuesStepTest { @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Rule public LogTester logTester = new LogTester(); private final DbClient dbClient = dbTester.getDbClient(); @@ -144,10 +141,11 @@ public class ExportIssuesStepTest { public void execute_fails_with_ISE_if_componentUuid_is_not_set() { insertIssue(createBaseIssueDto(readyRuleDto, SOME_PROJECT_UUID).setComponentUuid(null)); - expectExportFailure(); - expectedException.expectCause(hasType(NullPointerException.class).andMessage("uuid can not be null")); - - underTest.execute(new TestComputationStepContext()); + assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Issue export failed after processing 0 issues successfully") + .hasRootCauseInstanceOf(NullPointerException.class) + .hasRootCauseMessage("uuid can not be null"); } @DataProvider @@ -303,11 +301,9 @@ public class ExportIssuesStepTest { byte[] rubbishBytes = getRubbishBytes(); String uuid = insertIssue(createBaseIssueDto(readyRuleDto, SOME_PROJECT_UUID).setLocations(rubbishBytes)).getKey(); - expectExportFailure(); - expectedException.expectCause( - hasType(IllegalStateException.class).andMessage("Fail to read locations from DB for issue " + uuid)); - - underTest.execute(new TestComputationStepContext()); + assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Issue export failed after processing 0 issues successfully"); } @Test @@ -327,9 +323,9 @@ public class ExportIssuesStepTest { insertIssue(createBaseIssueDto(readyRuleDto, SOME_PROJECT_UUID)); insertIssue(createBaseIssueDto(readyRuleDto, SOME_PROJECT_UUID).setLocations(getRubbishBytes())).getKey(); - expectExportFailure(2); - - underTest.execute(new TestComputationStepContext()); + assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Issue export failed after processing 2 issues successfully"); } private byte[] getRubbishBytes() throws IOException, URISyntaxException { @@ -340,14 +336,14 @@ public class ExportIssuesStepTest { return dumpWriter.getWrittenMessagesOf(DumpElement.ISSUES).get(0); } - private void expectExportFailure() { - expectExportFailure(0); - } +// private void expectExportFailure() { +// expectExportFailure(0); +// } - private void expectExportFailure(int i) { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Issue export failed after processing " + i + " issues successfully"); - } +// private void expectExportFailure(int i) { +// expectedException.expect(IllegalStateException.class); +// expectedException.expectMessage("Issue export failed after processing " + i + " issues successfully"); +// } private int issueUuidGenerator = 1; diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/rule/ExportAdHocRulesStepTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/rule/ExportAdHocRulesStepTest.java index 06ecfd7d1dc..b8806ba6c39 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/rule/ExportAdHocRulesStepTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/rule/ExportAdHocRulesStepTest.java @@ -26,7 +26,6 @@ import java.util.List; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.resources.Qualifiers; import org.sonar.api.resources.Scopes; import org.sonar.api.rule.RuleKey; @@ -49,6 +48,7 @@ import org.sonar.db.rule.RuleDto; import org.sonar.db.rule.RuleMetadataDto; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -79,8 +79,6 @@ public class ExportAdHocRulesStepTest { new BranchDto().setBranchType(BranchType.BRANCH).setProjectUuid(PROJECT_UUID).setKey("branch-3").setUuid("branch-3-uuid").setMergeBranchUuid("master") .setExcludeFromPurge(false)); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public LogTester logTester = new LogTester(); @@ -172,10 +170,10 @@ public class ExportAdHocRulesStepTest { insertIssue(rule2, PROJECT_UUID, PROJECT_UUID); insertIssue(rule3, PROJECT_UUID, PROJECT_UUID); dumpWriter.failIfMoreThan(2, DumpElement.AD_HOC_RULES); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Ad-hoc rules export failed after processing 2 rules successfully"); - underTest.execute(new TestComputationStepContext()); + assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Ad-hoc rules export failed after processing 2 rules successfully"); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/rule/ExportRuleStepTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/rule/ExportRuleStepTest.java index d2983b7e765..bbd3628f018 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/rule/ExportRuleStepTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/rule/ExportRuleStepTest.java @@ -24,7 +24,6 @@ import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.rule.RuleKey; import org.sonar.api.utils.log.LogTester; import org.sonar.api.utils.log.LoggerLevel; @@ -34,14 +33,13 @@ import org.sonar.ce.task.step.TestComputationStepContext; import org.sonar.core.util.Uuids; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class ExportRuleStepTest { private static final String REPOSITORY = "repository"; @org.junit.Rule public LogTester logTester = new LogTester(); - @org.junit.Rule - public ExpectedException expectedException = ExpectedException.none(); private FakeDumpWriter dumpWriter = new FakeDumpWriter(); private SimpleRuleRepository ruleRepository = new SimpleRuleRepository(); @@ -90,10 +88,9 @@ public class ExportRuleStepTest { // will cause NPE .addNull(); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Rule Export failed after processing 3 rules successfully"); - - underTest.execute(new TestComputationStepContext()); + assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Rule Export failed after processing 3 rules successfully"); } private static class SimpleRuleRepository implements RuleRepository { diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/rule/RuleRepositoryImplTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/rule/RuleRepositoryImplTest.java index cc94dab3987..3355927d1d5 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/rule/RuleRepositoryImplTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/rule/RuleRepositoryImplTest.java @@ -22,11 +22,11 @@ package org.sonar.ce.task.projectexport.rule; import java.util.Collection; import java.util.Random; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.rule.RuleKey; import org.sonar.core.util.Uuids; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class RuleRepositoryImplTest { private static final String SOME_UUID = "uuid-846"; @@ -34,8 +34,6 @@ public class RuleRepositoryImplTest { private static final String SOME_RULE_KEY = "key"; private static final Rule SOME_RULE = new Rule("uuid-1", SOME_REPOSITORY, SOME_RULE_KEY); - @org.junit.Rule - public ExpectedException expectedException = ExpectedException.none(); private Random random = new Random(); @@ -43,10 +41,9 @@ public class RuleRepositoryImplTest { @Test public void register_throws_NPE_if_ruleKey_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("ruleKey can not be null"); - - underTest.register(SOME_UUID, null); + assertThatThrownBy(() -> underTest.register(SOME_UUID, null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("ruleKey can not be null"); } @Test @@ -64,20 +61,18 @@ public class RuleRepositoryImplTest { public void register_fails_IAE_if_RuleKey_is_not_the_same_repository_for_a_specific_ref() { underTest.register(SOME_UUID, RuleKey.of(SOME_REPOSITORY, SOME_RULE_KEY)); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Specified RuleKey 'other repo:key' is not equal to the one already registered in repository for ref " + SOME_UUID + ": 'rep:key'"); - - underTest.register(SOME_UUID, RuleKey.of("other repo", SOME_RULE_KEY)); + assertThatThrownBy(() -> underTest.register(SOME_UUID, RuleKey.of("other repo", SOME_RULE_KEY))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Specified RuleKey 'other repo:key' is not equal to the one already registered in repository for ref " + SOME_UUID + ": 'rep:key'"); } @Test public void register_fails_IAE_if_RuleKey_is_not_the_same_key_for_a_specific_ref() { underTest.register(SOME_UUID, RuleKey.of(SOME_REPOSITORY, SOME_RULE_KEY)); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Specified RuleKey 'rep:other key' is not equal to the one already registered in repository for ref " + SOME_UUID + ": 'rep:key'"); - - underTest.register(SOME_UUID, RuleKey.of(SOME_REPOSITORY, "other key")); + assertThatThrownBy(() -> underTest.register(SOME_UUID, RuleKey.of(SOME_REPOSITORY, "other key"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Specified RuleKey 'rep:other key' is not equal to the one already registered in repository for ref " + SOME_UUID + ": 'rep:key'"); } @Test @@ -105,7 +100,8 @@ public class RuleRepositoryImplTest { Collection all = underTest.getAll(); assertThat(all).isEmpty(); - ensureImmutable(all); + assertThatThrownBy(() -> all.add(SOME_RULE)) + .isInstanceOf(UnsupportedOperationException.class); } @Test @@ -125,12 +121,9 @@ public class RuleRepositoryImplTest { assertThat(all).extracting(Rule::getRepository).containsOnly(repositories); assertThat(all).extracting(Rule::getKey).containsOnly(keys); - ensureImmutable(all); - } - private void ensureImmutable(Collection collection) { - expectedException.expect(UnsupportedOperationException.class); - collection.add(SOME_RULE); + assertThatThrownBy(() -> all.add(SOME_RULE)) + .isInstanceOf(UnsupportedOperationException.class); } private int someRandomInt() { diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/rule/RuleTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/rule/RuleTest.java index 28cab509a77..bac31d4b1c6 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/rule/RuleTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/rule/RuleTest.java @@ -20,34 +20,30 @@ package org.sonar.ce.task.projectexport.rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class RuleTest { private static final String SOME_DUMP_UUID = "uuid-12334"; private static final String SOME_REPOSITORY = "some repository"; private static final String SOME_KEY = "some key"; - @org.junit.Rule - public ExpectedException expectedException = ExpectedException.none(); private Rule underTest = new Rule(SOME_DUMP_UUID, SOME_REPOSITORY, SOME_KEY); @Test public void constructor_throws_NPE_if_repository_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("repository can not be null"); - - new Rule(SOME_DUMP_UUID, null, SOME_KEY); + assertThatThrownBy(() -> new Rule(SOME_DUMP_UUID, null, SOME_KEY)) + .isInstanceOf(NullPointerException.class) + .hasMessage("repository can not be null"); } @Test public void constructor_throws_NPE_if_key_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("key can not be null"); - - new Rule(SOME_DUMP_UUID, SOME_REPOSITORY, null); + assertThatThrownBy(() -> new Rule(SOME_DUMP_UUID, SOME_REPOSITORY, null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("key can not be null"); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/steps/DumpElementTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/steps/DumpElementTest.java index 26ea45f2759..769136af7d3 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/steps/DumpElementTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/steps/DumpElementTest.java @@ -23,7 +23,18 @@ import com.sonarsource.governance.projectdump.protobuf.ProjectDump; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; -import static org.sonar.ce.task.projectexport.steps.DumpElement.*; +import static org.sonar.ce.task.projectexport.steps.DumpElement.ANALYSES; +import static org.sonar.ce.task.projectexport.steps.DumpElement.COMPONENTS; +import static org.sonar.ce.task.projectexport.steps.DumpElement.EVENTS; +import static org.sonar.ce.task.projectexport.steps.DumpElement.ISSUES; +import static org.sonar.ce.task.projectexport.steps.DumpElement.ISSUES_CHANGELOG; +import static org.sonar.ce.task.projectexport.steps.DumpElement.LINKS; +import static org.sonar.ce.task.projectexport.steps.DumpElement.MEASURES; +import static org.sonar.ce.task.projectexport.steps.DumpElement.METADATA; +import static org.sonar.ce.task.projectexport.steps.DumpElement.METRICS; +import static org.sonar.ce.task.projectexport.steps.DumpElement.PLUGINS; +import static org.sonar.ce.task.projectexport.steps.DumpElement.RULES; +import static org.sonar.ce.task.projectexport.steps.DumpElement.SETTINGS; public class DumpElementTest { diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/steps/DumpWriterImplTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/steps/DumpWriterImplTest.java index 1cd1666bc1c..b876344ffee 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/steps/DumpWriterImplTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/steps/DumpWriterImplTest.java @@ -25,7 +25,6 @@ import java.io.File; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.sonar.api.utils.TempFolder; import org.sonar.api.utils.log.LogTester; @@ -34,14 +33,13 @@ import org.sonar.ce.task.projectexport.taskprocessor.ProjectDescriptor; import org.sonar.ce.task.projectexport.util.ProjectExportDumpFS; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.ce.task.projectexport.steps.DumpElement.COMPONENTS; public class DumpWriterImplTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public TemporaryFolder junitTemp = new TemporaryFolder(); @@ -81,9 +79,9 @@ public class DumpWriterImplTest { public void writeMetadata_fails_if_called_twice() { underTest.write(newMetadata()); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Metadata has already been written"); - underTest.write(newMetadata()); + assertThatThrownBy(() -> underTest.write(newMetadata())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Metadata has already been written"); } @Test @@ -102,16 +100,16 @@ public class DumpWriterImplTest { underTest.write(newMetadata()); underTest.publish(); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Dump is already published"); - underTest.publish(); + assertThatThrownBy(() -> underTest.publish()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Dump is already published"); } @Test public void publish_fails_if_metadata_is_missing() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Metadata is missing"); - underTest.publish(); + assertThatThrownBy(() -> underTest.publish()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Metadata is missing"); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/steps/ExportEventsStepTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/steps/ExportEventsStepTest.java index bfac265a168..a0ebffa634e 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/steps/ExportEventsStepTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/steps/ExportEventsStepTest.java @@ -24,7 +24,6 @@ import java.util.List; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.resources.Qualifiers; import org.sonar.api.resources.Scopes; import org.sonar.api.utils.System2; @@ -38,6 +37,7 @@ import org.sonar.db.component.SnapshotDto; import org.sonar.db.event.EventDto; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.db.component.ComponentDto.UUID_PATH_OF_ROOT; import static org.sonar.db.component.SnapshotDto.STATUS_PROCESSED; @@ -57,8 +57,6 @@ public class ExportEventsStepTest { .setDbKey("the_project") .setEnabled(true); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); @@ -108,9 +106,9 @@ public class ExportEventsStepTest { insertEvent(snapshot, "E2", "two"); dumpWriter.failIfMoreThan(1, DumpElement.EVENTS); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Event Export failed after processing 1 events successfully"); - underTest.execute(new TestComputationStepContext()); + assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Event Export failed after processing 1 events successfully"); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/steps/ExportLinksStepTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/steps/ExportLinksStepTest.java index 86c2baafde0..939b1b3ff6b 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/steps/ExportLinksStepTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/steps/ExportLinksStepTest.java @@ -23,7 +23,6 @@ import com.sonarsource.governance.projectdump.protobuf.ProjectDump.Link; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.resources.Qualifiers; import org.sonar.api.resources.Scopes; import org.sonar.api.utils.System2; @@ -37,6 +36,7 @@ import org.sonar.db.component.ProjectLinkDto; import org.sonar.db.project.ProjectExportMapper; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.groups.Tuple.tuple; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -63,8 +63,6 @@ public class ExportLinksStepTest { @Rule public DbTester db = DbTester.createWithExtensionMappers(System2.INSTANCE, ProjectExportMapper.class); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public LogTester logTester = new LogTester(); @@ -114,9 +112,9 @@ public class ExportLinksStepTest { dumpWriter.failIfMoreThan(2, DumpElement.LINKS); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Link export failed after processing 2 link(s) successfully"); - underTest.execute(new TestComputationStepContext()); + assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Link export failed after processing 2 link(s) successfully"); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/steps/ExportLiveMeasuresStepTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/steps/ExportLiveMeasuresStepTest.java index 0ed2e499887..0fc13dd7f5a 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/steps/ExportLiveMeasuresStepTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/steps/ExportLiveMeasuresStepTest.java @@ -23,7 +23,6 @@ import com.sonarsource.governance.projectdump.protobuf.ProjectDump; import java.util.List; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.utils.System2; import org.sonar.api.utils.log.LogTester; import org.sonar.api.utils.log.LoggerLevel; @@ -44,8 +43,6 @@ import static org.mockito.Mockito.when; import static org.sonar.api.measures.Metric.ValueType.INT; public class ExportLiveMeasuresStepTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public LogTester logTester = new LogTester(); @Rule diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/steps/ExportMeasuresStepTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/steps/ExportMeasuresStepTest.java index 251bbc97183..ad73d378f01 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/steps/ExportMeasuresStepTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/steps/ExportMeasuresStepTest.java @@ -24,7 +24,6 @@ import java.util.List; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.utils.System2; import org.sonar.api.utils.log.LogTester; import org.sonar.api.utils.log.LoggerLevel; @@ -90,8 +89,6 @@ public class ExportMeasuresStepTest { .setUuid(PROJECT.uuid()) .setProjectUuid(PROJECT.uuid())); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public LogTester logTester = new LogTester(); diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/steps/ExportMetricsStepTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/steps/ExportMetricsStepTest.java index 676fc0639c8..9b8aad95849 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/steps/ExportMetricsStepTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/steps/ExportMetricsStepTest.java @@ -26,7 +26,6 @@ import javax.annotation.Nonnull; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.utils.System2; import org.sonar.api.utils.log.LogTester; import org.sonar.api.utils.log.LoggerLevel; @@ -36,6 +35,7 @@ import org.sonar.db.metric.MetricDto; import static com.google.common.collect.FluentIterable.from; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class ExportMetricsStepTest { @@ -50,8 +50,6 @@ public class ExportMetricsStepTest { .setShortName("Coverage") .setEnabled(true); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public LogTester logTester = new LogTester(); @@ -102,11 +100,9 @@ public class ExportMetricsStepTest { metricsHolder.add(NCLOC.getUuid()); dumpWriter.failIfMoreThan(0, DumpElement.METRICS); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Metric Export failed after processing 0 metrics successfully"); - underTest.execute(new TestComputationStepContext()); - - assertThat(logTester.logs(LoggerLevel.DEBUG)).contains("Metric Export failed after processing 0 metrics successfully"); + assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Metric Export failed after processing 0 metrics successfully"); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/steps/ExportNewCodePeriodsStepTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/steps/ExportNewCodePeriodsStepTest.java index b171bff692a..557948f6cb4 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/steps/ExportNewCodePeriodsStepTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/steps/ExportNewCodePeriodsStepTest.java @@ -27,7 +27,6 @@ import javax.annotation.Nullable; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.resources.Qualifiers; import org.sonar.api.utils.System2; import org.sonar.api.utils.log.LogTester; @@ -42,6 +41,7 @@ import org.sonar.db.newcodeperiod.NewCodePeriodType; import org.sonar.db.project.ProjectExportMapper; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.db.component.ComponentDto.UUID_PATH_OF_ROOT; import static org.sonar.db.newcodeperiod.NewCodePeriodType.PREVIOUS_VERSION; import static org.sonar.db.newcodeperiod.NewCodePeriodType.SPECIFIC_ANALYSIS; @@ -78,8 +78,6 @@ public class ExportNewCodePeriodsStepTest { new BranchDto().setBranchType(BranchType.BRANCH).setProjectUuid(ANOTHER_PROJECT_UUID).setKey("branch-3").setUuid("branch-uuid-3").setMergeBranchUuid("master") .setExcludeFromPurge(true)); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public LogTester logTester = new LogTester(); @Rule @@ -150,9 +148,9 @@ public class ExportNewCodePeriodsStepTest { newDto("uuid1", PROJECT.uuid(), null, SPECIFIC_ANALYSIS, "analysis-uuid"), newDto("uuid2", PROJECT.uuid(), "branch-uuid-1", SPECIFIC_ANALYSIS, "analysis-uuid")); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("New Code Periods Export failed after processing 1 new code periods successfully"); - underTest.execute(new TestComputationStepContext()); + assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("New Code Periods Export failed after processing 1 new code periods successfully"); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/steps/ExportSettingsStepTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/steps/ExportSettingsStepTest.java index 4c25a186542..ace5c0a3520 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/steps/ExportSettingsStepTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/steps/ExportSettingsStepTest.java @@ -25,7 +25,6 @@ import javax.annotation.Nullable; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.resources.Qualifiers; import org.sonar.api.utils.System2; import org.sonar.api.utils.log.LogTester; @@ -39,6 +38,7 @@ import org.sonar.db.project.ProjectExportMapper; import org.sonar.db.property.PropertyDto; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.db.component.ComponentDto.UUID_PATH_OF_ROOT; public class ExportSettingsStepTest { @@ -57,8 +57,6 @@ public class ExportSettingsStepTest { .setProjectUuid("another_project_uuid") .setDbKey("another_project"); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public LogTester logTester = new LogTester(); @Rule @@ -143,9 +141,9 @@ public class ExportSettingsStepTest { insertProperties(PROJECT.getKey(), PROJECT.name(), newDto("p1", null, PROJECT), newDto("p2", null, PROJECT)); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Settings Export failed after processing 1 settings successfully"); - underTest.execute(new TestComputationStepContext()); + assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Settings Export failed after processing 1 settings successfully"); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/steps/LoadProjectStepTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/steps/LoadProjectStepTest.java index 4aa0d6b55c5..def7d554391 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/steps/LoadProjectStepTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/steps/LoadProjectStepTest.java @@ -21,7 +21,6 @@ package org.sonar.ce.task.projectexport.steps; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.resources.Qualifiers; import org.sonar.api.utils.MessageException; import org.sonar.api.utils.System2; @@ -31,13 +30,12 @@ import org.sonar.db.DbTester; import org.sonar.db.component.ComponentDto; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class LoadProjectStepTest { private static final String PROJECT_KEY = "project_key"; - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); @@ -47,9 +45,9 @@ public class LoadProjectStepTest { @Test public void fails_if_project_does_not_exist() { - expectedException.expect(MessageException.class); - expectedException.expectMessage("Project with key [project_key] does not exist"); - underTest.execute(new TestComputationStepContext()); + assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext())) + .isInstanceOf(MessageException.class) + .hasMessage("Project with key [project_key] does not exist"); } @Test @@ -63,9 +61,9 @@ public class LoadProjectStepTest { "created_at", 1L, "updated_at", 1L); - expectedException.expect(MessageException.class); - expectedException.expectMessage("Project with key [project_key] does not exist"); - underTest.execute(new TestComputationStepContext()); + assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext())) + .isInstanceOf(MessageException.class) + .hasMessage("Project with key [project_key] does not exist"); } @Test diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/util/Files2Test.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/util/Files2Test.java index 26461d03bb9..1b8ad44cc0f 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/util/Files2Test.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/util/Files2Test.java @@ -26,20 +26,16 @@ import java.io.IOException; import java.nio.file.Files; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; -import org.hamcrest.Description; -import org.hamcrest.TypeSafeMatcher; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.spy; public class Files2Test { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public TemporaryFolder temp = new TemporaryFolder(); @@ -76,8 +72,8 @@ public class Files2Test { File file = temp.newFile(); doThrow(new IOException("failure")).when(underTest).deleteIfExistsOrThrowIOE(file); - expectedException.expect(IllegalStateException.class); - underTest.deleteIfExists(file); + assertThatThrownBy(() -> underTest.deleteIfExists(file)) + .isInstanceOf(IllegalStateException.class); } @Test @@ -95,20 +91,20 @@ public class Files2Test { final File file = temp.newFile(); assertThat(file.delete()).isTrue(); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Can not open file " + file); - expectCauseMessage("File " + file + " does not exist"); - underTest.openInputStream(file); + assertThatThrownBy(() -> underTest.openInputStream(file)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Can not open file " + file) + .hasRootCauseMessage("File " + file + " does not exist"); } @Test public void openInputStream_throws_ISE_if_file_is_a_directory() throws Exception { File dir = temp.newFolder(); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Can not open file " + dir); - expectCauseMessage("File " + dir + " exists but is a directory"); - underTest.openInputStream(dir); + assertThatThrownBy(() -> underTest.openInputStream(dir)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Can not open file " + dir) + .hasRootCauseMessage("File " + dir + " exists but is a directory"); } @Test @@ -148,10 +144,10 @@ public class Files2Test { public void openOutputStream_throws_ISE_if_file_is_a_directory() throws Exception { File dir = temp.newFolder(); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Can not open file " + dir); - expectCauseMessage("File " + dir + " exists but is a directory"); - underTest.openOutputStream(dir, false); + assertThatThrownBy(() -> underTest.openOutputStream(dir, false)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Can not open file " + dir) + .hasRootCauseMessage("File " + dir + " exists but is a directory"); } @Test @@ -173,20 +169,20 @@ public class Files2Test { File dir = temp.newFolder(); underTest.deleteIfExists(dir); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Can not zip directory " + dir); - expectCauseMessage("Directory " + dir + " does not exist"); - underTest.zipDir(dir, temp.newFile()); + assertThatThrownBy(() -> underTest.zipDir(dir, temp.newFile())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Can not zip directory " + dir) + .hasRootCauseMessage("Directory " + dir + " does not exist"); } @Test public void zipDir_throws_ISE_if_directory_is_a_file() throws Exception { File file = temp.newFile(); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Can not zip directory " + file); - expectCauseMessage("File " + file + " exists but is not a directory"); - underTest.zipDir(file, temp.newFile()); + assertThatThrownBy(() -> underTest.zipDir(file, temp.newFile())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Can not zip directory " + file) + .hasRootCauseMessage("File " + file + " exists but is not a directory"); } @Test @@ -221,32 +217,17 @@ public class Files2Test { public void createDir_throws_ISE_if_File_is_an_existing_file() throws IOException { File file = temp.newFile(); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage(file.toPath() + " is not a directory"); - - underTest.createDir(file); + assertThatThrownBy(() -> underTest.createDir(file)) + .isInstanceOf(IllegalStateException.class) + .hasMessage(file.toPath() + " is not a directory"); } @Test public void createDir_throws_ISE_if_File_is_an_existing_link() throws IOException { File file = Files.createLink(new File(temp.newFolder(), "toto.lnk").toPath(), temp.newFile().toPath()).toFile(); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage(file.toPath() + " is not a directory"); - - underTest.createDir(file); - } - - private void expectCauseMessage(final String msg) { - expectedException.expectCause(new TypeSafeMatcher() { - @Override - protected boolean matchesSafely(Throwable throwable) { - return throwable.getMessage().contains(msg); - } - - @Override - public void describeTo(Description description) { - } - }); + assertThatThrownBy(() -> underTest.createDir(file)) + .isInstanceOf(IllegalStateException.class) + .hasMessage(file.toPath() + " is not a directory"); } } diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/util/Protobuf2Test.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/util/Protobuf2Test.java index 741e91a021f..766c840e0b4 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/util/Protobuf2Test.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/util/Protobuf2Test.java @@ -28,10 +28,10 @@ import java.io.InputStream; import java.io.OutputStream; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.ce.task.util.Files2.FILES2; public class Protobuf2Test { @@ -42,9 +42,6 @@ public class Protobuf2Test { @Rule public TemporaryFolder temp = new TemporaryFolder(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); - Protobuf2 underTest = Protobuf2.PROTOBUF2; @Test @@ -76,36 +73,36 @@ public class Protobuf2Test { @Test public void writeTo_throws_ISE_on_error() throws Exception { try (FailureOutputStream output = new FailureOutputStream()) { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Can not write message"); - underTest.writeTo(newMetadata(PROJECT_KEY_1), output); + assertThatThrownBy(() -> underTest.writeTo(newMetadata(PROJECT_KEY_1), output)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Can not write message"); } } @Test public void writeDelimitedTo_throws_ISE_on_error() throws Exception { try (FailureOutputStream output = new FailureOutputStream()) { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Can not write message"); - underTest.writeDelimitedTo(newMetadata(PROJECT_KEY_1), output); + assertThatThrownBy(() -> underTest.writeDelimitedTo(newMetadata(PROJECT_KEY_1), output)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Can not write message"); } } @Test public void parseFrom_throws_ISE_on_error() throws Exception { try (FailureInputStream input = new FailureInputStream()) { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Can not parse message"); - underTest.parseFrom(Metadata.parser(), input); + assertThatThrownBy(() -> underTest.parseFrom(Metadata.parser(), input)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Can not parse message"); } } @Test public void parseDelimitedFrom_throws_ISE_on_error() throws Exception { try (FailureInputStream input = new FailureInputStream()) { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Can not parse message"); - underTest.parseDelimitedFrom(Metadata.parser(), input); + assertThatThrownBy(() -> underTest.parseDelimitedFrom(Metadata.parser(), input)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Can not parse message"); } } diff --git a/server/sonar-ce-task/src/test/java/org/sonar/ce/task/CeTaskComponentTest.java b/server/sonar-ce-task/src/test/java/org/sonar/ce/task/CeTaskComponentTest.java index 8ce0b099685..4389facfb02 100644 --- a/server/sonar-ce-task/src/test/java/org/sonar/ce/task/CeTaskComponentTest.java +++ b/server/sonar-ce-task/src/test/java/org/sonar/ce/task/CeTaskComponentTest.java @@ -22,26 +22,22 @@ package org.sonar.ce.task; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; @RunWith(DataProviderRunner.class) public class CeTaskComponentTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test @UseDataProvider("nullOrEmpty") public void constructor_fails_with_NPE_if_uuid_is_null_or_empty(String str) { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("uuid can't be null nor empty"); - - new CeTask.Component(str, "foo", "bar"); + assertThatThrownBy(() -> new CeTask.Component(str, "foo", "bar")) + .isInstanceOf(NullPointerException.class) + .hasMessage("uuid can't be null nor empty"); } @Test diff --git a/server/sonar-ce-task/src/test/java/org/sonar/ce/task/CeTaskTest.java b/server/sonar-ce-task/src/test/java/org/sonar/ce/task/CeTaskTest.java index 3800f861cb6..08b12549b77 100644 --- a/server/sonar-ce-task/src/test/java/org/sonar/ce/task/CeTaskTest.java +++ b/server/sonar-ce-task/src/test/java/org/sonar/ce/task/CeTaskTest.java @@ -23,18 +23,15 @@ import com.google.common.collect.ImmutableMap; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.entry; @RunWith(DataProviderRunner.class) public class CeTaskTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private CeTask.Builder underTest = new CeTask.Builder(); @@ -46,10 +43,9 @@ public class CeTaskTest { underTest.setComponent(component); underTest.setMainComponent(mainComponent); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("None or both component and main component must be non null"); - - underTest.build(); + assertThatThrownBy(() -> underTest.build()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("None or both component and main component must be non null"); } @DataProvider diff --git a/server/sonar-ce-task/src/test/java/org/sonar/ce/task/container/TaskContainerImplTest.java b/server/sonar-ce-task/src/test/java/org/sonar/ce/task/container/TaskContainerImplTest.java index 935bb05f9dd..a4c6834d9a3 100644 --- a/server/sonar-ce-task/src/test/java/org/sonar/ce/task/container/TaskContainerImplTest.java +++ b/server/sonar-ce-task/src/test/java/org/sonar/ce/task/container/TaskContainerImplTest.java @@ -25,6 +25,7 @@ import org.sonar.core.platform.ComponentContainer; import org.sonar.core.platform.ContainerPopulator; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; @@ -32,14 +33,16 @@ public class TaskContainerImplTest { private ComponentContainer parent = new ComponentContainer(); private ContainerPopulator populator = spy(new DummyContainerPopulator()); - @Test(expected = NullPointerException.class) + @Test public void constructor_fails_fast_on_null_container() { - new TaskContainerImpl(null, populator); + assertThatThrownBy(() -> new TaskContainerImpl(null, populator)) + .isInstanceOf(NullPointerException.class); } - @Test(expected = NullPointerException.class) + @Test public void constructor_fails_fast_on_null_item() { - new TaskContainerImpl(new ComponentContainer(), null); + assertThatThrownBy(() -> new TaskContainerImpl(new ComponentContainer(), null)) + .isInstanceOf(NullPointerException.class); } @Test diff --git a/server/sonar-ce-task/src/test/java/org/sonar/ce/task/log/CeTaskLoggingTest.java b/server/sonar-ce-task/src/test/java/org/sonar/ce/task/log/CeTaskLoggingTest.java index 7afc0b7b0d6..fda2bb00aff 100644 --- a/server/sonar-ce-task/src/test/java/org/sonar/ce/task/log/CeTaskLoggingTest.java +++ b/server/sonar-ce-task/src/test/java/org/sonar/ce/task/log/CeTaskLoggingTest.java @@ -21,9 +21,7 @@ package org.sonar.ce.task.log; import ch.qos.logback.core.joran.spi.JoranException; import org.junit.After; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.Mockito; import org.slf4j.MDC; import org.sonar.ce.task.CeTask; @@ -35,8 +33,6 @@ import static org.sonar.ce.task.log.CeTaskLogging.MDC_CE_TASK_UUID; public class CeTaskLoggingTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private LogbackHelper helper = new LogbackHelper(); private CeTaskLogging underTest = new CeTaskLogging(); diff --git a/server/sonar-ce-task/src/test/java/org/sonar/ce/task/log/CeTaskMessagesImplTest.java b/server/sonar-ce-task/src/test/java/org/sonar/ce/task/log/CeTaskMessagesImplTest.java index 301441b21e0..245b8b921dc 100644 --- a/server/sonar-ce-task/src/test/java/org/sonar/ce/task/log/CeTaskMessagesImplTest.java +++ b/server/sonar-ce-task/src/test/java/org/sonar/ce/task/log/CeTaskMessagesImplTest.java @@ -28,7 +28,6 @@ import java.util.stream.IntStream; import java.util.stream.Stream; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.sonar.api.utils.System2; @@ -41,6 +40,7 @@ import static java.util.stream.Collectors.toList; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyZeroInteractions; @@ -49,8 +49,6 @@ import static org.mockito.Mockito.when; public class CeTaskMessagesImplTest { @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private DbClient dbClient = dbTester.getDbClient(); private UuidFactory uuidFactory = mock(UuidFactory.class); @@ -65,9 +63,9 @@ public class CeTaskMessagesImplTest { @Test public void add_fails_with_NPE_if_arg_is_null() { - expectMessageCantBeNullNPE(); - - underTest.add(null); + assertThatThrownBy(() -> underTest.add(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("message can't be null"); } @Test @@ -85,9 +83,8 @@ public class CeTaskMessagesImplTest { @Test public void addAll_fails_with_NPE_if_arg_is_null() { - expectedException.expect(NullPointerException.class); - - underTest.addAll(null); + assertThatThrownBy(() -> underTest.addAll(null)) + .isInstanceOf(NullPointerException.class); } @Test @@ -102,9 +99,9 @@ public class CeTaskMessagesImplTest { .flatMap(t -> t) .collect(toList()); - expectMessageCantBeNullNPE(); - - underTest.addAll(messages); + assertThatThrownBy(() -> underTest.addAll(messages)) + .isInstanceOf(NullPointerException.class) + .hasMessage("message can't be null"); } @Test @@ -146,9 +143,4 @@ public class CeTaskMessagesImplTest { tuple(uuids[3], taskUuid, messages[3].getText(), messages[3].getTimestamp()), tuple(uuids[4], taskUuid, messages[4].getText(), messages[4].getTimestamp())); } - - private void expectMessageCantBeNullNPE() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("message can't be null"); - } } diff --git a/server/sonar-ce-task/src/test/java/org/sonar/ce/task/step/ComputationStepExecutorTest.java b/server/sonar-ce-task/src/test/java/org/sonar/ce/task/step/ComputationStepExecutorTest.java index b914e3def83..3921cee2ab7 100644 --- a/server/sonar-ce-task/src/test/java/org/sonar/ce/task/step/ComputationStepExecutorTest.java +++ b/server/sonar-ce-task/src/test/java/org/sonar/ce/task/step/ComputationStepExecutorTest.java @@ -23,7 +23,6 @@ import java.util.Arrays; import java.util.List; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.InOrder; import org.sonar.api.utils.log.LogTester; import org.sonar.api.utils.log.LoggerLevel; @@ -31,6 +30,7 @@ import org.sonar.ce.task.CeTaskInterrupter; import org.sonar.ce.task.ChangeLogLevel; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; @@ -46,8 +46,6 @@ import static org.mockito.Mockito.when; public class ComputationStepExecutorTest { @Rule public LogTester logTester = new LogTester(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private final ComputationStepExecutor.Listener listener = mock(ComputationStepExecutor.Listener.class); private final CeTaskInterrupter taskInterrupter = mock(CeTaskInterrupter.class); @@ -81,10 +79,9 @@ public class ComputationStepExecutorTest { ComputationStepExecutor computationStepExecutor = new ComputationStepExecutor(mockComputationSteps(computationStep), taskInterrupter); - expectedException.expect(RuntimeException.class); - expectedException.expectMessage(message); - - computationStepExecutor.execute(); + assertThatThrownBy(computationStepExecutor::execute) + .isInstanceOf(RuntimeException.class) + .hasMessage(message); } @Test @@ -143,10 +140,9 @@ public class ComputationStepExecutorTest { ComputationStep step = new StepWithStatistics("A Step", "foo", "100", "time", "20"); try (ChangeLogLevel executor = new ChangeLogLevel(ComputationStepExecutor.class, LoggerLevel.INFO)) { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Statistic with key [time] is not accepted"); - - new ComputationStepExecutor(mockComputationSteps(step), taskInterrupter).execute(); + assertThatThrownBy(() -> new ComputationStepExecutor(mockComputationSteps(step), taskInterrupter).execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Statistic with key [time] is not accepted"); } } @@ -155,10 +151,9 @@ public class ComputationStepExecutorTest { ComputationStep step = new StepWithStatistics("A Step", "foo", "100", "foo", "20"); try (ChangeLogLevel executor = new ChangeLogLevel(ComputationStepExecutor.class, LoggerLevel.INFO)) { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Statistic with key [foo] is already present"); - - new ComputationStepExecutor(mockComputationSteps(step), taskInterrupter).execute(); + assertThatThrownBy(() -> new ComputationStepExecutor(mockComputationSteps(step), taskInterrupter).execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Statistic with key [foo] is already present"); } } @@ -167,10 +162,9 @@ public class ComputationStepExecutorTest { ComputationStep step = new StepWithStatistics("A Step", "foo", "100", null, "bar"); try (ChangeLogLevel executor = new ChangeLogLevel(ComputationStepExecutor.class, LoggerLevel.INFO)) { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("Statistic has null key"); - - new ComputationStepExecutor(mockComputationSteps(step), taskInterrupter).execute(); + assertThatThrownBy(() -> new ComputationStepExecutor(mockComputationSteps(step), taskInterrupter).execute()) + .isInstanceOf(NullPointerException.class) + .hasMessage("Statistic has null key"); } } @@ -179,10 +173,9 @@ public class ComputationStepExecutorTest { ComputationStep step = new StepWithStatistics("A Step", "foo", "100", "bar", null); try (ChangeLogLevel executor = new ChangeLogLevel(ComputationStepExecutor.class, LoggerLevel.INFO)) { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("Statistic with key [bar] has null value"); - - new ComputationStepExecutor(mockComputationSteps(step), taskInterrupter).execute(); + assertThatThrownBy(() -> new ComputationStepExecutor(mockComputationSteps(step), taskInterrupter).execute()) + .isInstanceOf(NullPointerException.class) + .hasMessage("Statistic with key [bar] has null value"); } } diff --git a/server/sonar-ce-task/src/test/java/org/sonar/ce/task/step/ExecuteStatelessInitExtensionsStepTest.java b/server/sonar-ce-task/src/test/java/org/sonar/ce/task/step/ExecuteStatelessInitExtensionsStepTest.java index 1885d5bb4c0..d828b5a6492 100644 --- a/server/sonar-ce-task/src/test/java/org/sonar/ce/task/step/ExecuteStatelessInitExtensionsStepTest.java +++ b/server/sonar-ce-task/src/test/java/org/sonar/ce/task/step/ExecuteStatelessInitExtensionsStepTest.java @@ -19,9 +19,7 @@ */ package org.sonar.ce.task.step; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.InOrder; import static org.assertj.core.api.Assertions.assertThat; @@ -34,8 +32,6 @@ import static org.mockito.Mockito.verify; public class ExecuteStatelessInitExtensionsStepTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void test_getDescription() { diff --git a/server/sonar-ce-task/src/test/java/org/sonar/ce/task/taskprocessor/MutableTaskResultHolderImplTest.java b/server/sonar-ce-task/src/test/java/org/sonar/ce/task/taskprocessor/MutableTaskResultHolderImplTest.java index 4f82a45bdf2..bd1dcfd183f 100644 --- a/server/sonar-ce-task/src/test/java/org/sonar/ce/task/taskprocessor/MutableTaskResultHolderImplTest.java +++ b/server/sonar-ce-task/src/test/java/org/sonar/ce/task/taskprocessor/MutableTaskResultHolderImplTest.java @@ -20,25 +20,21 @@ package org.sonar.ce.task.taskprocessor; import org.assertj.core.api.Assertions; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.ce.task.CeTaskResult; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; public class MutableTaskResultHolderImplTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private MutableTaskResultHolder underTest = new MutableTaskResultHolderImpl(); @Test public void getResult_throws_ISE_if_no_CeTaskResult_is_set() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("No CeTaskResult has been set in the holder"); - - underTest.getResult(); + assertThatThrownBy(() -> underTest.getResult()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("No CeTaskResult has been set in the holder"); } @Test @@ -52,19 +48,17 @@ public class MutableTaskResultHolderImplTest { @Test public void setResult_throws_NPE_if_CeTaskResult_argument_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("taskResult can not be null"); - - underTest.setResult(null); + assertThatThrownBy(() -> underTest.setResult(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("taskResult can not be null"); } @Test public void setResult_throws_ISE_if_called_twice() { underTest.setResult(mock(CeTaskResult.class)); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("CeTaskResult has already been set in the holder"); - - underTest.setResult(mock(CeTaskResult.class)); + assertThatThrownBy(() -> underTest.setResult(mock(CeTaskResult.class))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("CeTaskResult has already been set in the holder"); } } diff --git a/server/sonar-ce/src/main/java/org/sonar/ce/ComputeEngineImpl.java b/server/sonar-ce/src/main/java/org/sonar/ce/ComputeEngineImpl.java index a801aa0fc15..f5a8dde6bf5 100644 --- a/server/sonar-ce/src/main/java/org/sonar/ce/ComputeEngineImpl.java +++ b/server/sonar-ce/src/main/java/org/sonar/ce/ComputeEngineImpl.java @@ -74,8 +74,6 @@ public class ComputeEngineImpl implements ComputeEngine, ComputeEngineStatus { this.status = Status.STOPPED; } } - - @Override public Status getStatus() { return status; diff --git a/server/sonar-ce/src/test/java/org/sonar/ce/ComputeEngineImplTest.java b/server/sonar-ce/src/test/java/org/sonar/ce/ComputeEngineImplTest.java index 241fc1c0106..baac8bed39f 100644 --- a/server/sonar-ce/src/test/java/org/sonar/ce/ComputeEngineImplTest.java +++ b/server/sonar-ce/src/test/java/org/sonar/ce/ComputeEngineImplTest.java @@ -20,16 +20,14 @@ package org.sonar.ce; import java.util.Properties; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.sonar.ce.container.ComputeEngineStatus; import org.sonar.ce.container.ComputeEngineContainer; +import org.sonar.ce.container.ComputeEngineStatus; import org.sonar.process.Props; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + public class ComputeEngineImplTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private ComputeEngineContainer computeEngineContainer = new NoOpComputeEngineContainer(); private ComputeEngine underTest = new ComputeEngineImpl(new Props(new Properties()), computeEngineContainer); @@ -38,18 +36,16 @@ public class ComputeEngineImplTest { public void startup_throws_ISE_when_called_twice() { underTest.startup(); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("startup() can not be called multiple times"); - - underTest.startup(); + assertThatThrownBy(() -> underTest.startup()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("startup() can not be called multiple times"); } @Test public void stopProcessing_throws_ISE_if_startup_was_not_called_before() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("stopProcessing() must not be called before startup()"); - - underTest.stopProcessing(); + assertThatThrownBy(() -> underTest.stopProcessing()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("stopProcessing() must not be called before startup()"); } @Test @@ -57,10 +53,9 @@ public class ComputeEngineImplTest { underTest.startup(); underTest.shutdown(); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("stopProcessing() can not be called after shutdown()"); - - underTest.stopProcessing(); + assertThatThrownBy(() -> underTest.stopProcessing()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("stopProcessing() can not be called after shutdown()"); } @Test @@ -68,18 +63,16 @@ public class ComputeEngineImplTest { underTest.startup(); underTest.stopProcessing(); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("stopProcessing() can not be called multiple times"); - - underTest.stopProcessing(); + assertThatThrownBy(() -> underTest.stopProcessing()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("stopProcessing() can not be called multiple times"); } @Test public void shutdown_throws_ISE_if_startup_was_not_called_before() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("shutdown() must not be called before startup()"); - - underTest.shutdown(); + assertThatThrownBy(() -> underTest.shutdown()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("shutdown() must not be called before startup()"); } @Test @@ -87,10 +80,9 @@ public class ComputeEngineImplTest { underTest.startup(); underTest.shutdown(); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("shutdown() can not be called multiple times"); - - underTest.shutdown(); + assertThatThrownBy(() -> underTest.shutdown()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("shutdown() can not be called multiple times"); } private static class NoOpComputeEngineContainer implements ComputeEngineContainer { diff --git a/server/sonar-ce/src/test/java/org/sonar/ce/StandaloneCeDistributedInformationTest.java b/server/sonar-ce/src/test/java/org/sonar/ce/StandaloneCeDistributedInformationTest.java index 24112d92496..bb706e41b6c 100644 --- a/server/sonar-ce/src/test/java/org/sonar/ce/StandaloneCeDistributedInformationTest.java +++ b/server/sonar-ce/src/test/java/org/sonar/ce/StandaloneCeDistributedInformationTest.java @@ -26,21 +26,18 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.stream.Collectors; import java.util.stream.IntStream; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.ce.taskprocessor.CeWorker; import org.sonar.ce.taskprocessor.CeWorkerFactory; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class StandaloneCeDistributedInformationTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void broadcastWorkerUUIDs_must_retrieve_from_ceworkerfactory() { @@ -74,10 +71,9 @@ public class StandaloneCeDistributedInformationTest { CeWorkerFactory ceWorkerFactory = mock(CeWorkerFactory.class); StandaloneCeDistributedInformation ceCluster = new StandaloneCeDistributedInformation(ceWorkerFactory); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Invalid call, broadcastWorkerUUIDs() must be called first."); - - ceCluster.getWorkerUUIDs(); + assertThatThrownBy(ceCluster::getWorkerUUIDs) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Invalid call, broadcastWorkerUUIDs() must be called first."); } @Test diff --git a/server/sonar-ce/src/test/java/org/sonar/ce/app/CeServerTest.java b/server/sonar-ce/src/test/java/org/sonar/ce/app/CeServerTest.java index a30c17c4f4a..77847b37133 100644 --- a/server/sonar-ce/src/test/java/org/sonar/ce/app/CeServerTest.java +++ b/server/sonar-ce/src/test/java/org/sonar/ce/app/CeServerTest.java @@ -30,7 +30,6 @@ import org.junit.After; import org.junit.Rule; import org.junit.Test; import org.junit.rules.DisableOnDebug; -import org.junit.rules.ExpectedException; import org.junit.rules.TestRule; import org.junit.rules.Timeout; import org.junit.runner.RunWith; @@ -43,6 +42,7 @@ import org.sonar.process.Monitored; import static com.google.common.base.Preconditions.checkState; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.awaitility.Awaitility.await; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -51,8 +51,6 @@ import static org.mockito.Mockito.verify; public class CeServerTest { @Rule public TestRule safeguardTimeout = new DisableOnDebug(Timeout.seconds(60)); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private CeServer underTest = null; private Thread waitingThread = null; @@ -88,10 +86,9 @@ public class CeServerTest { public void awaitStop_throws_ISE_if_called_before_start() { CeServer ceServer = newCeServer(); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("awaitStop() must not be called before start()"); - - ceServer.awaitStop(); + assertThatThrownBy(ceServer::awaitStop) + .isInstanceOf(IllegalStateException.class) + .hasMessage("awaitStop() must not be called before start()"); } @Test @@ -134,20 +131,18 @@ public class CeServerTest { ceServer.start(); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("start() can not be called twice"); - - ceServer.start(); + assertThatThrownBy(ceServer::start) + .isInstanceOf(IllegalStateException.class) + .hasMessage("start() can not be called twice"); } @Test public void getStatus_throws_ISE_when_called_before_start() { CeServer ceServer = newCeServer(); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("getStatus() can not be called before start()"); - - ceServer.getStatus(); + assertThatThrownBy(ceServer::getStatus) + .isInstanceOf(IllegalStateException.class) + .hasMessage("getStatus() can not be called before start()"); } @Test @@ -235,9 +230,8 @@ public class CeServerTest { public void staticMain_withoutAnyArguments_expectException() { String[] emptyArray = {}; - expectedException.expectMessage("Only a single command-line argument is accepted (absolute path to configuration file)"); - - CeServer.main(emptyArray); + assertThatThrownBy(() -> CeServer.main(emptyArray)) + .hasMessage("Only a single command-line argument is accepted (absolute path to configuration file)"); } @Test diff --git a/server/sonar-ce/src/test/java/org/sonar/ce/async/SynchronousAsyncExecutionTest.java b/server/sonar-ce/src/test/java/org/sonar/ce/async/SynchronousAsyncExecutionTest.java index 78de4aab639..200d0562a9b 100644 --- a/server/sonar-ce/src/test/java/org/sonar/ce/async/SynchronousAsyncExecutionTest.java +++ b/server/sonar-ce/src/test/java/org/sonar/ce/async/SynchronousAsyncExecutionTest.java @@ -21,23 +21,19 @@ package org.sonar.ce.async; import java.util.HashSet; import java.util.Set; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class SynchronousAsyncExecutionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private SynchronousAsyncExecution underTest = new SynchronousAsyncExecution(); @Test public void addToQueue_fails_with_NPE_if_Runnable_is_null() { - expectedException.expect(NullPointerException.class); - - underTest.addToQueue(null); + assertThatThrownBy(() -> underTest.addToQueue(null)) + .isInstanceOf(NullPointerException.class); } @Test diff --git a/server/sonar-ce/src/test/java/org/sonar/ce/configuration/CeConfigurationImplTest.java b/server/sonar-ce/src/test/java/org/sonar/ce/configuration/CeConfigurationImplTest.java index 835ad9e8ad5..a2d1f1690bd 100644 --- a/server/sonar-ce/src/test/java/org/sonar/ce/configuration/CeConfigurationImplTest.java +++ b/server/sonar-ce/src/test/java/org/sonar/ce/configuration/CeConfigurationImplTest.java @@ -20,20 +20,17 @@ package org.sonar.ce.configuration; import java.util.Random; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.config.internal.ConfigurationBridge; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.utils.MessageException; import static java.lang.Math.abs; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class CeConfigurationImplTest { public static final ConfigurationBridge EMPTY_CONFIGURATION = new ConfigurationBridge(new MapSettings()); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private SimpleWorkerCountProvider workerCountProvider = new SimpleWorkerCountProvider(); @@ -67,9 +64,10 @@ public class CeConfigurationImplTest { public void constructor_throws_MessageException_when_WorkerCountProvider_returns_0() { workerCountProvider.set(0); - expectMessageException(0); - - new CeConfigurationImpl(EMPTY_CONFIGURATION, workerCountProvider); + assertThatThrownBy(() -> new CeConfigurationImpl(EMPTY_CONFIGURATION, workerCountProvider)) + .isInstanceOf(MessageException.class) + .hasMessage("Worker count '0' is invalid. " + + "It must be an integer strictly greater than 0 and less or equal to 10"); } @Test @@ -77,9 +75,10 @@ public class CeConfigurationImplTest { int value = -1 - abs(new Random().nextInt()); workerCountProvider.set(value); - expectMessageException(value); - - new CeConfigurationImpl(EMPTY_CONFIGURATION, workerCountProvider); + assertThatThrownBy(() -> new CeConfigurationImpl(EMPTY_CONFIGURATION, workerCountProvider)) + .isInstanceOf(MessageException.class) + .hasMessage("Worker count '" + value + "' is invalid. " + + "It must be an integer strictly greater than 0 and less or equal to 10"); } @Test @@ -87,15 +86,10 @@ public class CeConfigurationImplTest { int value = 10 + abs(new Random().nextInt()); workerCountProvider.set(value); - expectMessageException(value); - - new CeConfigurationImpl(EMPTY_CONFIGURATION, workerCountProvider); - } - - private void expectMessageException(int value) { - expectedException.expect(MessageException.class); - expectedException.expectMessage("Worker count '" + value + "' is invalid. " + - "It must be an integer strictly greater than 0 and less or equal to 10"); + assertThatThrownBy(() -> new CeConfigurationImpl(EMPTY_CONFIGURATION, workerCountProvider)) + .isInstanceOf(MessageException.class) + .hasMessage("Worker count '" + value + "' is invalid. " + + "It must be an integer strictly greater than 0 and less or equal to 10"); } @Test diff --git a/server/sonar-ce/src/test/java/org/sonar/ce/httpd/CeHttpServerTest.java b/server/sonar-ce/src/test/java/org/sonar/ce/httpd/CeHttpServerTest.java index 0328a55c09c..578972730d1 100644 --- a/server/sonar-ce/src/test/java/org/sonar/ce/httpd/CeHttpServerTest.java +++ b/server/sonar-ce/src/test/java/org/sonar/ce/httpd/CeHttpServerTest.java @@ -33,11 +33,11 @@ import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.sonar.process.sharedmemoryfile.DefaultProcessCommands; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.process.ProcessEntryPoint.PROPERTY_PROCESS_INDEX; import static org.sonar.process.ProcessEntryPoint.PROPERTY_SHARED_PATH; @@ -45,8 +45,6 @@ public class CeHttpServerTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private static final RuntimeException FAILING_ACTION = new IllegalStateException("Simulating the action failed"); private CeHttpServer underTest; @@ -110,8 +108,9 @@ public class CeHttpServerTest { @Test public void stop_stops_http_server() throws Exception { underTest.stop(); - expectedException.expect(ConnectException.class); - call(underTest.getUrl()); + + assertThatThrownBy(() -> call(underTest.getUrl())) + .isInstanceOf(ConnectException.class); } @Test diff --git a/server/sonar-ce/src/test/java/org/sonar/ce/logging/CeProcessLoggingTest.java b/server/sonar-ce/src/test/java/org/sonar/ce/logging/CeProcessLoggingTest.java index b38b976d4be..0181b49e1fb 100644 --- a/server/sonar-ce/src/test/java/org/sonar/ce/logging/CeProcessLoggingTest.java +++ b/server/sonar-ce/src/test/java/org/sonar/ce/logging/CeProcessLoggingTest.java @@ -35,13 +35,13 @@ import org.junit.AfterClass; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.sonar.process.Props; import org.sonar.process.logging.LogbackHelper; import org.sonar.process.logging.PatternLayoutEncoder; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.slf4j.Logger.ROOT_LOGGER_NAME; import static org.sonar.process.ProcessProperties.Property.PATH_LOGS; @@ -49,8 +49,6 @@ public class CeProcessLoggingTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private File logDir; private Props props = new Props(new Properties()); @@ -356,50 +354,45 @@ public class CeProcessLoggingTest { public void fail_with_IAE_if_global_property_unsupported_level() { props.set("sonar.log.level", "ERROR"); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("log level ERROR in property sonar.log.level is not a supported value (allowed levels are [TRACE, DEBUG, INFO])"); - - underTest.configure(props); + assertThatThrownBy(() -> underTest.configure(props)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("log level ERROR in property sonar.log.level is not a supported value (allowed levels are [TRACE, DEBUG, INFO])"); } @Test public void fail_with_IAE_if_ce_property_unsupported_level() { props.set("sonar.log.level.ce", "ERROR"); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("log level ERROR in property sonar.log.level.ce is not a supported value (allowed levels are [TRACE, DEBUG, INFO])"); - - underTest.configure(props); + assertThatThrownBy(() -> underTest.configure(props)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("log level ERROR in property sonar.log.level.ce is not a supported value (allowed levels are [TRACE, DEBUG, INFO])"); } @Test public void fail_with_IAE_if_ce_sql_property_unsupported_level() { props.set("sonar.log.level.ce.sql", "ERROR"); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("log level ERROR in property sonar.log.level.ce.sql is not a supported value (allowed levels are [TRACE, DEBUG, INFO])"); - - underTest.configure(props); + assertThatThrownBy(() -> underTest.configure(props)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("log level ERROR in property sonar.log.level.ce.sql is not a supported value (allowed levels are [TRACE, DEBUG, INFO])"); } @Test public void fail_with_IAE_if_ce_es_property_unsupported_level() { props.set("sonar.log.level.ce.es", "ERROR"); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("log level ERROR in property sonar.log.level.ce.es is not a supported value (allowed levels are [TRACE, DEBUG, INFO])"); - - underTest.configure(props); + assertThatThrownBy(() -> underTest.configure(props)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("log level ERROR in property sonar.log.level.ce.es is not a supported value (allowed levels are [TRACE, DEBUG, INFO])"); } @Test public void fail_with_IAE_if_ce_jmx_property_unsupported_level() { props.set("sonar.log.level.ce.jmx", "ERROR"); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("log level ERROR in property sonar.log.level.ce.jmx is not a supported value (allowed levels are [TRACE, DEBUG, INFO])"); - - underTest.configure(props); + assertThatThrownBy(() -> underTest.configure(props)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("log level ERROR in property sonar.log.level.ce.jmx is not a supported value (allowed levels are [TRACE, DEBUG, INFO])"); } @Test diff --git a/server/sonar-ce/src/test/java/org/sonar/ce/monitoring/CommonCEQueueStatusImplTest.java b/server/sonar-ce/src/test/java/org/sonar/ce/monitoring/CommonCEQueueStatusImplTest.java index 7a13cc22ace..e8680d4bddf 100644 --- a/server/sonar-ce/src/test/java/org/sonar/ce/monitoring/CommonCEQueueStatusImplTest.java +++ b/server/sonar-ce/src/test/java/org/sonar/ce/monitoring/CommonCEQueueStatusImplTest.java @@ -21,13 +21,12 @@ package org.sonar.ce.monitoring; import java.util.Optional; import java.util.Random; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.db.DbClient; import org.sonar.server.property.InternalProperties; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; @@ -35,10 +34,6 @@ import static org.mockito.Mockito.when; public abstract class CommonCEQueueStatusImplTest { private static final int SOME_RANDOM_MAX = 96535; private static final int SOME_PROCESSING_TIME = 8723; - - @Rule - public ExpectedException expectedException = ExpectedException.none(); - private DbClient dbClient; protected CommonCEQueueStatusImplTest(DbClient dbClient) { @@ -82,10 +77,9 @@ public abstract class CommonCEQueueStatusImplTest { @Test public void addError_throws_IAE_if_time_is_less_than_0() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Processing time can not be < 0"); - - getUnderTest().addError(-1); + assertThatThrownBy(() -> getUnderTest().addError(-1)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Processing time can not be < 0"); } @Test @@ -112,10 +106,9 @@ public abstract class CommonCEQueueStatusImplTest { @Test public void addSuccess_throws_IAE_if_time_is_less_than_0() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Processing time can not be < 0"); - - getUnderTest().addSuccess(-1); + assertThatThrownBy(() -> getUnderTest().addSuccess(-1)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Processing time can not be < 0"); } @Test diff --git a/server/sonar-ce/src/test/java/org/sonar/ce/notification/ReportAnalysisFailureNotificationExecutionListenerTest.java b/server/sonar-ce/src/test/java/org/sonar/ce/notification/ReportAnalysisFailureNotificationExecutionListenerTest.java index 33eb2019a33..306f5691080 100644 --- a/server/sonar-ce/src/test/java/org/sonar/ce/notification/ReportAnalysisFailureNotificationExecutionListenerTest.java +++ b/server/sonar-ce/src/test/java/org/sonar/ce/notification/ReportAnalysisFailureNotificationExecutionListenerTest.java @@ -28,7 +28,6 @@ import javax.annotation.Nullable; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; import org.sonar.api.notifications.Notification; import org.sonar.api.utils.System2; @@ -50,6 +49,7 @@ import org.sonar.server.notification.NotificationService; import static java.util.Collections.singleton; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.same; @@ -63,8 +63,6 @@ import static org.sonar.db.component.ComponentTesting.newModuleDto; public class ReportAnalysisFailureNotificationExecutionListenerTest { @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private final Random random = new Random(); private final DbClient dbClient = dbTester.getDbClient(); @@ -140,10 +138,9 @@ public class ReportAnalysisFailureNotificationExecutionListenerTest { when(notificationService.hasProjectSubscribersForTypes(componentUuid, singleton(ReportAnalysisFailureNotification.class))) .thenReturn(true); - expectedException.expect(RowNotFoundException.class); - expectedException.expectMessage("Component with uuid '" + componentUuid + "' not found"); - - underTest.onEnd(ceTaskMock, CeActivityDto.Status.FAILED, randomDuration(), ceTaskResultMock, throwableMock); + assertThatThrownBy(() -> underTest.onEnd(ceTaskMock, CeActivityDto.Status.FAILED, randomDuration(), ceTaskResultMock, throwableMock)) + .isInstanceOf(RowNotFoundException.class) + .hasMessage("Component with uuid '" + componentUuid + "' not found"); } @Test @@ -186,10 +183,9 @@ public class ReportAnalysisFailureNotificationExecutionListenerTest { .thenReturn(true); dbTester.components().insertPrivateProject(s -> s.setUuid(componentUuid)); - expectedException.expect(RowNotFoundException.class); - expectedException.expectMessage("CeActivity with uuid '" + taskUuid + "' not found"); - - underTest.onEnd(ceTaskMock, CeActivityDto.Status.FAILED, randomDuration(), ceTaskResultMock, throwableMock); + assertThatThrownBy(() -> underTest.onEnd(ceTaskMock, CeActivityDto.Status.FAILED, randomDuration(), ceTaskResultMock, throwableMock)) + .isInstanceOf(RowNotFoundException.class) + .hasMessage("CeActivity with uuid '" + taskUuid + "' not found"); } @Test diff --git a/server/sonar-ce/src/test/java/org/sonar/ce/platform/DatabaseCompatibilityTest.java b/server/sonar-ce/src/test/java/org/sonar/ce/platform/DatabaseCompatibilityTest.java index 7b1adab36cb..0e3d506f360 100644 --- a/server/sonar-ce/src/test/java/org/sonar/ce/platform/DatabaseCompatibilityTest.java +++ b/server/sonar-ce/src/test/java/org/sonar/ce/platform/DatabaseCompatibilityTest.java @@ -23,12 +23,11 @@ import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.Arrays; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.server.platform.db.migration.version.DatabaseVersion; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; @@ -39,8 +38,6 @@ import static org.sonar.server.platform.db.migration.version.DatabaseVersion.Sta @RunWith(DataProviderRunner.class) public class DatabaseCompatibilityTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private DatabaseVersion databaseVersion = mock(DatabaseVersion.class); private DatabaseCompatibility underTest = new DatabaseCompatibility(databaseVersion); @@ -50,10 +47,9 @@ public class DatabaseCompatibilityTest { public void start_throws_ISE_if_status_is_not_UP_TO_DATE_nor_FRESH_INSTALL(DatabaseVersion.Status status) { when(databaseVersion.getStatus()).thenReturn(status); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Compute Engine can't start unless Database is up to date"); - - underTest.start(); + assertThatThrownBy(() -> underTest.start()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Compute Engine can't start unless Database is up to date"); } @DataProvider diff --git a/server/sonar-ce/src/test/java/org/sonar/ce/queue/InternalCeQueueImplTest.java b/server/sonar-ce/src/test/java/org/sonar/ce/queue/InternalCeQueueImplTest.java index cd4f7368ebd..310533c50c4 100644 --- a/server/sonar-ce/src/test/java/org/sonar/ce/queue/InternalCeQueueImplTest.java +++ b/server/sonar-ce/src/test/java/org/sonar/ce/queue/InternalCeQueueImplTest.java @@ -28,7 +28,6 @@ import javax.annotation.Nullable; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.impl.utils.AlwaysIncreasingSystem2; import org.sonar.api.utils.System2; import org.sonar.ce.container.ComputeEngineStatus; @@ -52,6 +51,7 @@ import org.sonar.db.user.UserDto; import static java.util.Arrays.asList; import static java.util.Collections.emptyMap; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.fail; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.mock; @@ -69,8 +69,6 @@ public class InternalCeQueueImplTest { private System2 system2 = new AlwaysIncreasingSystem2(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester db = DbTester.create(system2); @@ -144,10 +142,9 @@ public class InternalCeQueueImplTest { @Test public void peek_throws_NPE_if_workerUUid_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("workerUuid can't be null"); - - underTest.peek(null, true); + assertThatThrownBy(() -> underTest.peek(null, true)) + .isInstanceOf(NullPointerException.class) + .hasMessage("workerUuid can't be null"); } @Test @@ -170,18 +167,16 @@ public class InternalCeQueueImplTest { @Test public void remove_throws_IAE_if_exception_is_provided_but_status_is_SUCCESS() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Error can be provided only when status is FAILED"); - - underTest.remove(mock(CeTask.class), CeActivityDto.Status.SUCCESS, null, new RuntimeException("Some error")); + assertThatThrownBy(() -> underTest.remove(mock(CeTask.class), CeActivityDto.Status.SUCCESS, null, new RuntimeException("Some error"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Error can be provided only when status is FAILED"); } @Test public void remove_throws_IAE_if_exception_is_provided_but_status_is_CANCELED() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Error can be provided only when status is FAILED"); - - underTest.remove(mock(CeTask.class), CeActivityDto.Status.CANCELED, null, new RuntimeException("Some error")); + assertThatThrownBy(() -> underTest.remove(mock(CeTask.class), CeActivityDto.Status.CANCELED, null, new RuntimeException("Some error"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Error can be provided only when status is FAILED"); } @Test @@ -326,9 +321,8 @@ public class InternalCeQueueImplTest { CeTask task = submit(CeTaskTypes.REPORT, newProjectDto("PROJECT_1")); underTest.remove(task, CeActivityDto.Status.SUCCESS, null, null); - expectedException.expect(IllegalStateException.class); - - underTest.remove(task, CeActivityDto.Status.SUCCESS, null, null); + assertThatThrownBy(() -> underTest.remove(task, CeActivityDto.Status.SUCCESS, null, null)) + .isInstanceOf(IllegalStateException.class); } @Test @@ -492,10 +486,9 @@ public class InternalCeQueueImplTest { underTest.peek(WORKER_UUID_2, true); CeQueueDto queueDto = db.getDbClient().ceQueueDao().selectByUuid(db.getSession(), task.getUuid()).get(); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Task is in progress and can't be canceled"); - - underTest.cancel(db.getSession(), queueDto); + assertThatThrownBy(() -> underTest.cancel(db.getSession(), queueDto)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Task is in progress and can't be canceled"); } @Test diff --git a/server/sonar-ce/src/test/java/org/sonar/ce/systeminfo/SystemInfoHttpActionTest.java b/server/sonar-ce/src/test/java/org/sonar/ce/systeminfo/SystemInfoHttpActionTest.java index a73c3f9b920..ff952940049 100644 --- a/server/sonar-ce/src/test/java/org/sonar/ce/systeminfo/SystemInfoHttpActionTest.java +++ b/server/sonar-ce/src/test/java/org/sonar/ce/systeminfo/SystemInfoHttpActionTest.java @@ -22,9 +22,7 @@ package org.sonar.ce.systeminfo; import fi.iki.elonen.NanoHTTPD; import java.util.Arrays; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.ce.httpd.HttpAction; import org.sonar.process.systeminfo.JvmStateSection; import org.sonar.process.systeminfo.SystemInfoSection; @@ -40,10 +38,6 @@ import static org.mockito.Mockito.verify; import static org.sonar.ce.httpd.CeHttpUtils.createHttpSession; public class SystemInfoHttpActionTest { - - @Rule - public ExpectedException expectedException = ExpectedException.none(); - private SystemInfoSection stateProvider1 = new JvmStateSection("state1"); private SystemInfoSection stateProvider2 = new JvmStateSection("state2"); private SystemInfoHttpAction underTest; diff --git a/server/sonar-ce/src/test/java/org/sonar/ce/taskprocessor/CeTaskInterrupterProviderTest.java b/server/sonar-ce/src/test/java/org/sonar/ce/taskprocessor/CeTaskInterrupterProviderTest.java index 5f116dd14c4..4666c710230 100644 --- a/server/sonar-ce/src/test/java/org/sonar/ce/taskprocessor/CeTaskInterrupterProviderTest.java +++ b/server/sonar-ce/src/test/java/org/sonar/ce/taskprocessor/CeTaskInterrupterProviderTest.java @@ -21,19 +21,16 @@ package org.sonar.ce.taskprocessor; import java.lang.reflect.Field; import java.util.Random; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.utils.System2; import org.sonar.ce.task.CeTaskInterrupter; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; public class CeTaskInterrupterProviderTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private MapSettings settings = new MapSettings(); private CeWorkerController ceWorkerController = mock(CeWorkerController.class); @@ -79,20 +76,18 @@ public class CeTaskInterrupterProviderTest { public void provide_fails_with_ISE_if_property_is_not_a_long() { settings.setProperty("sonar.ce.task.timeoutSeconds", "foo"); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("The property 'sonar.ce.task.timeoutSeconds' is not an long value: For input string: \"foo\""); - - underTest.provide(settings.asConfig(), ceWorkerController, system2); + assertThatThrownBy(() -> underTest.provide(settings.asConfig(), ceWorkerController, system2)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("The property 'sonar.ce.task.timeoutSeconds' is not an long value: For input string: \"foo\""); } @Test public void provide_fails_with_ISE_if_property_is_zero() { settings.setProperty("sonar.ce.task.timeoutSeconds", "0"); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("The property 'sonar.ce.task.timeoutSeconds' must be a long value >= 1. Got '0'"); - - underTest.provide(settings.asConfig(), ceWorkerController, system2); + assertThatThrownBy(() -> underTest.provide(settings.asConfig(), ceWorkerController, system2)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("The property 'sonar.ce.task.timeoutSeconds' must be a long value >= 1. Got '0'"); } @Test @@ -100,10 +95,9 @@ public class CeTaskInterrupterProviderTest { int negativeValue = -(1 + new Random().nextInt(1_212)); settings.setProperty("sonar.ce.task.timeoutSeconds", negativeValue); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("The property 'sonar.ce.task.timeoutSeconds' must be a long value >= 1. Got '" + negativeValue + "'"); - - underTest.provide(settings.asConfig(), ceWorkerController, system2); + assertThatThrownBy(() -> underTest.provide(settings.asConfig(), ceWorkerController, system2)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("The property 'sonar.ce.task.timeoutSeconds' must be a long value >= 1. Got '" + negativeValue + "'"); } @Test diff --git a/server/sonar-ce/src/test/java/org/sonar/ce/taskprocessor/CeTaskInterrupterWorkerExecutionListenerTest.java b/server/sonar-ce/src/test/java/org/sonar/ce/taskprocessor/CeTaskInterrupterWorkerExecutionListenerTest.java index 0a649e06026..3566ea4e7a2 100644 --- a/server/sonar-ce/src/test/java/org/sonar/ce/taskprocessor/CeTaskInterrupterWorkerExecutionListenerTest.java +++ b/server/sonar-ce/src/test/java/org/sonar/ce/taskprocessor/CeTaskInterrupterWorkerExecutionListenerTest.java @@ -34,8 +34,6 @@ import static org.mockito.Mockito.verify; public class CeTaskInterrupterWorkerExecutionListenerTest { private CeTaskInterrupter ceTaskInterrupter = mock(CeTaskInterrupter.class); private CeTaskInterrupterWorkerExecutionListener underTest = new CeTaskInterrupterWorkerExecutionListener(ceTaskInterrupter); - - @Test public void onStart_delegates_to_ceTaskInterrupter_onStart() { CeTask ceTask = mock(CeTask.class); diff --git a/server/sonar-ce/src/test/java/org/sonar/ce/taskprocessor/CeTaskProcessorModuleTest.java b/server/sonar-ce/src/test/java/org/sonar/ce/taskprocessor/CeTaskProcessorModuleTest.java index 14bced24758..cec10979a47 100644 --- a/server/sonar-ce/src/test/java/org/sonar/ce/taskprocessor/CeTaskProcessorModuleTest.java +++ b/server/sonar-ce/src/test/java/org/sonar/ce/taskprocessor/CeTaskProcessorModuleTest.java @@ -59,8 +59,6 @@ public class CeTaskProcessorModuleTest { ComponentContainer container = new ComponentContainer(); underTest.configure(container); - - assertThat(container.getPicoContainer().getComponentAdapter(CeTaskInterrupter.class)) .isInstanceOf(CeTaskInterrupterProvider.class); } diff --git a/server/sonar-ce/src/test/java/org/sonar/ce/taskprocessor/CeTaskProcessorRepositoryImplTest.java b/server/sonar-ce/src/test/java/org/sonar/ce/taskprocessor/CeTaskProcessorRepositoryImplTest.java index ec742c0c08d..4f76663b6d8 100644 --- a/server/sonar-ce/src/test/java/org/sonar/ce/taskprocessor/CeTaskProcessorRepositoryImplTest.java +++ b/server/sonar-ce/src/test/java/org/sonar/ce/taskprocessor/CeTaskProcessorRepositoryImplTest.java @@ -21,22 +21,17 @@ package org.sonar.ce.taskprocessor; import com.google.common.collect.ImmutableSet; import java.util.Set; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.ce.task.CeTask; import org.sonar.ce.task.CeTaskResult; import org.sonar.ce.task.taskprocessor.CeTaskProcessor; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class CeTaskProcessorRepositoryImplTest { private static final String SOME_CE_TASK_TYPE = "some type"; private static final String SOME_COMPONENT_KEY = "key"; - - @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Test public void constructor_accepts_empty_array_argument() { new CeTaskProcessorRepositoryImpl(new CeTaskProcessor[] {}); @@ -44,28 +39,30 @@ public class CeTaskProcessorRepositoryImplTest { @Test public void constructor_throws_IAE_if_two_TaskProcessor_handle_the_same_CeTask_type() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage( - "There can be only one CeTaskProcessor instance registered as the processor for CeTask type " + SOME_CE_TASK_TYPE + ". " + - "More than one found. Please fix your configuration: " + SomeProcessor1.class.getName() + ", " + SomeProcessor2.class.getName()); - - new CeTaskProcessorRepositoryImpl(new CeTaskProcessor[] { - new SomeProcessor1(SOME_CE_TASK_TYPE), - new SomeProcessor2(SOME_CE_TASK_TYPE) - }); + assertThatThrownBy(() -> { + new CeTaskProcessorRepositoryImpl(new CeTaskProcessor[] { + new SomeProcessor1(SOME_CE_TASK_TYPE), + new SomeProcessor2(SOME_CE_TASK_TYPE) + }); + }).isInstanceOf(IllegalArgumentException.class) + .hasMessage( + "There can be only one CeTaskProcessor instance registered as the processor for CeTask type " + SOME_CE_TASK_TYPE + ". " + + "More than one found. Please fix your configuration: " + SomeProcessor1.class.getName() + ", " + SomeProcessor2.class.getName() + ); } @Test public void constructor_throws_IAE_if_multiple_TaskProcessor_overlap_their_supported_CeTask_type() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage( - "There can be only one CeTaskProcessor instance registered as the processor for CeTask type " + SOME_CE_TASK_TYPE + ". " + - "More than one found. Please fix your configuration: " + SomeProcessor1.class.getName() + ", " + SomeProcessor2.class.getName()); - - new CeTaskProcessorRepositoryImpl(new CeTaskProcessor[] { - new SomeProcessor2(SOME_CE_TASK_TYPE + "_2", SOME_CE_TASK_TYPE), - new SomeProcessor1(SOME_CE_TASK_TYPE, SOME_CE_TASK_TYPE + "_3") - }); + assertThatThrownBy(() -> { + new CeTaskProcessorRepositoryImpl(new CeTaskProcessor[] { + new SomeProcessor2(SOME_CE_TASK_TYPE + "_2", SOME_CE_TASK_TYPE), + new SomeProcessor1(SOME_CE_TASK_TYPE, SOME_CE_TASK_TYPE + "_3") + }); + }).isInstanceOf(IllegalArgumentException.class) + .hasMessage( + "There can be only one CeTaskProcessor instance registered as the processor for CeTask type " + SOME_CE_TASK_TYPE + ". " + + "More than one found. Please fix your configuration: " + SomeProcessor1.class.getName() + ", " + SomeProcessor2.class.getName() + ); } @Test diff --git a/server/sonar-ce/src/test/java/org/sonar/ce/taskprocessor/CeWorkerImplTest.java b/server/sonar-ce/src/test/java/org/sonar/ce/taskprocessor/CeWorkerImplTest.java index 60a3253ef4b..7e67d9d50ff 100644 --- a/server/sonar-ce/src/test/java/org/sonar/ce/taskprocessor/CeWorkerImplTest.java +++ b/server/sonar-ce/src/test/java/org/sonar/ce/taskprocessor/CeWorkerImplTest.java @@ -33,7 +33,6 @@ import javax.annotation.Nullable; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; import org.mockito.InOrder; import org.mockito.stubbing.Answer; @@ -57,6 +56,7 @@ import org.sonar.db.user.UserTesting; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyString; @@ -84,8 +84,6 @@ public class CeWorkerImplTest { @Rule public LogTester logTester = new LogTester(); @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Rule public DbTester db = DbTester.create(system2); private DbSession session = db.getSession(); @@ -111,10 +109,9 @@ public class CeWorkerImplTest { @Test public void constructor_throws_IAE_if_ordinal_is_less_than_zero() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Ordinal must be >= 0"); - - new CeWorkerImpl(-1 - new Random().nextInt(20), workerUuid, queue, taskProcessorRepository, ceWorkerController); + assertThatThrownBy(() -> new CeWorkerImpl(-1 - new Random().nextInt(20), workerUuid, queue, taskProcessorRepository, ceWorkerController)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Ordinal must be >= 0"); } @Test diff --git a/server/sonar-ce/src/test/java/org/sonar/ce/taskprocessor/SimpleCeTaskInterrupterTest.java b/server/sonar-ce/src/test/java/org/sonar/ce/taskprocessor/SimpleCeTaskInterrupterTest.java index 8163c5e26ad..5bf19053da9 100644 --- a/server/sonar-ce/src/test/java/org/sonar/ce/taskprocessor/SimpleCeTaskInterrupterTest.java +++ b/server/sonar-ce/src/test/java/org/sonar/ce/taskprocessor/SimpleCeTaskInterrupterTest.java @@ -19,19 +19,16 @@ */ package org.sonar.ce.taskprocessor; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.ce.task.CeTask; import org.sonar.ce.task.CeTaskCanceledException; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyZeroInteractions; public class SimpleCeTaskInterrupterTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private SimpleCeTaskInterrupter underTest = new SimpleCeTaskInterrupter(); @@ -48,10 +45,9 @@ public class SimpleCeTaskInterrupterTest { t.interrupt(); - expectedException.expect(CeTaskCanceledException.class); - expectedException.expectMessage("CeWorker executing in Thread '" + threadName + "' has been interrupted"); - - underTest.check(t); + assertThatThrownBy(() -> underTest.check(t)) + .isInstanceOf(CeTaskCanceledException.class) + .hasMessage("CeWorker executing in Thread '" + threadName + "' has been interrupted"); } finally { t.kill(); t.join(1_000); diff --git a/server/sonar-ce/src/test/java/org/sonar/ce/taskprocessor/TimeoutCeTaskInterrupterTest.java b/server/sonar-ce/src/test/java/org/sonar/ce/taskprocessor/TimeoutCeTaskInterrupterTest.java index 782e8ee43ed..6e711b94931 100644 --- a/server/sonar-ce/src/test/java/org/sonar/ce/taskprocessor/TimeoutCeTaskInterrupterTest.java +++ b/server/sonar-ce/src/test/java/org/sonar/ce/taskprocessor/TimeoutCeTaskInterrupterTest.java @@ -23,7 +23,6 @@ import java.util.Optional; import java.util.Random; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.utils.System2; import org.sonar.api.utils.log.LogTester; import org.sonar.api.utils.log.LoggerLevel; @@ -33,12 +32,11 @@ import org.sonar.ce.task.CeTaskTimeoutException; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class TimeoutCeTaskInterrupterTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public LogTester logTester = new LogTester(); @@ -52,19 +50,18 @@ public class TimeoutCeTaskInterrupterTest { @Test public void constructor_fails_with_IAE_if_timeout_is_0() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("threshold must be >= 1"); - - new TimeoutCeTaskInterrupter(0, ceWorkerController, system2); + assertThatThrownBy(() -> new TimeoutCeTaskInterrupter(0, ceWorkerController, system2)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("threshold must be >= 1"); } @Test public void constructor_fails_with_IAE_if_timeout_is_less_than_0() { long timeout = - (1 + new Random().nextInt(299)); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("threshold must be >= 1"); - new TimeoutCeTaskInterrupter(timeout, ceWorkerController, system2); + assertThatThrownBy(() -> new TimeoutCeTaskInterrupter(timeout, ceWorkerController, system2)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("threshold must be >= 1"); } @Test @@ -82,10 +79,9 @@ public class TimeoutCeTaskInterrupterTest { public void check_fails_with_ISE_if_thread_is_not_running_a_CeWorker() { Thread t = newThreadWithRandomName(); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Could not find the CeTask being executed in thread '" + t.getName() + "'"); - - underTest.check(t); + assertThatThrownBy(() -> underTest.check(t)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Could not find the CeTask being executed in thread '" + t.getName() + "'"); } @Test @@ -93,10 +89,9 @@ public class TimeoutCeTaskInterrupterTest { Thread t = newThreadWithRandomName(); mockWorkerOnThread(t, ceWorker); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Could not find the CeTask being executed in thread '" + t.getName() + "'"); - - underTest.check(t); + assertThatThrownBy(() -> underTest.check(t)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Could not find the CeTask being executed in thread '" + t.getName() + "'"); } @Test @@ -107,10 +102,9 @@ public class TimeoutCeTaskInterrupterTest { mockWorkerWithTask(ceTask); when(ceTask.getUuid()).thenReturn(taskUuid); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("No start time recorded for task " + taskUuid); - - underTest.check(t); + assertThatThrownBy(() -> underTest.check(t)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("No start time recorded for task " + taskUuid); } @Test @@ -123,10 +117,9 @@ public class TimeoutCeTaskInterrupterTest { underTest.onStart(this.ceTask); underTest.onEnd(this.ceTask); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("No start time recorded for task " + taskUuid); - - underTest.check(t); + assertThatThrownBy(() -> underTest.check(t)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("No start time recorded for task " + taskUuid); } @Test @@ -145,10 +138,9 @@ public class TimeoutCeTaskInterrupterTest { t.interrupt(); - expectedException.expect(CeTaskCanceledException.class); - expectedException.expectMessage("CeWorker executing in Thread '" + threadName + "' has been interrupted"); - - underTest.check(t); + assertThatThrownBy(() -> underTest.check(t)) + .isInstanceOf(CeTaskCanceledException.class) + .hasMessage("CeWorker executing in Thread '" + threadName + "' has been interrupted"); } finally { t.kill(); t.join(1_000); @@ -172,10 +164,9 @@ public class TimeoutCeTaskInterrupterTest { int afterTimeoutOffset = new Random().nextInt(7_112); when(system2.now()).thenReturn(now + timeoutInMs + afterTimeoutOffset); - expectedException.expect(CeTaskTimeoutException.class); - expectedException.expectMessage("Execution of task timed out after " + (timeoutInMs + afterTimeoutOffset) + " ms"); - - underTest.check(thread); + assertThatThrownBy(() -> underTest.check(thread)) + .isInstanceOf(CeTaskTimeoutException.class) + .hasMessage("Execution of task timed out after " + (timeoutInMs + afterTimeoutOffset) + " ms"); } @Test @@ -196,10 +187,9 @@ public class TimeoutCeTaskInterrupterTest { int afterTimeoutOffset = new Random().nextInt(7_112); when(system2.now()).thenReturn(now + timeoutInMs + afterTimeoutOffset); - expectedException.expect(CeTaskCanceledException.class); - expectedException.expectMessage("CeWorker executing in Thread '" + threadName + "' has been interrupted"); - - underTest.check(t); + assertThatThrownBy(() -> underTest.check(t)) + .isInstanceOf(CeTaskCanceledException.class) + .hasMessage("CeWorker executing in Thread '" + threadName + "' has been interrupted"); } finally { t.kill(); t.join(1_000); diff --git a/server/sonar-db-core/src/test/java/org/sonar/db/DatabaseUtilsTest.java b/server/sonar-db-core/src/test/java/org/sonar/db/DatabaseUtilsTest.java index 1bf15ffb479..118518ab2e7 100644 --- a/server/sonar-db-core/src/test/java/org/sonar/db/DatabaseUtilsTest.java +++ b/server/sonar-db-core/src/test/java/org/sonar/db/DatabaseUtilsTest.java @@ -36,7 +36,6 @@ import java.util.Optional; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.utils.log.LogTester; import org.sonar.api.utils.log.LoggerLevel; import org.sonar.api.utils.log.Loggers; @@ -67,8 +66,6 @@ public class DatabaseUtilsTest { @Rule public CoreDbTester dbTester = CoreDbTester.createForSchema(DatabaseUtilsTest.class, "sql.sql", false); @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Rule public LogTester logTester = new LogTester(); @Test @@ -196,23 +193,20 @@ public class DatabaseUtilsTest { @Test public void toUniqueAndSortedList_throws_NPE_if_arg_is_null() { - expectedException.expect(NullPointerException.class); - - toUniqueAndSortedList(null); + assertThatThrownBy(() -> toUniqueAndSortedList(null)) + .isInstanceOf(NullPointerException.class); } @Test public void toUniqueAndSortedList_throws_NPE_if_arg_contains_a_null() { - expectedException.expect(NullPointerException.class); - - toUniqueAndSortedList(asList("A", null, "C")); + assertThatThrownBy(() -> toUniqueAndSortedList(asList("A", null, "C"))) + .isInstanceOf(NullPointerException.class); } @Test public void toUniqueAndSortedList_throws_NPE_if_arg_is_a_set_containing_a_null() { - expectedException.expect(NullPointerException.class); - - toUniqueAndSortedList(new HashSet<>(asList("A", null, "C"))); + assertThatThrownBy(() -> toUniqueAndSortedList(new HashSet<>(asList("A", null, "C")))) + .isInstanceOf(NullPointerException.class); } @Test @@ -536,9 +530,8 @@ public class DatabaseUtilsTest { @Test public void checkThatNotTooManyConditions_throws_IAE_if_strictly_more_than_1000_conditions() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("the message"); - - DatabaseUtils.checkThatNotTooManyConditions(Collections.nCopies(1_001, "foo"), "the message"); + assertThatThrownBy(() -> DatabaseUtils.checkThatNotTooManyConditions(Collections.nCopies(1_001, "foo"), "the message")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("the message"); } } diff --git a/server/sonar-db-core/src/test/java/org/sonar/db/DefaultDatabaseTest.java b/server/sonar-db-core/src/test/java/org/sonar/db/DefaultDatabaseTest.java index ba4c2a9083e..e19b90ce649 100644 --- a/server/sonar-db-core/src/test/java/org/sonar/db/DefaultDatabaseTest.java +++ b/server/sonar-db-core/src/test/java/org/sonar/db/DefaultDatabaseTest.java @@ -24,9 +24,7 @@ import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.Properties; import org.apache.commons.dbcp2.BasicDataSource; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.api.config.internal.MapSettings; import org.sonar.db.dialect.PostgreSql; @@ -34,7 +32,7 @@ import org.sonar.process.logging.LogbackHelper; import static org.apache.commons.lang.StringUtils.removeStart; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.rules.ExpectedException.none; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; @RunWith(DataProviderRunner.class) @@ -43,8 +41,6 @@ public class DefaultDatabaseTest { private LogbackHelper logbackHelper = mock(LogbackHelper.class); private static final String SONAR_JDBC = "sonar.jdbc."; - @Rule - public ExpectedException expectedException = none(); @Test public void shouldLoadDefaultValues() { @@ -92,10 +88,9 @@ public class DefaultDatabaseTest { props.setProperty(jdbcProperty, "100"); props.setProperty(dbcpProperty, "200"); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage(String.format("Duplicate property declaration for resolved jdbc key '%s': conflicting values are", removeStart(dbcpProperty, SONAR_JDBC))); - - DefaultDatabase.extractCommonsDbcpProperties(props); + assertThatThrownBy(() -> DefaultDatabase.extractCommonsDbcpProperties(props)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining(String.format("Duplicate property declaration for resolved jdbc key '%s': conflicting values are", removeStart(dbcpProperty, SONAR_JDBC))); } @Test diff --git a/server/sonar-db-core/src/test/java/org/sonar/db/dialect/DialectUtilsTest.java b/server/sonar-db-core/src/test/java/org/sonar/db/dialect/DialectUtilsTest.java index ceb0720b937..dc9e96a99a0 100644 --- a/server/sonar-db-core/src/test/java/org/sonar/db/dialect/DialectUtilsTest.java +++ b/server/sonar-db-core/src/test/java/org/sonar/db/dialect/DialectUtilsTest.java @@ -23,6 +23,7 @@ import org.junit.Test; import org.sonar.api.utils.MessageException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class DialectUtilsTest { @@ -38,8 +39,9 @@ public class DialectUtilsTest { assertThat(d).isInstanceOf(PostgreSql.class); } - @Test(expected = MessageException.class) + @Test public void testFindNoMatch() { - DialectUtils.find("foo", "bar"); + assertThatThrownBy(() -> DialectUtils.find("foo", "bar")) + .isInstanceOf(MessageException.class); } } diff --git a/server/sonar-db-core/src/test/java/org/sonar/db/dialect/MsSqlTest.java b/server/sonar-db-core/src/test/java/org/sonar/db/dialect/MsSqlTest.java index 0be74e0fcd3..b07dfd64c8e 100644 --- a/server/sonar-db-core/src/test/java/org/sonar/db/dialect/MsSqlTest.java +++ b/server/sonar-db-core/src/test/java/org/sonar/db/dialect/MsSqlTest.java @@ -21,20 +21,17 @@ package org.sonar.db.dialect; import java.sql.DatabaseMetaData; import java.sql.SQLException; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.Mockito; import org.sonar.api.utils.MessageException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class MsSqlTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private MsSql underTest = new MsSql(); @@ -76,11 +73,12 @@ public class MsSqlTest { @Test public void init_throws_MessageException_if_mssql_2012() throws Exception { - expectedException.expect(MessageException.class); - expectedException.expectMessage("Unsupported mssql version: 11.0. Minimal supported version is 12.0."); - - DatabaseMetaData metadata = newMetadata( 11, 0); - underTest.init(metadata); + assertThatThrownBy(() -> { + DatabaseMetaData metadata = newMetadata( 11, 0); + underTest.init(metadata); + }) + .isInstanceOf(MessageException.class) + .hasMessage("Unsupported mssql version: 11.0. Minimal supported version is 12.0."); } @Test diff --git a/server/sonar-db-core/src/test/java/org/sonar/db/dialect/PostgreSqlTest.java b/server/sonar-db-core/src/test/java/org/sonar/db/dialect/PostgreSqlTest.java index 15d44dea98d..cc76081db42 100644 --- a/server/sonar-db-core/src/test/java/org/sonar/db/dialect/PostgreSqlTest.java +++ b/server/sonar-db-core/src/test/java/org/sonar/db/dialect/PostgreSqlTest.java @@ -23,20 +23,18 @@ import java.sql.DatabaseMetaData; import java.sql.SQLException; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.Mockito; import org.sonar.api.utils.MessageException; import org.sonar.api.utils.log.LogTester; import org.sonar.api.utils.log.LoggerLevel; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class PostgreSqlTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public LogTester logs = new LogTester(); @@ -83,11 +81,12 @@ public class PostgreSqlTest { @Test public void postgresql_9_2_is_not_supported() throws Exception { - expectedException.expect(MessageException.class); - expectedException.expectMessage("Unsupported postgresql version: 9.2. Minimal supported version is 9.3."); - - DatabaseMetaData metadata = newMetadata( 9, 2); - underTest.init(metadata); + assertThatThrownBy(() -> { + DatabaseMetaData metadata = newMetadata( 9, 2); + underTest.init(metadata); + }) + .isInstanceOf(MessageException.class) + .hasMessage("Unsupported postgresql version: 9.2. Minimal supported version is 9.3."); } @Test @@ -113,18 +112,16 @@ public class PostgreSqlTest { DatabaseMetaData metaData = newMetadata(9, 5); underTest.init(metaData); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("onInit() must be called once"); - - underTest.init(metaData); + assertThatThrownBy(() -> underTest.init(metaData)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("onInit() must be called once"); } @Test public void supportsUpsert_throws_ISE_if_not_initialized() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("onInit() must be called before calling supportsUpsert()"); - - underTest.supportsUpsert(); + assertThatThrownBy(() -> underTest.supportsUpsert()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("onInit() must be called before calling supportsUpsert()"); } private DatabaseMetaData newMetadata(int dbMajorVersion, int dbMinorVersion) throws SQLException { diff --git a/server/sonar-db-core/src/test/java/org/sonar/db/profiling/InvocationUtilsTest.java b/server/sonar-db-core/src/test/java/org/sonar/db/profiling/InvocationUtilsTest.java index 8dde440fc90..02d19d4b409 100644 --- a/server/sonar-db-core/src/test/java/org/sonar/db/profiling/InvocationUtilsTest.java +++ b/server/sonar-db-core/src/test/java/org/sonar/db/profiling/InvocationUtilsTest.java @@ -27,7 +27,6 @@ import org.junit.Test; import org.sonar.test.TestUtils; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/DaoModuleTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/DaoModuleTest.java index 8a1d5373da4..373b9439baa 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/DaoModuleTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/DaoModuleTest.java @@ -23,7 +23,6 @@ import org.junit.Test; import org.sonar.core.platform.ComponentContainer; import static org.assertj.core.api.Assertions.assertThat; -import static org.sonar.core.platform.ComponentContainer.COMPONENTS_IN_EMPTY_COMPONENT_CONTAINER; public class DaoModuleTest { @Test diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/DaoUtilsTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/DaoUtilsTest.java index 5ac9660c492..2ae748dc784 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/DaoUtilsTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/DaoUtilsTest.java @@ -38,6 +38,4 @@ public class DaoUtilsTest { assertThat(buildLikeValue("like-\\_%/-value", AFTER)).isEqualTo(escapedValue + wildcard); assertThat(buildLikeValue("like-\\_%/-value", BEFORE_AND_AFTER)).isEqualTo(wildcard + escapedValue + wildcard); } - - } diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/IsAliveMapperTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/IsAliveMapperTest.java index 3879edaafa0..84085a5ed1a 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/IsAliveMapperTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/IsAliveMapperTest.java @@ -26,8 +26,6 @@ import org.junit.Test; import org.sonar.api.utils.System2; import static org.assertj.core.api.Assertions.assertThat; - - public class IsAliveMapperTest { @Rule diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/PaginationTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/PaginationTest.java index 00e39446bed..aaf90cbc676 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/PaginationTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/PaginationTest.java @@ -20,17 +20,12 @@ package org.sonar.db; import java.util.Random; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.db.Pagination.forPage; - - public class PaginationTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void all_is_page_1_with_MAX_INTEGER_page_size() { @@ -47,38 +42,34 @@ public class PaginationTest { @Test public void forPage_fails_with_IAE_if_page_is_0() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("page index must be >= 1"); - - forPage(0); + assertThatThrownBy(() -> forPage(0)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("page index must be >= 1"); } @Test public void forPage_fails_with_IAE_if_page_is_less_than_0() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("page index must be >= 1"); - - forPage(-Math.abs(new Random().nextInt()) - 1); + assertThatThrownBy(() -> forPage(-Math.abs(new Random().nextInt()) - 1)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("page index must be >= 1"); } @Test public void andSize_fails_with_IAE_if_size_is_0() { Pagination.Builder builder = forPage(1); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("page size must be >= 1"); - - builder.andSize(0); + assertThatThrownBy(() -> builder.andSize(0)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("page size must be >= 1"); } @Test public void andSize_fails_with_IAE_if_size_is_less_than_0() { Pagination.Builder builder = forPage(1); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("page size must be >= 1"); - - builder.andSize(-Math.abs(new Random().nextInt()) - 1); + assertThatThrownBy(() -> builder.andSize(-Math.abs(new Random().nextInt()) - 1)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("page size must be >= 1"); } @Test diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/alm/setting/ProjectAlmSettingDaoWithPersisterTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/alm/setting/ProjectAlmSettingDaoWithPersisterTest.java index e1ce9095f12..3a111a8e2b1 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/alm/setting/ProjectAlmSettingDaoWithPersisterTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/alm/setting/ProjectAlmSettingDaoWithPersisterTest.java @@ -36,9 +36,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.when; import static org.sonar.db.almsettings.AlmSettingsTesting.newGithubAlmSettingDto; import static org.sonar.db.almsettings.AlmSettingsTesting.newGithubProjectAlmSettingDto; diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/ce/CeActivityDtoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/ce/CeActivityDtoTest.java index 1e25770c33f..1e27e37d998 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/ce/CeActivityDtoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/ce/CeActivityDtoTest.java @@ -23,21 +23,16 @@ import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.Random; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; @RunWith(DataProviderRunner.class) public class CeActivityDtoTest { private static final String STR_40_CHARS = "0123456789012345678901234567890123456789"; - - @Rule - public ExpectedException expectedException = ExpectedException.none(); - private CeActivityDto underTest = new CeActivityDto(); @Test @@ -82,10 +77,9 @@ public class CeActivityDtoTest { public void setComponentUuid_throws_IAE_if_value_is_41_chars() { String str_41_chars = STR_40_CHARS + "a"; - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Value is too long for column CE_ACTIVITY.COMPONENT_UUID: " + str_41_chars); - - underTest.setComponentUuid(str_41_chars); + assertThatThrownBy(() -> underTest.setComponentUuid(str_41_chars)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Value is too long for column CE_ACTIVITY.COMPONENT_UUID: " + str_41_chars); } @Test @@ -100,10 +94,9 @@ public class CeActivityDtoTest { public void setMainComponentUuid_throws_IAE_if_value_is_41_chars() { String str_41_chars = STR_40_CHARS + "a"; - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Value is too long for column CE_ACTIVITY.MAIN_COMPONENT_UUID: " + str_41_chars); - - underTest.setMainComponentUuid(str_41_chars); + assertThatThrownBy(() -> underTest.setMainComponentUuid(str_41_chars)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Value is too long for column CE_ACTIVITY.MAIN_COMPONENT_UUID: " + str_41_chars); } @Test @@ -137,9 +130,8 @@ public class CeActivityDtoTest { underTest.setWarningCount(0); underTest.setWarningCount(1 + new Random().nextInt(10)); - expectedException.expect(IllegalArgumentException.class); - - underTest.setWarningCount(-1 - new Random().nextInt(10)); + assertThatThrownBy(() -> underTest.setWarningCount(-1 - new Random().nextInt(10))) + .isInstanceOf(IllegalArgumentException.class); } @DataProvider diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/ce/CeQueueDtoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/ce/CeQueueDtoTest.java index 678660e30a1..66ffd7de5b9 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/ce/CeQueueDtoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/ce/CeQueueDtoTest.java @@ -19,19 +19,15 @@ */ package org.sonar.db.ce; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class CeQueueDtoTest { private static final String STR_15_CHARS = "012345678901234"; private static final String STR_40_CHARS = "0123456789012345678901234567890123456789"; private static final String STR_255_CHARS = STR_40_CHARS + STR_40_CHARS + STR_40_CHARS + STR_40_CHARS + STR_40_CHARS + STR_40_CHARS + STR_15_CHARS; - - @Rule - public ExpectedException expectedException = ExpectedException.none(); - private CeQueueDto underTest = new CeQueueDto(); @Test @@ -46,10 +42,9 @@ public class CeQueueDtoTest { public void setComponentUuid_throws_IAE_if_value_is_41_chars() { String str_41_chars = STR_40_CHARS + "a"; - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Value is too long for column CE_QUEUE.COMPONENT_UUID: " + str_41_chars); - - underTest.setComponentUuid(str_41_chars); + assertThatThrownBy(() -> underTest.setComponentUuid(str_41_chars)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Value is too long for column CE_QUEUE.COMPONENT_UUID: " + str_41_chars); } @Test @@ -64,17 +59,15 @@ public class CeQueueDtoTest { public void setMainComponentUuid_throws_IAE_if_value_is_41_chars() { String str_41_chars = STR_40_CHARS + "a"; - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Value is too long for column CE_QUEUE.MAIN_COMPONENT_UUID: " + str_41_chars); - - underTest.setMainComponentUuid(str_41_chars); + assertThatThrownBy(() -> underTest.setMainComponentUuid(str_41_chars)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Value is too long for column CE_QUEUE.MAIN_COMPONENT_UUID: " + str_41_chars); } @Test public void setTaskType_throws_NPE_if_argument_is_null() { - expectedException.expect(NullPointerException.class); - - underTest.setTaskType(null); + assertThatThrownBy(() -> underTest.setTaskType(null)) + .isInstanceOf(NullPointerException.class); } @Test @@ -88,10 +81,9 @@ public class CeQueueDtoTest { public void setTaskType_throws_IAE_if_value_is_41_chars() { String str_16_chars = STR_15_CHARS + "a"; - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Value of task type is too long: " + str_16_chars); - - underTest.setTaskType(str_16_chars); + assertThatThrownBy(() -> underTest.setTaskType(str_16_chars)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Value of task type is too long: " + str_16_chars); } @Test @@ -106,9 +98,8 @@ public class CeQueueDtoTest { public void setSubmitterLogin_throws_IAE_if_value_is_41_chars() { String str_256_chars = STR_255_CHARS + "a"; - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Value of submitter uuid is too long: " + str_256_chars); - - underTest.setSubmitterUuid(str_256_chars); + assertThatThrownBy(() -> underTest.setSubmitterUuid(str_256_chars)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Value of submitter uuid is too long: " + str_256_chars); } } diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/ce/CeScannerContextDaoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/ce/CeScannerContextDaoTest.java index 7358d5751f3..c30fc96f0bd 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/ce/CeScannerContextDaoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/ce/CeScannerContextDaoTest.java @@ -22,7 +22,6 @@ package org.sonar.db.ce; import com.google.common.collect.ImmutableSet; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.utils.System2; import org.sonar.core.util.CloseableIterator; import org.sonar.db.DbSession; @@ -31,6 +30,7 @@ import org.sonar.db.DbTester; import static java.lang.System.lineSeparator; import static java.util.Collections.singleton; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; public class CeScannerContextDaoTest { @@ -40,8 +40,6 @@ public class CeScannerContextDaoTest { @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private System2 system = mock(System2.class); private DbSession dbSession = dbTester.getSession(); @@ -65,10 +63,9 @@ public class CeScannerContextDaoTest { @Test public void insert_fails_with_IAE_if_data_is_empty() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Scanner context can not be empty"); - - underTest.insert(dbSession, SOME_UUID, CloseableIterator.emptyCloseableIterator()); + assertThatThrownBy(() -> underTest.insert(dbSession, SOME_UUID, CloseableIterator.emptyCloseableIterator())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Scanner context can not be empty"); } @Test @@ -76,10 +73,9 @@ public class CeScannerContextDaoTest { CloseableIterator iterator = scannerContextInputStreamOf("aa"); iterator.next(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Scanner context can not be empty"); - - underTest.insert(dbSession, SOME_UUID, iterator); + assertThatThrownBy(() -> underTest.insert(dbSession, SOME_UUID, iterator)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Scanner context can not be empty"); } @Test @@ -89,10 +85,9 @@ public class CeScannerContextDaoTest { assertThat(dbTester.countRowsOfTable(dbSession, TABLE_NAME)).isEqualTo(1); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Fail to insert scanner context for task " + SOME_UUID); - - underTest.insert(dbSession, SOME_UUID, scannerContextInputStreamOf("blo")); + assertThatThrownBy(() -> underTest.insert(dbSession, SOME_UUID, scannerContextInputStreamOf("blo"))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Fail to insert scanner context for task " + SOME_UUID); } @Test diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/ce/CeTaskCharacteristicDaoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/ce/CeTaskCharacteristicDaoTest.java index a1b146f662a..7f24139d9d8 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/ce/CeTaskCharacteristicDaoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/ce/CeTaskCharacteristicDaoTest.java @@ -22,7 +22,6 @@ package org.sonar.db.ce; import com.google.common.collect.ImmutableSet; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.utils.System2; import org.sonar.db.DbTester; @@ -35,8 +34,6 @@ import static org.assertj.core.api.Assertions.tuple; public class CeTaskCharacteristicDaoTest { @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private CeTaskCharacteristicDao underTest = new CeTaskCharacteristicDao(); @@ -54,8 +51,6 @@ public class CeTaskCharacteristicDaoTest { tuple("task2", "uuid2", "key2", "value2")); assertThat(underTest.selectByTaskUuids(dbTester.getSession(), singletonList("unknown"))).isEmpty(); } - - @Test public void deleteByTaskUuids() { insert("key1", "value1", "uuid1", "task1"); diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/ce/CeTaskCharacteristicDtoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/ce/CeTaskCharacteristicDtoTest.java index 7190b7838be..9f4ab2a3da9 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/ce/CeTaskCharacteristicDtoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/ce/CeTaskCharacteristicDtoTest.java @@ -19,10 +19,10 @@ */ package org.sonar.db.ce; -import static org.assertj.core.api.Assertions.assertThat; - import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; + public class CeTaskCharacteristicDtoTest { @Test diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/ce/CeTaskInputDaoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/ce/CeTaskInputDaoTest.java index df597c593c3..6242cd1bf92 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/ce/CeTaskInputDaoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/ce/CeTaskInputDaoTest.java @@ -24,12 +24,12 @@ import java.util.Optional; import org.apache.commons.io.IOUtils; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.utils.System2; import org.sonar.db.DbTester; import static java.util.Collections.singleton; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -42,10 +42,6 @@ public class CeTaskInputDaoTest { @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); - - @Rule - public ExpectedException expectedException = ExpectedException.none(); - private System2 system = mock(System2.class); private CeTaskInputDao underTest = new CeTaskInputDao(system); @@ -67,8 +63,8 @@ public class CeTaskInputDaoTest { @Test public void fail_to_insert_invalid_row() { - expectedException.expectMessage("Fail to insert data of CE task null"); - underTest.insert(dbTester.getSession(), null, IOUtils.toInputStream(SOME_DATA)); + assertThatThrownBy(() -> underTest.insert(dbTester.getSession(), null, IOUtils.toInputStream(SOME_DATA))) + .hasMessage("Fail to insert data of CE task null"); } @Test diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/ce/CeTaskMessageDaoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/ce/CeTaskMessageDaoTest.java index 40e9de11bb6..2b325d49b12 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/ce/CeTaskMessageDaoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/ce/CeTaskMessageDaoTest.java @@ -24,7 +24,6 @@ import java.util.Optional; import org.assertj.core.groups.Tuple; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.utils.System2; import org.sonar.db.DbSession; import org.sonar.db.DbTester; @@ -37,8 +36,6 @@ import static org.assertj.core.api.Assertions.assertThat; public class CeTaskMessageDaoTest { @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private final CeTaskMessageDao underTest = new CeTaskMessageDao(); diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/ce/CeTaskMessageDtoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/ce/CeTaskMessageDtoTest.java index 75b1228c86b..07053cba552 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/ce/CeTaskMessageDtoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/ce/CeTaskMessageDtoTest.java @@ -20,33 +20,28 @@ package org.sonar.db.ce; import java.util.Random; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.apache.commons.lang.StringUtils.repeat; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class CeTaskMessageDtoTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private CeTaskMessageDto underTest = new CeTaskMessageDto(); @Test public void setMessage_fails_with_IAE_if_argument_is_null() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("message can't be null nor empty"); - - underTest.setMessage(null); + assertThatThrownBy(() -> underTest.setMessage(null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("message can't be null nor empty"); } @Test public void setMessage_fails_with_IAE_if_argument_is_empty() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("message can't be null nor empty"); - - underTest.setMessage(""); + assertThatThrownBy(() -> underTest.setMessage("")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("message can't be null nor empty"); } @Test @@ -61,9 +56,9 @@ public class CeTaskMessageDtoTest { public void setMessage_fails_with_IAE_if_argument_has_size_bigger_then_4000() { int size = 4000 + 1 + new Random().nextInt(100); String str = repeat("a", size); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("message is too long: " + size); - underTest.setMessage(str); + assertThatThrownBy(() -> underTest.setMessage(str)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("message is too long: " + size); } } diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/ce/LogsIteratorInputStreamTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/ce/LogsIteratorInputStreamTest.java index e97de96bf9e..85e7a8f1e5f 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/ce/LogsIteratorInputStreamTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/ce/LogsIteratorInputStreamTest.java @@ -22,17 +22,14 @@ package org.sonar.db.ce; import java.io.IOException; import java.util.Arrays; import org.apache.commons.io.IOUtils; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.core.util.CloseableIterator; import static java.nio.charset.StandardCharsets.UTF_8; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class LogsIteratorInputStreamTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void read_from_ClosableIterator_with_several_lines() throws IOException { @@ -57,10 +54,9 @@ public class LogsIteratorInputStreamTest { @Test public void constructor_throws_IAE_when_ClosableIterator_is_empty() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("LogsIterator can't be empty or already read"); - - create(); + assertThatThrownBy(LogsIteratorInputStreamTest::create) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("LogsIterator can't be empty or already read"); } @Test @@ -70,10 +66,9 @@ public class LogsIteratorInputStreamTest { // read iterator to the end iterator.next(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("LogsIterator can't be empty or already read"); - - new LogsIteratorInputStream(iterator, UTF_8); + assertThatThrownBy(() -> new LogsIteratorInputStream(iterator, UTF_8)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("LogsIterator can't be empty or already read"); } private static LogsIteratorInputStream create(String... lines) { diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/ce/UpdateIfTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/ce/UpdateIfTest.java index 9370364fc16..29d794367d7 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/ce/UpdateIfTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/ce/UpdateIfTest.java @@ -24,20 +24,15 @@ import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.Random; import org.apache.commons.lang.RandomStringUtils; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; @RunWith(DataProviderRunner.class) public class UpdateIfTest { private static final String STR_40_CHARS = "0123456789012345678901234567890123456789"; - - @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Test public void newProperties_constructor_accepts_null_workerUuid() { UpdateIf.NewProperties newProperties = new UpdateIf.NewProperties(CeQueueDto.Status.PENDING, null, 123, 456); @@ -47,20 +42,18 @@ public class UpdateIfTest { @Test public void newProperties_constructor_fails_with_NPE_if_status_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("status can't be null"); - - new UpdateIf.NewProperties(null, "foo", 123, 456); + assertThatThrownBy(() -> new UpdateIf.NewProperties(null, "foo", 123, 456)) + .isInstanceOf(NullPointerException.class) + .hasMessage("status can't be null"); } @Test public void newProperties_constructor_fails_with_IAE_if_workerUuid_is_41_or_more() { String workerUuid = RandomStringUtils.randomAlphanumeric(41 + new Random().nextInt(5)); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("worker uuid is too long: " + workerUuid); - - new UpdateIf.NewProperties(CeQueueDto.Status.PENDING, workerUuid, 123, 456); + assertThatThrownBy(() -> new UpdateIf.NewProperties(CeQueueDto.Status.PENDING, workerUuid, 123, 456)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("worker uuid is too long: " + workerUuid); } @Test @@ -83,9 +76,8 @@ public class UpdateIfTest { public void newProperties_constructor_IAE_if_workerUuid_is_41_chars() { String str_41_chars = STR_40_CHARS + "a"; - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("worker uuid is too long: " + str_41_chars); - - new UpdateIf.NewProperties(CeQueueDto.Status.PENDING, str_41_chars, 123, 345); + assertThatThrownBy(() -> new UpdateIf.NewProperties(CeQueueDto.Status.PENDING, str_41_chars, 123, 345)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("worker uuid is too long: " + str_41_chars); } } diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/component/AnalysisPropertiesDaoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/component/AnalysisPropertiesDaoTest.java index 090ecdddb84..f4278817184 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/component/AnalysisPropertiesDaoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/component/AnalysisPropertiesDaoTest.java @@ -25,7 +25,6 @@ import java.util.Random; import java.util.Set; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.impl.utils.TestSystem2; import org.sonar.api.utils.System2; import org.sonar.db.DbSession; @@ -34,6 +33,7 @@ import org.sonar.db.project.ProjectDto; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.AssertionsForClassTypes.tuple; public class AnalysisPropertiesDaoTest { @@ -41,8 +41,6 @@ public class AnalysisPropertiesDaoTest { @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private final System2 system2 = new TestSystem2().setNow(NOW); private final DbSession dbSession = dbTester.getSession(); @@ -56,10 +54,9 @@ public class AnalysisPropertiesDaoTest { .setKey(randomAlphanumeric(10)) .setValue(randomAlphanumeric(10)); - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("uuid cannot be null"); - - underTest.insert(dbSession, analysisPropertyDto); + assertThatThrownBy(() -> underTest.insert(dbSession, analysisPropertyDto)) + .isInstanceOf(NullPointerException.class) + .hasMessage("uuid cannot be null"); } @Test @@ -69,10 +66,9 @@ public class AnalysisPropertiesDaoTest { .setUuid(randomAlphanumeric(10)) .setValue(randomAlphanumeric(10)); - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("key cannot be null"); - - underTest.insert(dbSession, analysisPropertyDto); + assertThatThrownBy(() -> underTest.insert(dbSession, analysisPropertyDto)) + .isInstanceOf(NullPointerException.class) + .hasMessage("key cannot be null"); } @Test @@ -82,10 +78,9 @@ public class AnalysisPropertiesDaoTest { .setKey(randomAlphanumeric(10)) .setValue(randomAlphanumeric(10)); - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("analysis uuid cannot be null"); - - underTest.insert(dbSession, analysisPropertyDto); + assertThatThrownBy(() -> underTest.insert(dbSession, analysisPropertyDto)) + .isInstanceOf(NullPointerException.class) + .hasMessage("analysis uuid cannot be null"); } @Test @@ -95,10 +90,9 @@ public class AnalysisPropertiesDaoTest { .setUuid(randomAlphanumeric(10)) .setKey(randomAlphanumeric(10)); - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("value cannot be null"); - - underTest.insert(dbSession, analysisPropertyDto); + assertThatThrownBy(() -> underTest.insert(dbSession, analysisPropertyDto)) + .isInstanceOf(NullPointerException.class) + .hasMessage("value cannot be null"); } @Test diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/component/AnalysisPropertyDtoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/component/AnalysisPropertyDtoTest.java index 8c114996e23..aaa88f39dc5 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/component/AnalysisPropertyDtoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/component/AnalysisPropertyDtoTest.java @@ -19,17 +19,14 @@ */ package org.sonar.db.component; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class AnalysisPropertyDtoTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private AnalysisPropertyDto underTest; @@ -37,40 +34,36 @@ public class AnalysisPropertyDtoTest { public void null_key_should_throw_NPE() { underTest = new AnalysisPropertyDto(); - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("key cannot be null"); - - underTest.setKey(null); + assertThatThrownBy(() -> underTest.setKey(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("key cannot be null"); } @Test public void null_value_should_throw_NPE() { underTest = new AnalysisPropertyDto(); - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("value cannot be null"); - - underTest.setValue(null); + assertThatThrownBy(() -> underTest.setValue(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("value cannot be null"); } @Test public void null_uuid_should_throw_NPE() { underTest = new AnalysisPropertyDto(); - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("uuid cannot be null"); - - underTest.setUuid(null); + assertThatThrownBy(() -> underTest.setUuid(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("uuid cannot be null"); } @Test public void null_analysis_uuid_should_throw_NPE() { underTest = new AnalysisPropertyDto(); - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("analysisUuid cannot be null"); - - underTest.setAnalysisUuid(null); + assertThatThrownBy(() -> underTest.setAnalysisUuid(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("analysisUuid cannot be null"); } @Test diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/component/ComponentKeyUpdaterDaoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/component/ComponentKeyUpdaterDaoTest.java index 9ad34ab0e70..cf859283393 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/component/ComponentKeyUpdaterDaoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/component/ComponentKeyUpdaterDaoTest.java @@ -26,7 +26,6 @@ import java.util.function.Predicate; import org.assertj.core.groups.Tuple; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.resources.Qualifiers; import org.sonar.api.utils.System2; import org.sonar.db.DbClient; @@ -37,6 +36,7 @@ import org.sonar.db.audit.model.ComponentKeyNewValue; import org.sonar.db.component.ComponentKeyUpdaterDao.RekeyedResource; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; @@ -53,8 +53,6 @@ import static org.sonar.db.component.ComponentTesting.newPrivateProjectDto; public class ComponentKeyUpdaterDaoTest { - @Rule - public ExpectedException thrown = ExpectedException.none(); @Rule public DbTester db = DbTester.create(System2.INSTANCE); @@ -142,10 +140,9 @@ public class ComponentKeyUpdaterDaoTest { ComponentDto appBranch = db.components().insertProjectBranch(app); db.components().insertProjectBranch(app, b -> b.setKey("newName")); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage(String.format("Impossible to update key: a component with key \"%s\" already exists.", generateBranchKey(app.getDbKey(), "newName"))); - - underTest.updateApplicationBranchKey(dbSession, appBranch.uuid(), app.getDbKey(), "newName"); + assertThatThrownBy(() -> underTest.updateApplicationBranchKey(dbSession, appBranch.uuid(), app.getDbKey(), "newName")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage(String.format("Impossible to update key: a component with key \"%s\" already exists.", generateBranchKey(app.getDbKey(), "newName"))); } @Test @@ -222,10 +219,9 @@ public class ComponentKeyUpdaterDaoTest { public void updateKey_throws_IAE_if_component_with_specified_key_does_not_exist() { populateSomeData(); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Impossible to update key: a component with key \"org.struts:struts-ui\" already exists."); - - underTest.updateKey(dbSession, "B", "org.struts:struts-ui"); + assertThatThrownBy(() -> underTest.updateKey(dbSession, "B", "org.struts:struts-ui")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Impossible to update key: a component with key \"org.struts:struts-ui\" already exists."); } @Test @@ -234,10 +230,10 @@ public class ComponentKeyUpdaterDaoTest { db.components().insertComponent(project); db.components().insertComponent(newFileDto(project, null).setDbKey("old-project-key:file")); String newLongProjectKey = Strings.repeat("a", 400); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Component key length (405) is longer than the maximum authorized (400). '" + newLongProjectKey + ":file' was provided."); - underTest.updateKey(dbSession, project.uuid(), newLongProjectKey); + assertThatThrownBy(() -> underTest.updateKey(dbSession, project.uuid(), newLongProjectKey)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Component key length (405) is longer than the maximum authorized (400). '" + newLongProjectKey + ":file' was provided."); } @Test diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/component/ComponentQueryTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/component/ComponentQueryTest.java index 7645fae9aeb..3f2e3751a2f 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/component/ComponentQueryTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/component/ComponentQueryTest.java @@ -21,19 +21,16 @@ package org.sonar.db.component; import java.util.Date; import java.util.function.Supplier; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static java.util.Collections.emptySet; import static java.util.Collections.singleton; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.resources.Qualifiers.PROJECT; public class ComponentQueryTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void build_query() { @@ -87,17 +84,15 @@ public class ComponentQueryTest { @Test public void fail_if_no_qualifier_provided() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("At least one qualifier must be provided"); - - ComponentQuery.builder().build(); + assertThatThrownBy(() -> ComponentQuery.builder().build()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("At least one qualifier must be provided"); } @Test public void fail_if_partial_match_on_key_without_a_query() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("A query must be provided if a partial match on key is specified."); - - ComponentQuery.builder().setQualifiers(PROJECT).setPartialMatchOnKey(false).build(); + assertThatThrownBy(() -> ComponentQuery.builder().setQualifiers(PROJECT).setPartialMatchOnKey(false).build()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("A query must be provided if a partial match on key is specified."); } } diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/component/ComponentTreeQueryTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/component/ComponentTreeQueryTest.java index cf77524d231..0ce0cfe619e 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/component/ComponentTreeQueryTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/component/ComponentTreeQueryTest.java @@ -19,12 +19,11 @@ */ package org.sonar.db.component; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.db.component.ComponentTesting.newPrivateProjectDto; import static org.sonar.db.component.ComponentTreeQuery.Strategy.CHILDREN; import static org.sonar.db.component.ComponentTreeQuery.Strategy.LEAVES; @@ -33,8 +32,6 @@ public class ComponentTreeQueryTest { private static final String BASE_UUID = "ABCD"; - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void create_query() { @@ -77,17 +74,21 @@ public class ComponentTreeQueryTest { @Test public void fail_when_no_base_uuid() { - expectedException.expect(NullPointerException.class); - ComponentTreeQuery.builder() - .setStrategy(CHILDREN) - .build(); + assertThatThrownBy(() -> { + ComponentTreeQuery.builder() + .setStrategy(CHILDREN) + .build(); + }) + .isInstanceOf(NullPointerException.class); } @Test public void fail_when_no_strategy() { - expectedException.expect(NullPointerException.class); - ComponentTreeQuery.builder() - .setBaseUuid(BASE_UUID) - .build(); + assertThatThrownBy(() -> { + ComponentTreeQuery.builder() + .setBaseUuid(BASE_UUID) + .build(); + }) + .isInstanceOf(NullPointerException.class); } } diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/component/ComponentValidatorTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/component/ComponentValidatorTest.java index e5a623edea5..d76fa0e7bf3 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/component/ComponentValidatorTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/component/ComponentValidatorTest.java @@ -19,17 +19,14 @@ */ package org.sonar.db.component; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static com.google.common.base.Strings.repeat; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.test.TestUtils.hasOnlyPrivateConstructors; public class ComponentValidatorTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void check_name() { @@ -40,10 +37,9 @@ public class ComponentValidatorTest { @Test public void fail_when_name_longer_than_500_characters() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Component name length"); - - ComponentValidator.checkComponentName(repeat("a", 500 + 1)); + assertThatThrownBy(() -> ComponentValidator.checkComponentName(repeat("a", 500 + 1))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Component name length"); } @Test @@ -55,11 +51,12 @@ public class ComponentValidatorTest { @Test public void fail_when_key_longer_than_400_characters() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Component key length"); - String key = repeat("a", 400 + 1); - - ComponentValidator.checkComponentKey(key); + assertThatThrownBy(() -> { + String key = repeat("a", 400 + 1); + ComponentValidator.checkComponentKey(key); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Component key length"); } @Test @@ -71,10 +68,9 @@ public class ComponentValidatorTest { @Test public void fail_when_qualifier_is_longer_than_10_characters() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Component qualifier length"); - - ComponentValidator.checkComponentQualifier(repeat("a", 10 + 1)); + assertThatThrownBy(() -> ComponentValidator.checkComponentQualifier(repeat("a", 10 + 1))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Component qualifier length"); } @Test diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/component/ProjectLinkDaoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/component/ProjectLinkDaoTest.java index c12c927edd4..4a7c96e0c25 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/component/ProjectLinkDaoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/component/ProjectLinkDaoTest.java @@ -22,8 +22,8 @@ package org.sonar.db.component; import java.util.Collections; import org.junit.Rule; import org.junit.Test; -import org.sonar.api.utils.System2; import org.sonar.api.impl.utils.TestSystem2; +import org.sonar.api.utils.System2; import org.sonar.db.DbTester; import static java.util.Arrays.asList; diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/component/SnapshotDaoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/component/SnapshotDaoTest.java index ed402198582..7164082cff9 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/component/SnapshotDaoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/component/SnapshotDaoTest.java @@ -33,7 +33,6 @@ import java.util.stream.IntStream; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.api.utils.DateUtils; import org.sonar.api.utils.System2; @@ -65,8 +64,6 @@ import static org.sonar.db.component.SnapshotTesting.newAnalysis; @RunWith(DataProviderRunner.class) public class SnapshotDaoTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester db = DbTester.create(System2.INSTANCE); diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/component/SnapshotDtoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/component/SnapshotDtoTest.java index 931f10b88c3..b43f88f1bfa 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/component/SnapshotDtoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/component/SnapshotDtoTest.java @@ -19,18 +19,15 @@ */ package org.sonar.db.component; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.apache.commons.lang.StringUtils.repeat; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.utils.DateUtils.parseDate; public class SnapshotDtoTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void test_getter_and_setter() { @@ -61,12 +58,11 @@ public class SnapshotDtoTest { snapshotDto.setProjectVersion("1.0"); snapshotDto.setProjectVersion(repeat("a", 100)); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("projectVersion" + - " length (101) is longer than the maximum authorized (100). " + - "'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' was provided."); - - snapshotDto.setProjectVersion(repeat("a", 101)); + assertThatThrownBy(() -> snapshotDto.setProjectVersion(repeat("a", 101))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("projectVersion" + + " length (101) is longer than the maximum authorized (100). " + + "'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' was provided."); } @Test @@ -76,11 +72,10 @@ public class SnapshotDtoTest { snapshotDto.setBuildString("1.0"); snapshotDto.setBuildString(repeat("a", 100)); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("buildString" + - " length (101) is longer than the maximum authorized (100). " + - "'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' was provided."); - - snapshotDto.setBuildString(repeat("a", 101)); + assertThatThrownBy(() -> snapshotDto.setBuildString(repeat("a", 101))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("buildString" + + " length (101) is longer than the maximum authorized (100). " + + "'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' was provided."); } } diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/createdb/CreateDb.java b/server/sonar-db-dao/src/test/java/org/sonar/db/createdb/CreateDb.java index 546c3661b2b..4f01e75a540 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/createdb/CreateDb.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/createdb/CreateDb.java @@ -24,8 +24,8 @@ import com.sonar.orchestrator.db.DatabaseClient; import com.sonar.orchestrator.db.DatabaseFactory; import com.sonar.orchestrator.db.DefaultDatabase; import java.util.function.Consumer; -import org.sonar.api.config.internal.Settings; import org.sonar.api.config.internal.MapSettings; +import org.sonar.api.config.internal.Settings; import org.sonar.api.utils.log.Logger; import org.sonar.api.utils.log.Loggers; import org.sonar.db.SQDatabase; diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/event/EventComponentChangeDaoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/event/EventComponentChangeDaoTest.java index 2e6416aaee5..7392677ece5 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/event/EventComponentChangeDaoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/event/EventComponentChangeDaoTest.java @@ -25,7 +25,6 @@ import java.util.Random; import java.util.stream.IntStream; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.utils.System2; import org.sonar.db.DbSession; import org.sonar.db.DbTester; @@ -41,8 +40,6 @@ import static org.mockito.Mockito.when; public class EventComponentChangeDaoTest { private static Random random = new Random(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/event/EventDaoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/event/EventDaoTest.java index 309f44b9355..d31c7998f96 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/event/EventDaoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/event/EventDaoTest.java @@ -25,7 +25,6 @@ import java.util.Random; import java.util.stream.IntStream; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.utils.System2; import org.sonar.db.DbClient; import org.sonar.db.DbSession; @@ -42,8 +41,6 @@ import static org.sonar.db.event.EventTesting.newEvent; public class EventDaoTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/event/EventValidatorTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/event/EventValidatorTest.java index f626bfbdead..9b76be9becf 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/event/EventValidatorTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/event/EventValidatorTest.java @@ -19,15 +19,12 @@ */ package org.sonar.db.event; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static com.google.common.base.Strings.repeat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class EventValidatorTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void valid_cases() { @@ -41,25 +38,22 @@ public class EventValidatorTest { @Test public void fail_if_name_longer_than_400() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Event name length (401) is longer than the maximum authorized (400)."); - - EventValidator.checkEventName(repeat("a", 400 + 1)); + assertThatThrownBy(() -> EventValidator.checkEventName(repeat("a", 400 + 1))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Event name length (401) is longer than the maximum authorized (400)."); } @Test public void fail_if_category_longer_than_50() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Event category length (51) is longer than the maximum authorized (50). 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' was provided."); - - EventValidator.checkEventCategory(repeat("a", 50 + 1)); + assertThatThrownBy(() -> EventValidator.checkEventCategory(repeat("a", 50 + 1))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Event category length (51) is longer than the maximum authorized (50). 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' was provided."); } @Test public void fail_if_description_longer_than_4000() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Event description length (4001) is longer than the maximum authorized (4000)."); - - EventValidator.checkEventDescription(repeat("a", 4000 + 1)); + assertThatThrownBy(() -> EventValidator.checkEventDescription(repeat("a", 4000 + 1))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Event description length (4001) is longer than the maximum authorized (4000)."); } } diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/issue/IssueDaoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/issue/IssueDaoTest.java index 0ee427cdeca..d3ba10a6349 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/issue/IssueDaoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/issue/IssueDaoTest.java @@ -27,7 +27,6 @@ import java.util.Set; import java.util.stream.Stream; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.issue.Issue; import org.sonar.api.rule.RuleKey; import org.sonar.api.rules.RuleType; @@ -46,8 +45,8 @@ import static java.util.Arrays.asList; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.apache.commons.lang.math.RandomUtils.nextInt; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertFalse; -import static org.junit.rules.ExpectedException.none; import static org.sonar.db.component.ComponentTesting.newDirectory; import static org.sonar.db.component.ComponentTesting.newFileDto; import static org.sonar.db.component.ComponentTesting.newModuleDto; @@ -66,8 +65,6 @@ public class IssueDaoTest { .filter(r -> r != RuleType.SECURITY_HOTSPOT) .toArray(RuleType[]::new); - @Rule - public ExpectedException expectedException = none(); @Rule public DbTester db = DbTester.create(System2.INSTANCE); @@ -113,12 +110,12 @@ public class IssueDaoTest { @Test public void selectByKeyOrFail_fails_if_key_not_found() { - expectedException.expect(RowNotFoundException.class); - expectedException.expectMessage("Issue with key 'DOES_NOT_EXIST' does not exist"); - - prepareTables(); - - underTest.selectOrFailByKey(db.getSession(), "DOES_NOT_EXIST"); + assertThatThrownBy(() -> { + prepareTables(); + underTest.selectOrFailByKey(db.getSession(), "DOES_NOT_EXIST"); + }) + .isInstanceOf(RowNotFoundException.class) + .hasMessage("Issue with key 'DOES_NOT_EXIST' does not exist"); } @Test diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/issue/IssueDtoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/issue/IssueDtoTest.java index 2007e1b56c6..644f33d74f7 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/issue/IssueDtoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/issue/IssueDtoTest.java @@ -26,9 +26,7 @@ import java.util.Date; import java.util.List; import java.util.Set; import org.apache.commons.lang.time.DateUtils; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.issue.Issue; import org.sonar.api.rule.RuleKey; import org.sonar.api.rules.RuleType; @@ -37,22 +35,22 @@ import org.sonar.core.issue.DefaultIssue; import org.sonar.db.rule.RuleDefinitionDto; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class IssueDtoTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void set_data_check_maximal_length() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Value is too long for issue attributes:"); - - StringBuilder s = new StringBuilder(4500); - for (int i = 0; i < 4500; i++) { - s.append('a'); - } - new IssueDto().setIssueAttributes(s.toString()); + assertThatThrownBy(() -> { + StringBuilder s = new StringBuilder(4500); + for (int i = 0; i < 4500; i++) { + s.append('a'); + } + new IssueDto().setIssueAttributes(s.toString()); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Value is too long for issue attributes:"); } @Test diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/mapping/ProjectMappingsDaoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/mapping/ProjectMappingsDaoTest.java index a2f577bf0b3..c5ce8c525a4 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/mapping/ProjectMappingsDaoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/mapping/ProjectMappingsDaoTest.java @@ -24,15 +24,16 @@ import java.util.Objects; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.assertj.core.api.AbstractAssert; +import org.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.utils.System2; import org.sonar.core.util.SequenceUuidFactory; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -48,8 +49,6 @@ public class ProjectMappingsDaoTest { private System2 system2 = mock(System2.class); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester dbTester = DbTester.create(system2); @@ -59,37 +58,27 @@ public class ProjectMappingsDaoTest { @Test public void put_throws_IAE_if_key_type_is_null() { - expectKeyTypeNullOrEmptyIAE(); - - underTest.put(dbSession, null, A_KEY, PROJECT_UUID); + expectKeyTypeNullOrEmptyIAE(() -> underTest.put(dbSession, null, A_KEY, PROJECT_UUID)); } @Test public void put_throws_IAE_if_key_is_null() { - expectKeyNullOrEmptyIAE(); - - underTest.put(dbSession, A_KEY_TYPE, null, PROJECT_UUID); + expectKeyNullOrEmptyIAE(() -> underTest.put(dbSession, A_KEY_TYPE, null, PROJECT_UUID)); } @Test public void put_throws_IAE_if_key_is_empty() { - expectKeyNullOrEmptyIAE(); - - underTest.put(dbSession, A_KEY_TYPE, EMPTY_STRING, PROJECT_UUID); + expectKeyNullOrEmptyIAE(() -> underTest.put(dbSession, A_KEY_TYPE, EMPTY_STRING, PROJECT_UUID)); } @Test public void save_throws_IAE_if_project_uuid_is_null() { - expectValueNullOrEmptyIAE(); - - underTest.put(dbSession, A_KEY_TYPE, A_KEY, null); + expectValueNullOrEmptyIAE(() -> underTest.put(dbSession, A_KEY_TYPE, A_KEY, null)); } @Test public void put_throws_IAE_if_project_uuid_is_empty() { - expectValueNullOrEmptyIAE(); - - underTest.put(dbSession, A_KEY_TYPE, A_KEY, EMPTY_STRING); + expectValueNullOrEmptyIAE(() -> underTest.put(dbSession, A_KEY_TYPE, A_KEY, EMPTY_STRING)); } @Test @@ -133,23 +122,17 @@ public class ProjectMappingsDaoTest { @Test public void get_throws_IAE_when_key_type_is_null() { - expectKeyTypeNullOrEmptyIAE(); - - underTest.get(dbSession, null, A_KEY); + expectKeyTypeNullOrEmptyIAE(() -> underTest.get(dbSession, null, A_KEY)); } @Test public void get_throws_IAE_when_key_is_null() { - expectKeyNullOrEmptyIAE(); - - underTest.get(dbSession, A_KEY_TYPE, null); + expectKeyNullOrEmptyIAE(() -> underTest.get(dbSession, A_KEY_TYPE, null)); } @Test public void get_throws_IAE_when_key_is_empty() { - expectKeyNullOrEmptyIAE(); - - underTest.get(dbSession, A_KEY_TYPE, EMPTY_STRING); + expectKeyNullOrEmptyIAE(() -> underTest.get(dbSession, A_KEY_TYPE, EMPTY_STRING)); } @Test @@ -164,19 +147,22 @@ public class ProjectMappingsDaoTest { assertThat(underTest.get(dbSession, A_KEY_TYPE, A_KEY).get().getProjectUuid()).isEqualTo(PROJECT_UUID); } - private void expectKeyTypeNullOrEmptyIAE() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("key type can't be null nor empty"); + private void expectKeyTypeNullOrEmptyIAE(ThrowingCallable callback) { + assertThatThrownBy(callback) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("key type can't be null nor empty"); } - private void expectKeyNullOrEmptyIAE() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("key can't be null nor empty"); + private void expectKeyNullOrEmptyIAE(ThrowingCallable callback) { + assertThatThrownBy(callback) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("key can't be null nor empty"); } - private void expectValueNullOrEmptyIAE() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("projectUuid can't be null nor empty"); + private void expectValueNullOrEmptyIAE(ThrowingCallable callback) { + assertThatThrownBy(callback) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("projectUuid can't be null nor empty"); } private ProjectMappingAssert assertThatProjectMapping(String keyType, String key) { diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/measure/MeasureDaoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/measure/MeasureDaoTest.java index 36e3e018191..e95ef5dcb67 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/measure/MeasureDaoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/measure/MeasureDaoTest.java @@ -24,7 +24,6 @@ import java.util.Optional; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.utils.System2; import org.sonar.core.util.Uuids; import org.sonar.db.DbClient; @@ -48,8 +47,6 @@ public class MeasureDaoTest { private MetricDto complexity; private MetricDto ncloc; - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester db = DbTester.create(System2.INSTANCE); diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/measure/MeasureTreeQueryTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/measure/MeasureTreeQueryTest.java index d10658b480e..f0cd3d60169 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/measure/MeasureTreeQueryTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/measure/MeasureTreeQueryTest.java @@ -20,20 +20,17 @@ package org.sonar.db.measure; import java.util.Collections; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.db.component.ComponentTesting; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.db.measure.MeasureTreeQuery.Strategy.CHILDREN; import static org.sonar.db.measure.MeasureTreeQuery.Strategy.LEAVES; public class MeasureTreeQueryTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void create_query() { @@ -111,9 +108,11 @@ public class MeasureTreeQueryTest { @Test public void fail_when_no_strategy() { - expectedException.expect(NullPointerException.class); - MeasureTreeQuery.builder() - .build(); + assertThatThrownBy(() -> { + MeasureTreeQuery.builder() + .build(); + }) + .isInstanceOf(NullPointerException.class); } } diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/measure/PastMeasureDtoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/measure/PastMeasureDtoTest.java index 295e9ea1c35..11d76693804 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/measure/PastMeasureDtoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/measure/PastMeasureDtoTest.java @@ -22,6 +22,7 @@ package org.sonar.db.measure; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class PastMeasureDtoTest { @@ -48,8 +49,9 @@ public class PastMeasureDtoTest { assertThat(measureWithoutValue.hasValue()).isFalse(); } - @Test(expected = NullPointerException.class) + @Test public void get_value_throw_a_NPE_if_value_is_null() { - new PastMeasureDto().getValue(); + assertThatThrownBy(() -> new PastMeasureDto().getValue()) + .isInstanceOf(NullPointerException.class); } } diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/measure/ProjectMeasuresIndexerIteratorTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/measure/ProjectMeasuresIndexerIteratorTest.java index e0e99b46386..21421d35b0e 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/measure/ProjectMeasuresIndexerIteratorTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/measure/ProjectMeasuresIndexerIteratorTest.java @@ -24,7 +24,6 @@ import java.util.Map; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.utils.System2; import org.sonar.db.DbClient; import org.sonar.db.DbSession; @@ -48,8 +47,6 @@ import static org.sonar.db.component.SnapshotTesting.newAnalysis; public class ProjectMeasuresIndexerIteratorTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/metric/MetricDaoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/metric/MetricDaoTest.java index 71d680a4d72..6297f2bfe84 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/metric/MetricDaoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/metric/MetricDaoTest.java @@ -28,7 +28,6 @@ import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.utils.System2; import org.sonar.core.util.Uuids; import org.sonar.db.DbSession; @@ -37,6 +36,7 @@ import org.sonar.db.RowNotFoundException; import static com.google.common.collect.Sets.newHashSet; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.within; import static org.sonar.db.metric.MetricTesting.newMetricDto; @@ -44,8 +44,6 @@ public class MetricDaoTest { @Rule public DbTester db = DbTester.create(System2.INSTANCE); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private DbSession dbSession = db.getSession(); private MetricDao underTest = new MetricDao(); @@ -66,9 +64,8 @@ public class MetricDaoTest { @Test public void select_or_fail_by_key() { - expectedException.expect(RowNotFoundException.class); - - underTest.selectOrFailByKey(dbSession, "unknown"); + assertThatThrownBy(() -> underTest.selectOrFailByKey(dbSession, "unknown")) + .isInstanceOf(RowNotFoundException.class); } @Test diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/metric/MetricDtoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/metric/MetricDtoTest.java index 4bee8934a12..0748e068b4e 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/metric/MetricDtoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/metric/MetricDtoTest.java @@ -19,16 +19,13 @@ */ package org.sonar.db.metric; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static com.google.common.base.Strings.repeat; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class MetricDtoTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private MetricDto underTest = new MetricDto(); @@ -70,39 +67,35 @@ public class MetricDtoTest { public void fail_if_key_longer_than_64_characters() { String a65 = repeat("a", 65); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Metric key length (65) is longer than the maximum authorized (64). '" + a65 + "' was provided."); - - underTest.setKey(a65); + assertThatThrownBy(() -> underTest.setKey(a65)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Metric key length (65) is longer than the maximum authorized (64). '" + a65 + "' was provided."); } @Test public void fail_if_name_longer_than_64_characters() { String a65 = repeat("a", 65); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Metric name length (65) is longer than the maximum authorized (64). '" + a65 + "' was provided."); - - underTest.setShortName(a65); + assertThatThrownBy(() -> underTest.setShortName(a65)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Metric name length (65) is longer than the maximum authorized (64). '" + a65 + "' was provided."); } @Test public void fail_if_description_longer_than_255_characters() { String a256 = repeat("a", 256); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Metric description length (256) is longer than the maximum authorized (255). '" + a256 + "' was provided."); - - underTest.setDescription(a256); + assertThatThrownBy(() -> underTest.setDescription(a256)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Metric description length (256) is longer than the maximum authorized (255). '" + a256 + "' was provided."); } @Test public void fail_if_domain_longer_than_64_characters() { String a65 = repeat("a", 65); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Metric domain length (65) is longer than the maximum authorized (64). '" + a65 + "' was provided."); - - underTest.setDomain(a65); + assertThatThrownBy(() -> underTest.setDomain(a65)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Metric domain length (65) is longer than the maximum authorized (64). '" + a65 + "' was provided."); } } diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/newcodeperiod/NewCodePeriodDtoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/newcodeperiod/NewCodePeriodDtoTest.java index 783178b558f..7f09acaf2f7 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/newcodeperiod/NewCodePeriodDtoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/newcodeperiod/NewCodePeriodDtoTest.java @@ -19,16 +19,12 @@ */ package org.sonar.db.newcodeperiod; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.utils.System2; import static org.assertj.core.api.Assertions.assertThat; public class NewCodePeriodDtoTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void getters_and_setters() { diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/permission/PermissionQueryTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/permission/PermissionQueryTest.java index 7271744f73a..4672f385847 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/permission/PermissionQueryTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/permission/PermissionQueryTest.java @@ -19,18 +19,15 @@ */ package org.sonar.db.permission; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.db.component.ComponentDto; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.db.component.ComponentTesting.newPublicProjectDto; public class PermissionQueryTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void create_query() { @@ -68,11 +65,12 @@ public class PermissionQueryTest { @Test public void fail_when_search_query_length_is_less_than_3_characters() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Search query should contains at least 3 characters"); - - PermissionQuery.builder() - .setSearchQuery("so") - .build(); + assertThatThrownBy(() -> { + PermissionQuery.builder() + .setSearchQuery("so") + .build(); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Search query should contains at least 3 characters"); } } diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/permission/template/PermissionTemplateCharacteristicDtoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/permission/template/PermissionTemplateCharacteristicDtoTest.java index cb3087e72e2..e5cec96aff9 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/permission/template/PermissionTemplateCharacteristicDtoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/permission/template/PermissionTemplateCharacteristicDtoTest.java @@ -20,22 +20,18 @@ package org.sonar.db.permission.template; import com.google.common.base.Strings; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class PermissionTemplateCharacteristicDtoTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); PermissionTemplateCharacteristicDto underTest = new PermissionTemplateCharacteristicDto(); @Test public void check_permission_field_length() { - expectedException.expect(IllegalArgumentException.class); - expectedException - .expectMessage("Permission key length (65) is longer than the maximum authorized (64). 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' was provided."); - - underTest.setPermission(Strings.repeat("a", 65)); + assertThatThrownBy(() -> underTest.setPermission(Strings.repeat("a", 65))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Permission key length (65) is longer than the maximum authorized (64). 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' was provided."); } } diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/permission/template/PermissionTemplateDaoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/permission/template/PermissionTemplateDaoTest.java index 3cfe40e6d75..396e4edb085 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/permission/template/PermissionTemplateDaoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/permission/template/PermissionTemplateDaoTest.java @@ -25,7 +25,6 @@ import java.util.List; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.utils.System2; import org.sonar.api.web.UserRole; import org.sonar.core.util.UuidFactory; @@ -54,8 +53,6 @@ public class PermissionTemplateDaoTest { private static final Date PAST = new Date(100_000_000_000L); private static final Date NOW = new Date(500_000_000_000L); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester db = DbTester.create(); diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/plugin/PluginDaoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/plugin/PluginDaoTest.java index 4b9f4f904bf..5562e83d46f 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/plugin/PluginDaoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/plugin/PluginDaoTest.java @@ -22,7 +22,6 @@ package org.sonar.db.plugin; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.utils.System2; import org.sonar.db.DbTester; import org.sonar.db.plugin.PluginDto.Type; @@ -33,8 +32,6 @@ import static org.sonar.db.plugin.PluginDto.Type.EXTERNAL; public class PluginDaoTest { - @Rule - public ExpectedException thrown = ExpectedException.none(); @Rule public DbTester db = DbTester.create(System2.INSTANCE); diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/plugin/PluginDaoWithPersisterTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/plugin/PluginDaoWithPersisterTest.java index 0d8132a118a..d3eaec31597 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/plugin/PluginDaoWithPersisterTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/plugin/PluginDaoWithPersisterTest.java @@ -21,7 +21,6 @@ package org.sonar.db.plugin; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; import org.sonar.api.utils.System2; import org.sonar.db.DbSession; @@ -38,8 +37,6 @@ import static org.sonar.db.plugin.PluginDto.Type.EXTERNAL; public class PluginDaoWithPersisterTest { private final AuditPersister auditPersister = mock(AuditPersister.class); - @Rule - public final ExpectedException thrown = ExpectedException.none(); @Rule public final DbTester db = DbTester.create(System2.INSTANCE, auditPersister); diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/property/InternalComponentPropertiesDaoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/property/InternalComponentPropertiesDaoTest.java index a9672e352ee..8c262d2957e 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/property/InternalComponentPropertiesDaoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/property/InternalComponentPropertiesDaoTest.java @@ -22,7 +22,6 @@ package org.sonar.db.property; import java.util.Optional; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.utils.System2; import org.sonar.core.util.UuidFactory; import org.sonar.core.util.UuidFactoryFast; @@ -42,8 +41,6 @@ public class InternalComponentPropertiesDaoTest { private System2 system2 = mock(System2.class); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester dbTester = DbTester.create(system2); private DbSession dbSession = dbTester.getSession(); diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/property/InternalComponentPropertyDtoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/property/InternalComponentPropertyDtoTest.java index 95aedbd7bd5..1089188d382 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/property/InternalComponentPropertyDtoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/property/InternalComponentPropertyDtoTest.java @@ -22,18 +22,15 @@ package org.sonar.db.property; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import org.apache.commons.lang.StringUtils; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; @RunWith(DataProviderRunner.class) public class InternalComponentPropertyDtoTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void setter_and_getter() { @@ -56,30 +53,27 @@ public class InternalComponentPropertyDtoTest { @Test @DataProvider({"null", ""}) public void setKey_throws_IAE_if_key_is_null_or_empty(String key) { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("key can't be null nor empty"); - - new InternalComponentPropertyDto().setKey(key); + assertThatThrownBy(() -> new InternalComponentPropertyDto().setKey(key)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("key can't be null nor empty"); } @Test public void setKey_throws_IAE_if_key_is_too_long() { String veryLongKey = StringUtils.repeat("a", 513); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(String.format("key length (513) is longer than the maximum authorized (512). '%s' was provided", veryLongKey)); - - new InternalComponentPropertyDto().setKey(veryLongKey); + assertThatThrownBy(() -> new InternalComponentPropertyDto().setKey(veryLongKey)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage(String.format("key length (513) is longer than the maximum authorized (512). '%s' was provided", veryLongKey)); } @Test public void setValue_throws_IAE_if_value_is_too_long() { String veryLongValue = StringUtils.repeat("a", 4001); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(String.format("value length (4001) is longer than the maximum authorized (4000). '%s' was provided", veryLongValue)); - - new InternalComponentPropertyDto().setValue(veryLongValue); + assertThatThrownBy(() -> new InternalComponentPropertyDto().setValue(veryLongValue)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage(String.format("value length (4001) is longer than the maximum authorized (4000). '%s' was provided", veryLongValue)); } @Test diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/property/InternalPropertiesDaoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/property/InternalPropertiesDaoTest.java index 020d2e7ff97..cfd4277c609 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/property/InternalPropertiesDaoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/property/InternalPropertiesDaoTest.java @@ -34,10 +34,10 @@ import java.util.stream.Stream; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.assertj.core.api.AbstractAssert; +import org.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import org.sonar.api.utils.System2; @@ -50,6 +50,7 @@ import static java.lang.Boolean.FALSE; import static java.lang.Boolean.TRUE; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.entry; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; @@ -81,8 +82,6 @@ public class InternalPropertiesDaoTest { private final System2 system2 = mock(System2.class); private final String DEFAULT_PROJECT_TEMPLATE = "defaultTemplate.prj"; - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester dbTester = DbTester.create(system2); @@ -98,30 +97,22 @@ public class InternalPropertiesDaoTest { @Test public void save_throws_IAE_if_key_is_null() { - expectKeyNullOrEmptyIAE(); - - underTest.save(dbSession, null, VALUE_SMALL); + expectKeyNullOrEmptyIAE(() -> underTest.save(dbSession, null, VALUE_SMALL)); } @Test public void save_throws_IAE_if_key_is_empty() { - expectKeyNullOrEmptyIAE(); - - underTest.save(dbSession, EMPTY_STRING, VALUE_SMALL); + expectKeyNullOrEmptyIAE(() -> underTest.save(dbSession, EMPTY_STRING, VALUE_SMALL)); } @Test public void save_throws_IAE_if_value_is_null() { - expectValueNullOrEmptyIAE(); - - underTest.save(dbSession, A_KEY, null); + expectValueNullOrEmptyIAE(() -> underTest.save(dbSession, A_KEY, null)); } @Test public void save_throws_IAE_if_value_is_empty() { - expectValueNullOrEmptyIAE(); - - underTest.save(dbSession, A_KEY, EMPTY_STRING); + expectValueNullOrEmptyIAE(() -> underTest.save(dbSession, A_KEY, EMPTY_STRING)); } @Test @@ -140,7 +131,7 @@ public class InternalPropertiesDaoTest { dbSession.commit(); assertThat(dbTester.countRowsOfTable("internal_properties")).isOne(); clearInvocations(auditPersister); - + underTest.delete(dbSession, A_KEY); dbSession.commit(); @@ -266,16 +257,12 @@ public class InternalPropertiesDaoTest { @Test public void saveAsEmpty_throws_IAE_if_key_is_null() { - expectKeyNullOrEmptyIAE(); - - underTest.saveAsEmpty(dbSession, null); + expectKeyNullOrEmptyIAE(() -> underTest.saveAsEmpty(dbSession, null)); } @Test public void saveAsEmpty_throws_IAE_if_key_is_empty() { - expectKeyNullOrEmptyIAE(); - - underTest.saveAsEmpty(dbSession, EMPTY_STRING); + expectKeyNullOrEmptyIAE(() -> underTest.saveAsEmpty(dbSession, EMPTY_STRING)); } @Test @@ -337,16 +324,12 @@ public class InternalPropertiesDaoTest { @Test public void selectByKey_throws_IAE_when_key_is_null() { - expectKeyNullOrEmptyIAE(); - - underTest.selectByKey(dbSession, null); + expectKeyNullOrEmptyIAE(() -> underTest.selectByKey(dbSession, null)); } @Test public void selectByKey_throws_IAE_when_key_is_empty() { - expectKeyNullOrEmptyIAE(); - - underTest.selectByKey(dbSession, EMPTY_STRING); + expectKeyNullOrEmptyIAE(() -> underTest.selectByKey(dbSession, EMPTY_STRING)); } @Test @@ -395,9 +378,7 @@ public class InternalPropertiesDaoTest { .flatMap(s -> s) .collect(Collectors.toSet()); - expectKeyNullOrEmptyIAE(); - - underTest.selectByKeys(dbSession, keysIncludingANull); + expectKeyNullOrEmptyIAE(() -> underTest.selectByKeys(dbSession, keysIncludingANull)); } @Test @@ -410,9 +391,7 @@ public class InternalPropertiesDaoTest { .flatMap(s -> s) .collect(Collectors.toSet()); - expectKeyNullOrEmptyIAE(); - - underTest.selectByKeys(dbSession, keysIncludingAnEmptyString); + expectKeyNullOrEmptyIAE(() -> underTest.selectByKeys(dbSession, keysIncludingAnEmptyString)); } @Test @@ -563,20 +542,18 @@ public class InternalPropertiesDaoTest { @Test public void tryLock_throws_IAE_if_lock_name_is_empty() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("lock name can't be empty"); - - underTest.tryLock(dbSession, "", 60); + assertThatThrownBy(() -> underTest.tryLock(dbSession, "", 60)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("lock name can't be empty"); } @Test public void tryLock_throws_IAE_if_lock_name_length_is_16_or_more() { String tooLongName = randomAlphabetic(16 + new Random().nextInt(30)); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("lock name is too long"); - - underTest.tryLock(dbSession, tooLongName, 60); + assertThatThrownBy(() -> underTest.tryLock(dbSession, tooLongName, 60)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("lock name is too long"); } private void assertAuditValue(String key, @Nullable String value) { @@ -591,14 +568,16 @@ public class InternalPropertiesDaoTest { return "lock." + lockName; } - private void expectKeyNullOrEmptyIAE() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("key can't be null nor empty"); + private void expectKeyNullOrEmptyIAE(ThrowingCallable callback) { + assertThatThrownBy(callback) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("key can't be null nor empty"); } - private void expectValueNullOrEmptyIAE() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("value can't be null nor empty"); + private void expectValueNullOrEmptyIAE(ThrowingCallable callback) { + assertThatThrownBy(callback) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("value can't be null nor empty"); } private InternalPropertyAssert assertThatInternalProperty(String key) { diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/property/PropertiesDaoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/property/PropertiesDaoTest.java index 58637968dcc..d11d76153c2 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/property/PropertiesDaoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/property/PropertiesDaoTest.java @@ -34,7 +34,6 @@ import javax.annotation.Nullable; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.api.impl.utils.AlwaysIncreasingSystem2; import org.sonar.api.resources.Qualifiers; @@ -54,6 +53,7 @@ import static com.google.common.collect.Sets.newHashSet; import static java.util.Collections.singletonList; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.groups.Tuple.tuple; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; @@ -76,8 +76,6 @@ public class PropertiesDaoTest { private final AlwaysIncreasingSystem2 system2 = new AlwaysIncreasingSystem2(INITIAL_DATE, 1); private final AuditPersister auditPersister = mock(AuditPersister.class); - @Rule - public ExpectedException thrown = ExpectedException.none(); @Rule public DbTester db = DbTester.create(system2, auditPersister); @@ -1269,14 +1267,14 @@ public class PropertiesDaoTest { @Test public void should_not_rename_with_empty_key() { - thrown.expect(IllegalArgumentException.class); - underTest.renamePropertyKey("foo", ""); + assertThatThrownBy(() -> underTest.renamePropertyKey("foo", "")) + .isInstanceOf(IllegalArgumentException.class); } @Test public void should_not_rename_an_empty_key() { - thrown.expect(IllegalArgumentException.class); - underTest.renamePropertyKey(null, "foo"); + assertThatThrownBy(() -> underTest.renamePropertyKey(null, "foo")) + .isInstanceOf(IllegalArgumentException.class); } private PropertyDto findByKey(List properties, String key) { diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/property/PropertiesDaoWithPersisterTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/property/PropertiesDaoWithPersisterTest.java index 1ba0912b70b..653ef24f2d8 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/property/PropertiesDaoWithPersisterTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/property/PropertiesDaoWithPersisterTest.java @@ -24,7 +24,6 @@ import java.util.List; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.sonar.api.impl.utils.AlwaysIncreasingSystem2; @@ -66,8 +65,6 @@ public class PropertiesDaoWithPersisterTest { private final AuditPersister auditPersister = mock(AuditPersister.class); private final ArgumentCaptor newValueCaptor = ArgumentCaptor.forClass(PropertyNewValue.class); - @Rule - public ExpectedException thrown = ExpectedException.none(); @Rule public DbTester db = DbTester.create(system2, auditPersister); diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/purge/PurgeDaoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/purge/PurgeDaoTest.java index ac34726bd91..f2566237fe2 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/purge/PurgeDaoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/purge/PurgeDaoTest.java @@ -39,7 +39,6 @@ import org.apache.commons.lang.math.RandomUtils; import org.apache.commons.lang.time.DateUtils; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.issue.Issue; import org.sonar.api.utils.System2; import org.sonar.core.util.CloseableIterator; @@ -117,8 +116,6 @@ public class PurgeDaoTest { @Rule public DbTester db = DbTester.create(system2); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private final DbClient dbClient = db.getDbClient(); private final DbSession dbSession = db.getSession(); diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/purge/PurgeDaoWithAuditTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/purge/PurgeDaoWithAuditTest.java index 70c27f914ea..bf0900bbc6e 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/purge/PurgeDaoWithAuditTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/purge/PurgeDaoWithAuditTest.java @@ -34,7 +34,6 @@ import org.sonar.db.component.ComponentDto; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/purge/PurgeableAnalysisDtoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/purge/PurgeableAnalysisDtoTest.java index 4228ca0cb4d..4905705ce2c 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/purge/PurgeableAnalysisDtoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/purge/PurgeableAnalysisDtoTest.java @@ -19,15 +19,12 @@ */ package org.sonar.db.purge; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class PurgeableAnalysisDtoTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void testEquals() { @@ -49,8 +46,9 @@ public class PurgeableAnalysisDtoTest { // no uuid => NPE dto = new PurgeableAnalysisDto(); - expectedException.expect(NullPointerException.class); - dto.hashCode(); + assertThatThrownBy(dto::hashCode) + .isInstanceOf(NullPointerException.class); + } @Test diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/qualityprofile/ActiveRuleDaoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/qualityprofile/ActiveRuleDaoTest.java index 36e09eb8f5b..5126294af22 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/qualityprofile/ActiveRuleDaoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/qualityprofile/ActiveRuleDaoTest.java @@ -27,7 +27,6 @@ import java.util.function.Consumer; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.impl.utils.TestSystem2; import org.sonar.api.rule.Severity; import org.sonar.api.rules.RuleType; @@ -43,6 +42,7 @@ import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.entry; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.api.rule.RuleStatus.BETA; @@ -56,8 +56,6 @@ import static org.sonar.db.qualityprofile.ActiveRuleDto.createFor; public class ActiveRuleDaoTest { - @Rule - public ExpectedException thrown = ExpectedException.none(); private static final long NOW = 10_000_000L; @@ -279,26 +277,23 @@ public class ActiveRuleDaoTest { @Test public void fail_to_insert_when_profile_id_is_null() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Quality profile is not persisted (missing id)"); - - underTest.insert(dbSession, createFor(profile1, rule1).setProfileUuid(null)); + assertThatThrownBy(() -> underTest.insert(dbSession, createFor(profile1, rule1).setProfileUuid(null))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Quality profile is not persisted (missing id)"); } @Test public void fail_to_insert_when_rule_uuid_is_null() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Rule is not persisted"); - - underTest.insert(dbSession, createFor(profile1, rule1).setRuleUuid(null)); + assertThatThrownBy(() -> underTest.insert(dbSession, createFor(profile1, rule1).setRuleUuid(null))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Rule is not persisted"); } @Test public void fail_to_insert_when_uuid_is_not_null() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("ActiveRule is already persisted"); - - underTest.insert(dbSession, createFor(profile1, rule1).setUuid("uuid")); + assertThatThrownBy(() -> underTest.insert(dbSession, createFor(profile1, rule1).setUuid("uuid"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("ActiveRule is already persisted"); } @Test @@ -333,26 +328,23 @@ public class ActiveRuleDaoTest { @Test public void fail_to_update_when_profile_id_is_null() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Quality profile is not persisted (missing id)"); - - underTest.update(dbSession, createFor(profile1, rule1).setUuid("uuid").setProfileUuid(null)); + assertThatThrownBy(() -> underTest.update(dbSession, createFor(profile1, rule1).setUuid("uuid").setProfileUuid(null))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Quality profile is not persisted (missing id)"); } @Test public void fail_to_update_when_rule_id_is_null() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Rule is not persisted"); - - underTest.update(dbSession, createFor(profile1, rule1).setUuid("uuid").setRuleUuid(null)); + assertThatThrownBy(() -> underTest.update(dbSession, createFor(profile1, rule1).setUuid("uuid").setRuleUuid(null))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Rule is not persisted"); } @Test public void fail_to_update_when_id_is_null() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("ActiveRule is not persisted"); - - underTest.update(dbSession, createFor(profile1, rule1).setUuid(null)); + assertThatThrownBy(() -> underTest.update(dbSession, createFor(profile1, rule1).setUuid(null))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("ActiveRule is not persisted"); } @Test @@ -470,32 +462,35 @@ public class ActiveRuleDaoTest { @Test public void insertParam_fails_when_active_rule_id_is_null() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("ActiveRule is not persisted"); - - underTest.insertParam(dbSession, - createFor(profile1, rule1).setUuid(null), - ActiveRuleParamDto.createFor(rule1Param1).setValue("activeValue1")); + assertThatThrownBy(() -> { + underTest.insertParam(dbSession, + createFor(profile1, rule1).setUuid(null), + ActiveRuleParamDto.createFor(rule1Param1).setValue("activeValue1")); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("ActiveRule is not persisted"); } @Test public void insertParam_fails_when_active_rule_param_id_is_null() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("ActiveRuleParam is already persisted"); - - underTest.insertParam(dbSession, - createFor(profile1, rule1).setUuid("uuid"), - ActiveRuleParamDto.createFor(rule1Param1).setValue("activeValue1").setUuid("uuid-1")); + assertThatThrownBy(() -> { + underTest.insertParam(dbSession, + createFor(profile1, rule1).setUuid("uuid"), + ActiveRuleParamDto.createFor(rule1Param1).setValue("activeValue1").setUuid("uuid-1")); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("ActiveRuleParam is already persisted"); } @Test public void insertParam_fails_when_uuid_is_not_null() { - thrown.expect(NullPointerException.class); - thrown.expectMessage("Rule param is not persisted"); - - underTest.insertParam(dbSession, - createFor(profile1, rule1).setUuid("uuid"), - ActiveRuleParamDto.createFor(rule1Param1).setValue("activeValue1").setRulesParameterUuid(null)); + assertThatThrownBy(() -> { + underTest.insertParam(dbSession, + createFor(profile1, rule1).setUuid("uuid"), + ActiveRuleParamDto.createFor(rule1Param1).setValue("activeValue1").setRulesParameterUuid(null)); + }) + .isInstanceOf(NullPointerException.class) + .hasMessage("Rule param is not persisted"); } @Test diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/qualityprofile/QProfileChangeDaoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/qualityprofile/QProfileChangeDaoTest.java index 1870a09e685..cd49fca93ca 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/qualityprofile/QProfileChangeDaoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/qualityprofile/QProfileChangeDaoTest.java @@ -24,7 +24,6 @@ import java.util.Map; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.impl.utils.AlwaysIncreasingSystem2; import org.sonar.api.utils.System2; import org.sonar.core.util.SequenceUuidFactory; @@ -33,14 +32,13 @@ import org.sonar.db.DbSession; import org.sonar.db.DbTester; import static java.util.Arrays.asList; +import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; public class QProfileChangeDaoTest { private System2 system2 = new AlwaysIncreasingSystem2(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester db = DbTester.create(system2); @@ -77,10 +75,9 @@ public class QProfileChangeDaoTest { @Test public void insert_throws_ISE_if_date_is_already_set() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Date of QProfileChangeDto must be set by DAO only. Got 123."); - - underTest.insert(dbSession, new QProfileChangeDto().setCreatedAt(123L)); + assertThatThrownBy(() -> underTest.insert(dbSession, new QProfileChangeDto().setCreatedAt(123L))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Date of QProfileChangeDto must be set by DAO only. Got 123."); } @Test diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/qualityprofile/QProfileEditUsersDaoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/qualityprofile/QProfileEditUsersDaoTest.java index 8989a72e6ac..05df576f38b 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/qualityprofile/QProfileEditUsersDaoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/qualityprofile/QProfileEditUsersDaoTest.java @@ -23,7 +23,6 @@ import java.sql.SQLException; import java.util.List; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; import org.sonar.api.impl.utils.TestSystem2; import org.sonar.api.utils.System2; @@ -38,6 +37,7 @@ import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.entry; import static org.assertj.core.api.Assertions.tuple; +import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -46,7 +46,6 @@ import static org.sonar.db.qualityprofile.SearchQualityProfilePermissionQuery.AN import static org.sonar.db.qualityprofile.SearchQualityProfilePermissionQuery.IN; import static org.sonar.db.qualityprofile.SearchQualityProfilePermissionQuery.OUT; import static org.sonar.db.qualityprofile.SearchQualityProfilePermissionQuery.builder; -import static org.sonar.test.ExceptionCauseMatcher.hasType; public class QProfileEditUsersDaoTest { @@ -56,8 +55,6 @@ public class QProfileEditUsersDaoTest { private final AuditPersister auditPersister = mock(AuditPersister.class); private final ArgumentCaptor newValueCaptor = ArgumentCaptor.forClass(UserEditorNewValue.class); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester db = DbTester.create(system2, auditPersister); @@ -259,13 +256,14 @@ public class QProfileEditUsersDaoTest { .setQProfileUuid(qualityProfileUuid), qualityProfileName, userLogin); - expectedException.expectCause(hasType(SQLException.class)); - - underTest.insert(db.getSession(), new QProfileEditUsersDto() - .setUuid("UUID-2") - .setUserUuid(userUuid) - .setQProfileUuid(qualityProfileUuid), - qualityProfileName, userLogin); + assertThatThrownBy(() -> { + underTest.insert(db.getSession(), new QProfileEditUsersDto() + .setUuid("UUID-2") + .setUserUuid(userUuid) + .setQProfileUuid(qualityProfileUuid), + qualityProfileName, userLogin); + }) + .hasCauseInstanceOf(SQLException.class); } @Test diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/rule/RuleDaoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/rule/RuleDaoTest.java index f8bb1002e1d..0aa60519e8b 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/rule/RuleDaoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/rule/RuleDaoTest.java @@ -32,7 +32,6 @@ import org.apache.ibatis.exceptions.PersistenceException; import org.apache.ibatis.session.ResultHandler; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.rule.RuleKey; import org.sonar.api.rule.RuleStatus; import org.sonar.api.rule.Severity; @@ -51,6 +50,7 @@ import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.api.rule.RuleStatus.REMOVED; import static org.sonar.db.rule.RuleTesting.newRuleMetadata; @@ -58,8 +58,6 @@ import static org.sonar.db.rule.RuleTesting.newRuleMetadata; public class RuleDaoTest { private static final String UNKNOWN_RULE_UUID = "unknown-uuid"; - @Rule - public ExpectedException thrown = ExpectedException.none(); @Rule public DbTester db = DbTester.create(System2.INSTANCE); @@ -179,18 +177,16 @@ public class RuleDaoTest { @Test public void selectOrFailByKey_fails_if_rule_not_found() { - thrown.expect(RowNotFoundException.class); - thrown.expectMessage("Rule with key 'NOT:FOUND' does not exist"); - - underTest.selectOrFailByKey(db.getSession(), RuleKey.of("NOT", "FOUND")); + assertThatThrownBy(() -> underTest.selectOrFailByKey(db.getSession(), RuleKey.of("NOT", "FOUND"))) + .isInstanceOf(RowNotFoundException.class) + .hasMessage("Rule with key 'NOT:FOUND' does not exist"); } @Test public void selectOrFailDefinitionByKey_fails_if_rule_not_found() { - thrown.expect(RowNotFoundException.class); - thrown.expectMessage("Rule with key 'NOT:FOUND' does not exist"); - - underTest.selectOrFailDefinitionByKey(db.getSession(), RuleKey.of("NOT", "FOUND")); + assertThatThrownBy(() -> underTest.selectOrFailDefinitionByKey(db.getSession(), RuleKey.of("NOT", "FOUND"))) + .isInstanceOf(RowNotFoundException.class) + .hasMessage("Rule with key 'NOT:FOUND' does not exist"); } @Test @@ -738,8 +734,8 @@ public class RuleDaoTest { underTest.insertRuleParam(db.getSession(), ruleDefinitionDto, param); - thrown.expect(PersistenceException.class); - underTest.insertRuleParam(db.getSession(), ruleDefinitionDto, param); + assertThatThrownBy(() -> underTest.insertRuleParam(db.getSession(), ruleDefinitionDto, param)) + .isInstanceOf(PersistenceException.class); } @Test @@ -1035,10 +1031,11 @@ public class RuleDaoTest { db.rules().insertDeprecatedKey(d -> d.setOldRepositoryKey(repositoryKey) .setOldRuleKey(ruleKey)); - thrown.expect(PersistenceException.class); - - db.rules().insertDeprecatedKey(d -> d.setOldRepositoryKey(repositoryKey) - .setOldRuleKey(ruleKey)); + assertThatThrownBy(() -> { + db.rules().insertDeprecatedKey(d -> d.setOldRepositoryKey(repositoryKey) + .setOldRuleKey(ruleKey)); + }) + .isInstanceOf(PersistenceException.class); } private static class Accumulator implements Consumer { diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/rule/RuleDtoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/rule/RuleDtoTest.java index c431285f3de..ca4645a8087 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/rule/RuleDtoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/rule/RuleDtoTest.java @@ -22,41 +22,37 @@ package org.sonar.db.rule; import com.google.common.collect.ImmutableSet; import java.util.Collections; import java.util.Set; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.apache.commons.lang.StringUtils.repeat; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class RuleDtoTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void fail_if_key_is_too_long() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Rule key is too long: "); - - new RuleDto().setRuleKey(repeat("x", 250)); + assertThatThrownBy(() -> new RuleDto().setRuleKey(repeat("x", 250))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Rule key is too long: "); } @Test public void fail_if_name_is_too_long() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Rule name is too long: "); - - new RuleDto().setName(repeat("x", 300)); + assertThatThrownBy(() -> new RuleDto().setName(repeat("x", 300))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Rule name is too long: "); } @Test public void fail_if_tags_are_too_long() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Rule tags are too long: "); - - Set tags = ImmutableSet.of(repeat("a", 2000), repeat("b", 1000), repeat("c", 2000)); - new RuleDto().setTags(tags); + assertThatThrownBy(() -> { + Set tags = ImmutableSet.of(repeat("a", 2000), repeat("b", 1000), repeat("c", 2000)); + new RuleDto().setTags(tags); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Rule tags are too long: "); } @Test diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/rule/RuleRepositoryDaoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/rule/RuleRepositoryDaoTest.java index 7ef08756877..8ecb550b730 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/rule/RuleRepositoryDaoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/rule/RuleRepositoryDaoTest.java @@ -26,7 +26,6 @@ import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.impl.utils.AlwaysIncreasingSystem2; import org.sonar.api.utils.System2; import org.sonar.db.DbSession; @@ -35,13 +34,12 @@ import org.sonar.db.DbTester; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class RuleRepositoryDaoTest { private System2 system2 = new AlwaysIncreasingSystem2(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester dbTester = DbTester.create(system2); @@ -116,11 +114,12 @@ public class RuleRepositoryDaoTest { @Test public void deleteIfKeyNotIn_fails_if_more_than_1000_keys() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("too many rule repositories: 1100"); - - Collection keys = IntStream.range(0, 1_100).mapToObj(index -> "repo" + index).collect(Collectors.toSet()); - underTest.deleteIfKeyNotIn(dbTester.getSession(), keys); + assertThatThrownBy(() -> { + Collection keys = IntStream.range(0, 1_100).mapToObj(index -> "repo" + index).collect(Collectors.toSet()); + underTest.deleteIfKeyNotIn(dbTester.getSession(), keys); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("too many rule repositories: 1100"); } @Test diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/schemamigration/SchemaMigrationDaoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/schemamigration/SchemaMigrationDaoTest.java index 86de1101116..c29c53771cb 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/schemamigration/SchemaMigrationDaoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/schemamigration/SchemaMigrationDaoTest.java @@ -23,18 +23,16 @@ import java.sql.Statement; import org.junit.After; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.utils.System2; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class SchemaMigrationDaoTest { @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private DbSession dbSession = dbTester.getSession(); private SchemaMigrationDao underTest = dbTester.getDbClient().schemaMigrationDao(); @@ -49,18 +47,16 @@ public class SchemaMigrationDaoTest { @Test public void insert_fails_with_NPE_if_argument_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("version can't be null"); - - underTest.insert(dbSession, null); + assertThatThrownBy(() -> underTest.insert(dbSession, null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("version can't be null"); } @Test public void insert_fails_with_IAE_if_argument_is_empty() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("version can't be empty"); - - underTest.insert(dbSession, ""); + assertThatThrownBy(() -> underTest.insert(dbSession, "")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("version can't be empty"); } @Test diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/source/FileSourceDtoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/source/FileSourceDtoTest.java index 53efd6f8a48..ae89e31d7bc 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/source/FileSourceDtoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/source/FileSourceDtoTest.java @@ -25,12 +25,11 @@ import java.util.List; import java.util.Random; import java.util.stream.Collectors; import java.util.stream.IntStream; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.db.protobuf.DbFileSources; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class FileSourceDtoTest { private static final String LOREM_IPSUM = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam ac magna libero. " + @@ -39,8 +38,6 @@ public class FileSourceDtoTest { "Curabitur sit amet dignissim magna, at efficitur dolor. Ut non felis aliquam justo euismod gravida. Morbi eleifend vitae ante eu pulvinar. " + "Aliquam rhoncus magna quis lorem posuere semper."; - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void getSourceData_throws_ISE_with_id_fileUuid_and_projectUuid_in_message_when_data_cant_be_read() { @@ -53,10 +50,9 @@ public class FileSourceDtoTest { .setFileUuid(fileUuid) .setProjectUuid(projectUuid); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Fail to decompress and deserialize source data [uuid=" + uuid + ",fileUuid=" + fileUuid + ",projectUuid=" + projectUuid + "]"); - - underTest.getSourceData(); + assertThatThrownBy(underTest::getSourceData) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Fail to decompress and deserialize source data [uuid=" + uuid + ",fileUuid=" + fileUuid + ",projectUuid=" + projectUuid + "]"); } @Test diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/source/LineHashVersionTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/source/LineHashVersionTest.java index e36b08bc0d6..3069e6057b5 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/source/LineHashVersionTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/source/LineHashVersionTest.java @@ -19,15 +19,12 @@ */ package org.sonar.db.source; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class LineHashVersionTest { - @Rule - public ExpectedException exception = ExpectedException.none(); @Test public void should_create_from_int() { @@ -37,15 +34,15 @@ public class LineHashVersionTest { @Test public void should_throw_exception_if_version_is_too_high() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("Unknown line hash version: 2"); - LineHashVersion.valueOf(2); + assertThatThrownBy(() -> LineHashVersion.valueOf(2)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Unknown line hash version: 2"); } @Test public void should_throw_exception_if_version_is_too_low() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("Unknown line hash version: -1"); - LineHashVersion.valueOf(-1); + assertThatThrownBy(() -> LineHashVersion.valueOf(-1)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Unknown line hash version: -1"); } } diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/user/GroupMembershipQueryTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/user/GroupMembershipQueryTest.java index 15156c004c7..70f0b2e6451 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/user/GroupMembershipQueryTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/user/GroupMembershipQueryTest.java @@ -19,16 +19,13 @@ */ package org.sonar.db.user; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class GroupMembershipQueryTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void create_query() { @@ -47,11 +44,12 @@ public class GroupMembershipQueryTest { @Test public void fail_on_invalid_membership() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Membership is not valid (got unknwown). Availables values are [ANY, IN, OUT]"); - - GroupMembershipQuery.builder() - .membership("unknwown") - .build(); + assertThatThrownBy(() -> { + GroupMembershipQuery.builder() + .membership("unknwown") + .build(); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Membership is not valid (got unknwown). Availables values are [ANY, IN, OUT]"); } } diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/user/RoleDaoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/user/RoleDaoTest.java index 1280d8843e0..493b526e98d 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/user/RoleDaoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/user/RoleDaoTest.java @@ -20,10 +20,10 @@ package org.sonar.db.user; import java.util.List; +import org.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.utils.System2; import org.sonar.api.web.UserRole; import org.sonar.core.util.Uuids; @@ -32,14 +32,13 @@ import org.sonar.db.DbTester; import org.sonar.db.component.ComponentDto; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.db.permission.GlobalPermission.ADMINISTER; public class RoleDaoTest { @Rule public DbTester db = DbTester.create(System2.INSTANCE); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private DbSession dbSession = db.getSession(); private RoleDao underTest = db.getDbClient().roleDao(); @@ -59,21 +58,18 @@ public class RoleDaoTest { @Test public void selectComponentUuidsByPermissionAndUserId_throws_IAR_if_permission_USER_is_specified() { - expectUnsupportedUserAndCodeViewerPermission(); - - underTest.selectComponentUuidsByPermissionAndUserUuid(dbSession, UserRole.USER, Uuids.createFast()); + expectUnsupportedUserAndCodeViewerPermission(() -> underTest.selectComponentUuidsByPermissionAndUserUuid(dbSession, UserRole.USER, Uuids.createFast())); } @Test public void selectComponentUuidsByPermissionAndUserId_throws_IAR_if_permission_CODEVIEWER_is_specified() { - expectUnsupportedUserAndCodeViewerPermission(); - - underTest.selectComponentUuidsByPermissionAndUserUuid(dbSession, UserRole.CODEVIEWER, Uuids.createFast()); + expectUnsupportedUserAndCodeViewerPermission(() -> underTest.selectComponentUuidsByPermissionAndUserUuid(dbSession, UserRole.CODEVIEWER, Uuids.createFast())); } - private void expectUnsupportedUserAndCodeViewerPermission() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Permissions [user, codeviewer] are not supported by selectComponentUuidsByPermissionAndUserUuid"); + private void expectUnsupportedUserAndCodeViewerPermission(ThrowingCallable callback) { + assertThatThrownBy(callback) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Permissions [user, codeviewer] are not supported by selectComponentUuidsByPermissionAndUserUuid"); } @Test diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/user/UserDtoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/user/UserDtoTest.java index dc10e100482..5df972a123a 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/user/UserDtoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/user/UserDtoTest.java @@ -21,16 +21,12 @@ package org.sonar.db.user; import java.util.Arrays; import java.util.Collections; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; public class UserDtoTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void encode_scm_accounts() { diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/user/UserGroupDaoWithPersisterTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/user/UserGroupDaoWithPersisterTest.java index fdcda4f0ad3..b59790d0d04 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/user/UserGroupDaoWithPersisterTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/user/UserGroupDaoWithPersisterTest.java @@ -33,7 +33,6 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions; public class UserGroupDaoWithPersisterTest { diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/user/UserTokenDaoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/user/UserTokenDaoTest.java index 43b4f48a66c..bc4ec3e7d14 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/user/UserTokenDaoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/user/UserTokenDaoTest.java @@ -22,7 +22,6 @@ package org.sonar.db.user; import java.util.Map; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.utils.System2; import org.sonar.db.DbSession; import org.sonar.db.DbTester; @@ -34,8 +33,6 @@ import static org.sonar.db.user.UserTokenTesting.newUserToken; public class UserTokenDaoTest { @Rule public DbTester db = DbTester.create(System2.INSTANCE); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private DbSession dbSession = db.getSession(); diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/user/UserTokenDaoWithPersisterTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/user/UserTokenDaoWithPersisterTest.java index 16eed5e1f01..92e6d71afa8 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/user/UserTokenDaoWithPersisterTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/user/UserTokenDaoWithPersisterTest.java @@ -21,7 +21,6 @@ package org.sonar.db.user; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; import org.sonar.api.utils.DateUtils; import org.sonar.api.utils.System2; @@ -46,8 +45,6 @@ public class UserTokenDaoWithPersisterTest { @Rule public final DbTester db = DbTester.create(System2.INSTANCE, auditPersister); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private final DbSession dbSession = db.getSession(); private final DbClient dbClient = db.getDbClient(); diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/user/UserTokenDtoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/user/UserTokenDtoTest.java index 84366cf7f90..7e2f1e44c51 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/user/UserTokenDtoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/user/UserTokenDtoTest.java @@ -19,21 +19,17 @@ */ package org.sonar.db.user; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class UserTokenDtoTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void fail_if_token_hash_is_longer_than_255_characters() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Token hash length (256) is longer than the maximum authorized (255)"); - - new UserTokenDto().setTokenHash(randomAlphabetic(256)); + assertThatThrownBy(() -> new UserTokenDto().setTokenHash(randomAlphabetic(256))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Token hash length (256) is longer than the maximum authorized (255)"); } } diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/webhook/WebhookDeliveryDaoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/webhook/WebhookDeliveryDaoTest.java index c1eee3e00f0..fb2b70c8a7b 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/webhook/WebhookDeliveryDaoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/webhook/WebhookDeliveryDaoTest.java @@ -24,7 +24,6 @@ import java.util.Map; import java.util.Optional; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.utils.System2; import org.sonar.db.DbClient; import org.sonar.db.DbSession; @@ -42,8 +41,6 @@ public class WebhookDeliveryDaoTest { @Rule public final DbTester dbTester = DbTester.create(System2.INSTANCE); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private final DbClient dbClient = dbTester.getDbClient(); private final DbSession dbSession = dbTester.getSession(); diff --git a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/charset/DatabaseCharsetCheckerTest.java b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/charset/DatabaseCharsetCheckerTest.java index 4c54c7efeef..cc0814e8bb2 100644 --- a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/charset/DatabaseCharsetCheckerTest.java +++ b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/charset/DatabaseCharsetCheckerTest.java @@ -21,9 +21,7 @@ package org.sonar.server.platform.db.migration.charset; import java.sql.Connection; import java.sql.SQLException; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.Mockito; import org.sonar.db.Database; import org.sonar.db.dialect.Dialect; @@ -33,6 +31,7 @@ import org.sonar.db.dialect.Oracle; import org.sonar.db.dialect.PostgreSql; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doThrow; @@ -43,8 +42,6 @@ import static org.mockito.Mockito.when; public class DatabaseCharsetCheckerTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private Database db = mock(Database.class, Mockito.RETURNS_MOCKS); private CharsetHandler handler = mock(CharsetHandler.class); @@ -67,9 +64,9 @@ public class DatabaseCharsetCheckerTest { when(db.getDialect()).thenReturn(dialect); doThrow(new SQLException("failure")).when(handler).handle(any(Connection.class), any(DatabaseCharsetChecker.State.class)); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("failure"); - underTest.check(DatabaseCharsetChecker.State.UPGRADE); + assertThatThrownBy(() -> underTest.check(DatabaseCharsetChecker.State.UPGRADE)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("failure"); } @Test @@ -97,8 +94,8 @@ public class DatabaseCharsetCheckerTest { Dialect unsupportedDialect = mock(Dialect.class); when(unsupportedDialect.getId()).thenReturn("foo"); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Database not supported: foo"); - underTest.getHandler(unsupportedDialect); + assertThatThrownBy(() -> underTest.getHandler(unsupportedDialect)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Database not supported: foo"); } } diff --git a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/charset/MssqlCharsetHandlerTest.java b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/charset/MssqlCharsetHandlerTest.java index 83b8dc7f164..b706bfd2f1b 100644 --- a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/charset/MssqlCharsetHandlerTest.java +++ b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/charset/MssqlCharsetHandlerTest.java @@ -27,14 +27,13 @@ import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.stream.Stream; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.api.utils.MessageException; import static java.lang.String.format; import static java.util.Arrays.asList; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.same; @@ -51,8 +50,6 @@ public class MssqlCharsetHandlerTest { private static final String COLUMN_KEE = "kee"; private static final String COLUMN_NAME = "name"; - @Rule - public ExpectedException expectedException = ExpectedException.none(); private SqlExecutor sqlExecutor = mock(SqlExecutor.class); private MssqlMetadataReader metadata = mock(MssqlMetadataReader.class); @@ -72,18 +69,18 @@ public class MssqlCharsetHandlerTest { public void fresh_install_fails_if_default_collation_is_not_CS_AS() throws SQLException { answerDefaultCollation("Latin1_General_CI_AI"); - expectedException.expect(MessageException.class); - expectedException.expectMessage("Database collation must be case-sensitive and accent-sensitive. It is Latin1_General_CI_AI but should be Latin1_General_CS_AS."); - underTest.handle(connection, DatabaseCharsetChecker.State.FRESH_INSTALL); + assertThatThrownBy(() -> underTest.handle(connection, DatabaseCharsetChecker.State.FRESH_INSTALL)) + .isInstanceOf(MessageException.class) + .hasMessage("Database collation must be case-sensitive and accent-sensitive. It is Latin1_General_CI_AI but should be Latin1_General_CS_AS."); } @Test public void upgrade_fails_if_default_collation_is_not_CS_AS() throws SQLException { answerDefaultCollation("Latin1_General_CI_AI"); - expectedException.expect(MessageException.class); - expectedException.expectMessage("Database collation must be case-sensitive and accent-sensitive. It is Latin1_General_CI_AI but should be Latin1_General_CS_AS."); - underTest.handle(connection, DatabaseCharsetChecker.State.UPGRADE); + assertThatThrownBy(() -> underTest.handle(connection, DatabaseCharsetChecker.State.UPGRADE)) + .isInstanceOf(MessageException.class) + .hasMessage("Database collation must be case-sensitive and accent-sensitive. It is Latin1_General_CI_AI but should be Latin1_General_CS_AS."); } @Test diff --git a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/charset/OracleCharsetHandlerTest.java b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/charset/OracleCharsetHandlerTest.java index 653555f18ee..36bf08c570c 100644 --- a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/charset/OracleCharsetHandlerTest.java +++ b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/charset/OracleCharsetHandlerTest.java @@ -23,12 +23,11 @@ import java.sql.Connection; import java.sql.SQLException; import java.util.Collections; import javax.annotation.Nullable; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.utils.MessageException; import static java.util.Collections.singletonList; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; @@ -37,8 +36,6 @@ import static org.mockito.Mockito.when; public class OracleCharsetHandlerTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private SqlExecutor sqlExecutor = mock(SqlExecutor.class); private Connection connection = mock(Connection.class); @@ -69,19 +66,17 @@ public class OracleCharsetHandlerTest { public void fresh_install_fails_if_charset_is_not_utf8() throws Exception { answerCharset("LATIN"); - expectedException.expect(MessageException.class); - expectedException.expectMessage("Oracle NLS_CHARACTERSET does not support UTF8: LATIN"); - - underTest.handle(connection, DatabaseCharsetChecker.State.FRESH_INSTALL); + assertThatThrownBy(() -> underTest.handle(connection, DatabaseCharsetChecker.State.FRESH_INSTALL)) + .isInstanceOf(MessageException.class) + .hasMessage("Oracle NLS_CHARACTERSET does not support UTF8: LATIN"); } @Test public void fails_if_can_not_get_charset() throws Exception { answerCharset(null); - expectedException.expect(MessageException.class); - - underTest.handle(connection, DatabaseCharsetChecker.State.FRESH_INSTALL); + assertThatThrownBy(() -> underTest.handle(connection, DatabaseCharsetChecker.State.FRESH_INSTALL)) + .isInstanceOf(MessageException.class); } @Test diff --git a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/charset/PostgresCharsetHandlerTest.java b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/charset/PostgresCharsetHandlerTest.java index c19004f00d3..49270792f10 100644 --- a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/charset/PostgresCharsetHandlerTest.java +++ b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/charset/PostgresCharsetHandlerTest.java @@ -23,12 +23,11 @@ import java.sql.Connection; import java.sql.SQLException; import java.util.Arrays; import java.util.List; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.utils.MessageException; import static java.util.Arrays.asList; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.same; @@ -44,8 +43,6 @@ public class PostgresCharsetHandlerTest { private static final String COLUMN_KEE = "kee"; private static final String COLUMN_NAME = "name"; - @Rule - public ExpectedException expectedException = ExpectedException.none(); private SqlExecutor sqlExecutor = mock(SqlExecutor.class); private Connection connection = mock(Connection.class); @@ -106,10 +103,9 @@ public class PostgresCharsetHandlerTest { new String[] {TABLE_PROJECTS, COLUMN_KEE, "latin"}, new String[] {TABLE_PROJECTS, COLUMN_NAME, "latin"})); - expectedException.expect(MessageException.class); - expectedException.expectMessage("Database columns [projects.kee, projects.name] must have UTF8 charset."); - - underTest.handle(connection, DatabaseCharsetChecker.State.UPGRADE); + assertThatThrownBy(() -> underTest.handle(connection, DatabaseCharsetChecker.State.UPGRADE)) + .isInstanceOf(MessageException.class) + .hasMessage("Database columns [projects.kee, projects.name] must have UTF8 charset."); } @Test @@ -118,10 +114,9 @@ public class PostgresCharsetHandlerTest { answerColumns( Arrays.asList(new String[] {TABLE_ISSUES, COLUMN_KEE, "utf8"})); - expectedException.expect(MessageException.class); - expectedException.expectMessage("Database charset is latin. It must support UTF8."); - - underTest.handle(connection, DatabaseCharsetChecker.State.UPGRADE); + assertThatThrownBy(() -> underTest.handle(connection, DatabaseCharsetChecker.State.UPGRADE)) + .isInstanceOf(MessageException.class) + .hasMessage("Database charset is latin. It must support UTF8."); } private void answerDefaultCharset(String defaultCollation) throws SQLException { diff --git a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/def/BigIntegerColumnDefTest.java b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/def/BigIntegerColumnDefTest.java index dab4b22f77c..c0927fdd8b1 100644 --- a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/def/BigIntegerColumnDefTest.java +++ b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/def/BigIntegerColumnDefTest.java @@ -19,21 +19,16 @@ */ package org.sonar.server.platform.db.migration.def; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.db.dialect.H2; import org.sonar.db.dialect.MsSql; import org.sonar.db.dialect.Oracle; import org.sonar.db.dialect.PostgreSql; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class BigIntegerColumnDefTest { - - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void build_string_column_def() { BigIntegerColumnDef def = new BigIntegerColumnDef.Builder() @@ -70,20 +65,22 @@ public class BigIntegerColumnDefTest { @Test public void fail_with_NPE_if_name_is_null() { - thrown.expect(NullPointerException.class); - thrown.expectMessage("Column name cannot be null"); - - new BigIntegerColumnDef.Builder() - .setColumnName(null); + assertThatThrownBy(() -> { + new BigIntegerColumnDef.Builder() + .setColumnName(null); + }) + .isInstanceOf(NullPointerException.class) + .hasMessage("Column name cannot be null"); } @Test public void fail_with_NPE_if_no_name() { - thrown.expect(NullPointerException.class); - thrown.expectMessage("Column name cannot be null"); - - new BigIntegerColumnDef.Builder() - .build(); + assertThatThrownBy(() -> { + new BigIntegerColumnDef.Builder() + .build(); + }) + .isInstanceOf(NullPointerException.class) + .hasMessage("Column name cannot be null"); } } diff --git a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/def/BlobColumnDefTest.java b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/def/BlobColumnDefTest.java index 6b71f184e9f..6e138db928e 100644 --- a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/def/BlobColumnDefTest.java +++ b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/def/BlobColumnDefTest.java @@ -19,9 +19,7 @@ */ package org.sonar.server.platform.db.migration.def; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.db.dialect.Dialect; import org.sonar.db.dialect.H2; import org.sonar.db.dialect.MsSql; @@ -29,13 +27,12 @@ import org.sonar.db.dialect.Oracle; import org.sonar.db.dialect.PostgreSql; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.server.platform.db.migration.def.BlobColumnDef.newBlobColumnDefBuilder; public class BlobColumnDefTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private BlobColumnDef underTest = newBlobColumnDefBuilder().setColumnName("a").build(); @@ -43,19 +40,18 @@ public class BlobColumnDefTest { public void builder_setColumnName_throws_IAE_if_name_is_not_lowercase() { BlobColumnDef.Builder builder = newBlobColumnDefBuilder(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Column name must be lower case and contain only alphanumeric chars or '_', got 'T'"); - builder.setColumnName("T"); + assertThatThrownBy(() -> builder.setColumnName("T")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Column name must be lower case and contain only alphanumeric chars or '_', got 'T'"); } @Test public void builder_build_throws_NPE_if_no_name_was_set() { BlobColumnDef.Builder builder = newBlobColumnDefBuilder(); - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("Column name cannot be null"); - - builder.build(); + assertThatThrownBy(builder::build) + .isInstanceOf(NullPointerException.class) + .hasMessage("Column name cannot be null"); } @Test @@ -99,9 +95,8 @@ public class BlobColumnDefTest { Dialect dialect = mock(Dialect.class); when(dialect.getId()).thenReturn("AAA"); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Unsupported dialect id AAA"); - - underTest.generateSqlType(dialect); + assertThatThrownBy(() -> underTest.generateSqlType(dialect)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Unsupported dialect id AAA"); } } diff --git a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/def/BooleanColumnDefTest.java b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/def/BooleanColumnDefTest.java index 048f64519dd..02a6f7f4955 100644 --- a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/def/BooleanColumnDefTest.java +++ b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/def/BooleanColumnDefTest.java @@ -19,22 +19,16 @@ */ package org.sonar.server.platform.db.migration.def; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.db.dialect.H2; import org.sonar.db.dialect.MsSql; import org.sonar.db.dialect.Oracle; import org.sonar.db.dialect.PostgreSql; import static org.assertj.core.api.Assertions.assertThat; - +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class BooleanColumnDefTest { - - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void build_column_def() { BooleanColumnDef def = new BooleanColumnDef.Builder() @@ -74,19 +68,15 @@ public class BooleanColumnDefTest { @Test public void fail_with_NPE_if_name_is_null() { - thrown.expect(NullPointerException.class); - thrown.expectMessage("Column name cannot be null"); - - new BooleanColumnDef.Builder().setColumnName(null); + assertThatThrownBy(() -> new BooleanColumnDef.Builder().setColumnName(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("Column name cannot be null"); } @Test public void fail_with_NPE_if_no_name() { - thrown.expect(NullPointerException.class); - thrown.expectMessage("Column name cannot be null"); - - new BooleanColumnDef.Builder().build(); + assertThatThrownBy(() -> new BooleanColumnDef.Builder().build()) + .isInstanceOf(NullPointerException.class) + .hasMessage("Column name cannot be null"); } - - } diff --git a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/def/ClobColumnDefTest.java b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/def/ClobColumnDefTest.java index f039bbed60c..cd1ff90e2d3 100644 --- a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/def/ClobColumnDefTest.java +++ b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/def/ClobColumnDefTest.java @@ -19,20 +19,17 @@ */ package org.sonar.server.platform.db.migration.def; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.db.dialect.H2; import org.sonar.db.dialect.MsSql; import org.sonar.db.dialect.Oracle; import org.sonar.db.dialect.PostgreSql; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class ClobColumnDefTest { - @Rule - public ExpectedException thrown = ExpectedException.none(); private final ClobColumnDef underTest = new ClobColumnDef.Builder() .setColumnName("issues") .setIsNullable(true) @@ -78,19 +75,21 @@ public class ClobColumnDefTest { @Test public void fail_with_NPE_if_name_is_null() { - thrown.expect(NullPointerException.class); - thrown.expectMessage("Column name cannot be null"); - - new ClobColumnDef.Builder() - .setColumnName(null); + assertThatThrownBy(() -> { + new ClobColumnDef.Builder() + .setColumnName(null); + }) + .isInstanceOf(NullPointerException.class) + .hasMessage("Column name cannot be null"); } @Test public void fail_with_NPE_if_no_name() { - thrown.expect(NullPointerException.class); - thrown.expectMessage("Column name cannot be null"); - - new ClobColumnDef.Builder() - .build(); + assertThatThrownBy(() -> { + new ClobColumnDef.Builder() + .build(); + }) + .isInstanceOf(NullPointerException.class) + .hasMessage("Column name cannot be null"); } } diff --git a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/def/DecimalColumnDefTest.java b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/def/DecimalColumnDefTest.java index 40a98ef217e..211d380f4c8 100644 --- a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/def/DecimalColumnDefTest.java +++ b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/def/DecimalColumnDefTest.java @@ -19,9 +19,7 @@ */ package org.sonar.server.platform.db.migration.def; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.db.dialect.Dialect; import org.sonar.db.dialect.H2; import org.sonar.db.dialect.MsSql; @@ -29,14 +27,11 @@ import org.sonar.db.dialect.Oracle; import org.sonar.db.dialect.PostgreSql; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class DecimalColumnDefTest { - - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void build_string_column_def() { DecimalColumnDef def = new DecimalColumnDef.Builder() @@ -55,20 +50,22 @@ public class DecimalColumnDefTest { @Test public void fail_with_NPE_if_name_is_null() { - thrown.expect(NullPointerException.class); - thrown.expectMessage("Column name cannot be null"); - - new DecimalColumnDef.Builder() - .setColumnName(null); + assertThatThrownBy(() -> { + new DecimalColumnDef.Builder() + .setColumnName(null); + }) + .isInstanceOf(NullPointerException.class) + .hasMessage("Column name cannot be null"); } @Test public void fail_with_NPE_if_no_name() { - thrown.expect(NullPointerException.class); - thrown.expectMessage("Column name cannot be null"); - - new DecimalColumnDef.Builder() - .build(); + assertThatThrownBy(() -> { + new DecimalColumnDef.Builder() + .build(); + }) + .isInstanceOf(NullPointerException.class) + .hasMessage("Column name cannot be null"); } @Test @@ -122,19 +119,20 @@ public class DecimalColumnDefTest { @Test public void fail_with_UOE_to_generate_sql_type_when_unknown_dialect() { - thrown.expect(UnsupportedOperationException.class); - thrown.expectMessage("Unknown dialect 'unknown'"); - - DecimalColumnDef def = new DecimalColumnDef.Builder() - .setColumnName("issues") - .setPrecision(30) - .setScale(20) - .setIsNullable(true) - .build(); - - Dialect dialect = mock(Dialect.class); - when(dialect.getId()).thenReturn("unknown"); - def.generateSqlType(dialect); + assertThatThrownBy(() -> { + DecimalColumnDef def = new DecimalColumnDef.Builder() + .setColumnName("issues") + .setPrecision(30) + .setScale(20) + .setIsNullable(true) + .build(); + + Dialect dialect = mock(Dialect.class); + when(dialect.getId()).thenReturn("unknown"); + def.generateSqlType(dialect); + }) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessage("Unknown dialect 'unknown'"); } } diff --git a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/def/IntegerColumnDefTest.java b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/def/IntegerColumnDefTest.java index 16ac8c03e27..705684e95b4 100644 --- a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/def/IntegerColumnDefTest.java +++ b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/def/IntegerColumnDefTest.java @@ -19,9 +19,7 @@ */ package org.sonar.server.platform.db.migration.def; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.db.dialect.Dialect; import org.sonar.db.dialect.H2; import org.sonar.db.dialect.MsSql; @@ -29,13 +27,12 @@ import org.sonar.db.dialect.Oracle; import org.sonar.db.dialect.PostgreSql; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.server.platform.db.migration.def.IntegerColumnDef.newIntegerColumnDefBuilder; public class IntegerColumnDefTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private IntegerColumnDef underTest = newIntegerColumnDefBuilder().setColumnName("a").build(); @@ -43,19 +40,18 @@ public class IntegerColumnDefTest { public void builder_setColumnName_throws_IAE_if_name_is_not_lowercase() { IntegerColumnDef.Builder builder = newIntegerColumnDefBuilder(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Column name must be lower case and contain only alphanumeric chars or '_', got 'T'"); - builder.setColumnName("T"); + assertThatThrownBy(() -> builder.setColumnName("T")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Column name must be lower case and contain only alphanumeric chars or '_', got 'T'"); } @Test public void builder_build_throws_NPE_if_no_name_was_set() { IntegerColumnDef.Builder builder = newIntegerColumnDefBuilder(); - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("Column name cannot be null"); - - builder.build(); + assertThatThrownBy(builder::build) + .isInstanceOf(NullPointerException.class) + .hasMessage("Column name cannot be null"); } @Test @@ -109,10 +105,9 @@ public class IntegerColumnDefTest { Dialect dialect = mock(Dialect.class); when(dialect.getId()).thenReturn("AAA"); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Unsupported dialect id AAA"); - - underTest.generateSqlType(dialect); + assertThatThrownBy(() -> underTest.generateSqlType(dialect)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Unsupported dialect id AAA"); } } diff --git a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/def/TimestampColumnDefTest.java b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/def/TimestampColumnDefTest.java index ebc07ce2e49..8df55a055ff 100644 --- a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/def/TimestampColumnDefTest.java +++ b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/def/TimestampColumnDefTest.java @@ -19,23 +19,18 @@ */ package org.sonar.server.platform.db.migration.def; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.db.dialect.H2; import org.sonar.db.dialect.MsSql; import org.sonar.db.dialect.Oracle; import org.sonar.db.dialect.PostgreSql; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.server.platform.db.migration.def.TimestampColumnDef.newTimestampColumnDefBuilder; @SuppressWarnings("deprecation") public class TimestampColumnDefTest { - - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void build_column_def() { TimestampColumnDef def = newTimestampColumnDefBuilder() @@ -73,17 +68,15 @@ public class TimestampColumnDefTest { @Test public void fail_with_NPE_if_name_is_null() { - thrown.expect(NullPointerException.class); - thrown.expectMessage("Column name cannot be null"); - - newTimestampColumnDefBuilder().setColumnName(null); + assertThatThrownBy(() -> newTimestampColumnDefBuilder().setColumnName(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("Column name cannot be null"); } @Test public void fail_with_NPE_if_no_name() { - thrown.expect(NullPointerException.class); - thrown.expectMessage("Column name cannot be null"); - - newTimestampColumnDefBuilder().build(); + assertThatThrownBy(() -> newTimestampColumnDefBuilder().build()) + .isInstanceOf(NullPointerException.class) + .hasMessage("Column name cannot be null"); } } diff --git a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/def/TinyIntColumnDefTest.java b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/def/TinyIntColumnDefTest.java index a6250d00b22..a7009851d2d 100644 --- a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/def/TinyIntColumnDefTest.java +++ b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/def/TinyIntColumnDefTest.java @@ -19,9 +19,7 @@ */ package org.sonar.server.platform.db.migration.def; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.db.dialect.Dialect; import org.sonar.db.dialect.H2; import org.sonar.db.dialect.MsSql; @@ -29,14 +27,11 @@ import org.sonar.db.dialect.Oracle; import org.sonar.db.dialect.PostgreSql; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class TinyIntColumnDefTest { - - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void build_string_column_def() { TinyIntColumnDef def = new TinyIntColumnDef.Builder() @@ -64,16 +59,17 @@ public class TinyIntColumnDefTest { @Test public void fail_with_UOE_to_generate_sql_type_when_unknown_dialect() { - thrown.expect(UnsupportedOperationException.class); - thrown.expectMessage("Unknown dialect 'unknown'"); - - TinyIntColumnDef def = new TinyIntColumnDef.Builder() - .setColumnName("foo") - .setIsNullable(true) - .build(); + assertThatThrownBy(() -> { + TinyIntColumnDef def = new TinyIntColumnDef.Builder() + .setColumnName("foo") + .setIsNullable(true) + .build(); - Dialect dialect = mock(Dialect.class); - when(dialect.getId()).thenReturn("unknown"); - def.generateSqlType(dialect); + Dialect dialect = mock(Dialect.class); + when(dialect.getId()).thenReturn("unknown"); + def.generateSqlType(dialect); + }) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessage("Unknown dialect 'unknown'"); } } diff --git a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/def/ValidationsTest.java b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/def/ValidationsTest.java index 1fa54d5c6c4..49f0487808d 100644 --- a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/def/ValidationsTest.java +++ b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/def/ValidationsTest.java @@ -19,19 +19,14 @@ */ package org.sonar.server.platform.db.migration.def; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.server.platform.db.migration.def.Validations.validateColumnName; import static org.sonar.server.platform.db.migration.def.Validations.validateIndexName; public class ValidationsTest { - - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void accept_valid_table_name() { validateColumnName("date_in_ms"); @@ -40,42 +35,37 @@ public class ValidationsTest { @Test public void fail_with_NPE_if_name_is_null() { - thrown.expect(NullPointerException.class); - thrown.expectMessage("Column name cannot be null"); - - validateColumnName(null); + assertThatThrownBy(() -> validateColumnName(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("Column name cannot be null"); } @Test public void fail_when_column_name_is_in_upper_case() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Column name must be lower case and contain only alphanumeric chars or '_', got 'DATE_IN_MS'"); - - validateColumnName("DATE_IN_MS"); + assertThatThrownBy(() -> validateColumnName("DATE_IN_MS")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Column name must be lower case and contain only alphanumeric chars or '_', got 'DATE_IN_MS'"); } @Test public void fail_when_column_name_contains_invalid_character() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Column name must be lower case and contain only alphanumeric chars or '_', got 'date-in/ms'"); - - validateColumnName("date-in/ms"); + assertThatThrownBy(() -> validateColumnName("date-in/ms")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Column name must be lower case and contain only alphanumeric chars or '_', got 'date-in/ms'"); } @Test public void validateIndexName_throws_IAE_when_index_name_contains_invalid_characters() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Index name must be lower case and contain only alphanumeric chars or '_', got '(not/valid)'"); - - validateIndexName("(not/valid)"); + assertThatThrownBy(() -> validateIndexName("(not/valid)")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Index name must be lower case and contain only alphanumeric chars or '_', got '(not/valid)'"); } @Test public void validateIndexName_throws_NPE_when_index_name_is_null() { - thrown.expect(NullPointerException.class); - thrown.expectMessage("Index name can't be null"); - - validateIndexName(null); + assertThatThrownBy(() -> validateIndexName(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("Index name can't be null"); } @Test diff --git a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/def/VarcharColumnDefTest.java b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/def/VarcharColumnDefTest.java index cecbc1e245f..95ad8fa0967 100644 --- a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/def/VarcharColumnDefTest.java +++ b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/def/VarcharColumnDefTest.java @@ -19,21 +19,16 @@ */ package org.sonar.server.platform.db.migration.def; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.db.dialect.H2; import org.sonar.db.dialect.MsSql; import org.sonar.db.dialect.Oracle; import org.sonar.db.dialect.PostgreSql; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class VarcharColumnDefTest { - - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void build_string_column_def() { VarcharColumnDef def = new VarcharColumnDef.Builder() @@ -90,29 +85,32 @@ public class VarcharColumnDefTest { @Test public void fail_with_NPE_if_name_is_null() { - thrown.expect(NullPointerException.class); - thrown.expectMessage("Column name cannot be null"); - - new VarcharColumnDef.Builder() - .setColumnName(null); + assertThatThrownBy(() -> { + new VarcharColumnDef.Builder() + .setColumnName(null); + }) + .isInstanceOf(NullPointerException.class) + .hasMessage("Column name cannot be null"); } @Test public void fail_with_NPE_if_no_name() { - thrown.expect(NullPointerException.class); - thrown.expectMessage("Column name cannot be null"); - - new VarcharColumnDef.Builder() - .build(); + assertThatThrownBy(() -> { + new VarcharColumnDef.Builder() + .build(); + }) + .isInstanceOf(NullPointerException.class) + .hasMessage("Column name cannot be null"); } @Test public void fail_with_NPE_if_size_is_null() { - thrown.expect(NullPointerException.class); - thrown.expectMessage("Limit cannot be null"); - - new VarcharColumnDef.Builder() - .setColumnName("issues") - .build(); + assertThatThrownBy(() -> { + new VarcharColumnDef.Builder() + .setColumnName("issues") + .build(); + }) + .isInstanceOf(NullPointerException.class) + .hasMessage("Limit cannot be null"); } } diff --git a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/history/MigrationHistoryImplTest.java b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/history/MigrationHistoryImplTest.java index 013aa65fbe4..49d3574970f 100644 --- a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/history/MigrationHistoryImplTest.java +++ b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/history/MigrationHistoryImplTest.java @@ -25,20 +25,18 @@ import java.sql.SQLException; import java.util.Arrays; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.db.CoreDbTester; import org.sonar.server.platform.db.migration.step.MigrationStep; import org.sonar.server.platform.db.migration.step.RegisteredMigrationStep; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; public class MigrationHistoryImplTest { @Rule public CoreDbTester dbTester = CoreDbTester.createForSchema(MigrationHistoryImplTest.class, "schema_migration.sql"); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private MigrationHistoryMeddler migrationHistoryMeddler = mock(MigrationHistoryMeddler.class); private MigrationHistoryImpl underTest = new MigrationHistoryImpl(dbTester.database(), migrationHistoryMeddler); @@ -64,9 +62,8 @@ public class MigrationHistoryImplTest { @Test public void done_fails_with_NPE_if_argument_is_null() { - expectedException.expect(NullPointerException.class); - - underTest.done(null); + assertThatThrownBy(() -> underTest.done(null)) + .isInstanceOf(NullPointerException.class); } @Test diff --git a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/history/MigrationHistoryTableImplTest.java b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/history/MigrationHistoryTableImplTest.java index 8585cc51687..9e8ba09610b 100644 --- a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/history/MigrationHistoryTableImplTest.java +++ b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/history/MigrationHistoryTableImplTest.java @@ -25,7 +25,6 @@ import java.sql.Statement; import java.sql.Types; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.db.CoreDbTester; import static org.assertj.core.api.Assertions.assertThat; @@ -35,8 +34,6 @@ public class MigrationHistoryTableImplTest { @Rule public CoreDbTester dbTester = CoreDbTester.createEmpty(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private MigrationHistoryTableImpl underTest = new MigrationHistoryTableImpl(dbTester.database()); diff --git a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/history/NoTableMigrationHistoryImplTest.java b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/history/NoTableMigrationHistoryImplTest.java index 5aa73d7902d..c0305074c7d 100644 --- a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/history/NoTableMigrationHistoryImplTest.java +++ b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/history/NoTableMigrationHistoryImplTest.java @@ -21,30 +21,26 @@ package org.sonar.server.platform.db.migration.history; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.db.CoreDbTester; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyZeroInteractions; public class NoTableMigrationHistoryImplTest { @Rule public CoreDbTester dbTester = CoreDbTester.createEmpty(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private MigrationHistoryMeddler migrationHistoryMeddler = mock(MigrationHistoryMeddler.class); private MigrationHistoryImpl underTest = new MigrationHistoryImpl(dbTester.database(), migrationHistoryMeddler); @Test public void start_fails_with_ISE_if_table_history_does_not_exist() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Migration history table is missing"); - - underTest.start(); - - verifyZeroInteractions(migrationHistoryMeddler); + assertThatThrownBy(() -> { + underTest.start(); + verifyZeroInteractions(migrationHistoryMeddler); + }) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Migration history table is missing"); } - - } diff --git a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/AddColumnsBuilderTest.java b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/AddColumnsBuilderTest.java index fec487f7174..2165d244e7f 100644 --- a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/AddColumnsBuilderTest.java +++ b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/AddColumnsBuilderTest.java @@ -19,9 +19,7 @@ */ package org.sonar.server.platform.db.migration.sql; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.db.dialect.Dialect; import org.sonar.db.dialect.H2; import org.sonar.db.dialect.MsSql; @@ -31,16 +29,13 @@ import org.sonar.server.platform.db.migration.def.BigIntegerColumnDef; import org.sonar.server.platform.db.migration.def.VarcharColumnDef; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.server.platform.db.migration.def.BooleanColumnDef.newBooleanColumnDefBuilder; import static org.sonar.server.platform.db.migration.def.VarcharColumnDef.newVarcharColumnDefBuilder; public class AddColumnsBuilderTest { private static final String TABLE_NAME = "issues"; - - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void add_columns_on_h2() { assertThat(createSampleBuilder(new H2()).build()) @@ -67,10 +62,10 @@ public class AddColumnsBuilderTest { @Test public void fail_with_ISE_if_no_column() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("No column has been defined"); + assertThatThrownBy(() -> new AddColumnsBuilder(new H2(), TABLE_NAME).build()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("No column has been defined"); - new AddColumnsBuilder(new H2(), TABLE_NAME).build(); } private AddColumnsBuilder createSampleBuilder(Dialect dialect) { diff --git a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/AlterColumnsBuilderTest.java b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/AlterColumnsBuilderTest.java index 16559111a0e..446b2131f04 100644 --- a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/AlterColumnsBuilderTest.java +++ b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/AlterColumnsBuilderTest.java @@ -19,9 +19,7 @@ */ package org.sonar.server.platform.db.migration.sql; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.db.dialect.Dialect; import org.sonar.db.dialect.H2; import org.sonar.db.dialect.MsSql; @@ -30,6 +28,7 @@ import org.sonar.db.dialect.PostgreSql; import org.sonar.server.platform.db.migration.def.BooleanColumnDef; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.server.platform.db.migration.def.BooleanColumnDef.newBooleanColumnDefBuilder; import static org.sonar.server.platform.db.migration.def.DecimalColumnDef.newDecimalColumnDefBuilder; import static org.sonar.server.platform.db.migration.def.VarcharColumnDef.newVarcharColumnDefBuilder; @@ -37,8 +36,6 @@ import static org.sonar.server.platform.db.migration.def.VarcharColumnDef.newVar public class AlterColumnsBuilderTest { private static final String TABLE_NAME = "issues"; - @Rule - public ExpectedException thrown = ExpectedException.none(); @Test public void update_columns_on_h2() { @@ -98,10 +95,9 @@ public class AlterColumnsBuilderTest { @Test public void fail_with_ISE_if_no_column() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("No column has been defined"); - - new AlterColumnsBuilder(new H2(), TABLE_NAME).build(); + assertThatThrownBy(() -> new AlterColumnsBuilder(new H2(), TABLE_NAME).build()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("No column has been defined"); } /** @@ -117,10 +113,9 @@ public class AlterColumnsBuilderTest { .build(); AlterColumnsBuilder alterColumnsBuilder = new AlterColumnsBuilder(new H2(), TABLE_NAME); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Default value is not supported on alter of column 'enabled'"); - - alterColumnsBuilder.updateColumn(column); + assertThatThrownBy(() -> alterColumnsBuilder.updateColumn(column)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Default value is not supported on alter of column 'enabled'"); } private AlterColumnsBuilder createSampleBuilder(Dialect dialect) { diff --git a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/CreateIndexBuilderTest.java b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/CreateIndexBuilderTest.java index 4a3bf5c146b..659aca617e8 100644 --- a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/CreateIndexBuilderTest.java +++ b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/CreateIndexBuilderTest.java @@ -20,18 +20,13 @@ package org.sonar.server.platform.db.migration.sql; import java.util.List; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.server.platform.db.migration.def.VarcharColumnDef.newVarcharColumnDefBuilder; public class CreateIndexBuilderTest { - - @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Test public void create_index_on_single_column() { verifySql(new CreateIndexBuilder() @@ -83,59 +78,64 @@ public class CreateIndexBuilderTest { @Test public void throw_NPE_if_table_is_missing() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("Table name can't be null"); - - new CreateIndexBuilder() - .setName("issues_key") - .addColumn(newVarcharColumnDefBuilder().setColumnName("kee").setLimit(10).build()) - .build(); + assertThatThrownBy(() -> { + new CreateIndexBuilder() + .setName("issues_key") + .addColumn(newVarcharColumnDefBuilder().setColumnName("kee").setLimit(10).build()) + .build(); + }) + .isInstanceOf(NullPointerException.class) + .hasMessage("Table name can't be null"); } @Test public void throw_NPE_if_index_name_is_missing() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("Index name can't be null"); - - new CreateIndexBuilder() - .setTable("issues") - .addColumn(newVarcharColumnDefBuilder().setColumnName("kee").setLimit(10).build()) - .build(); + assertThatThrownBy(() -> { + new CreateIndexBuilder() + .setTable("issues") + .addColumn(newVarcharColumnDefBuilder().setColumnName("kee").setLimit(10).build()) + .build(); + }) + .isInstanceOf(NullPointerException.class) + .hasMessage("Index name can't be null"); } @Test public void throw_IAE_if_columns_are_missing() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("at least one column must be specified"); - - new CreateIndexBuilder() - .setTable("issues") - .setName("issues_key") - .build(); + assertThatThrownBy(() -> { + new CreateIndexBuilder() + .setTable("issues") + .setName("issues_key") + .build(); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("at least one column must be specified"); } @Test public void throw_IAE_if_table_name_is_not_valid() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Table name must be lower case and contain only alphanumeric chars or '_', got '(not valid)'"); - - new CreateIndexBuilder() - .setTable("(not valid)") - .setName("issues_key") - .addColumn(newVarcharColumnDefBuilder().setColumnName("kee").setLimit(10).build()) - .build(); + assertThatThrownBy(() -> { + new CreateIndexBuilder() + .setTable("(not valid)") + .setName("issues_key") + .addColumn(newVarcharColumnDefBuilder().setColumnName("kee").setLimit(10).build()) + .build(); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Table name must be lower case and contain only alphanumeric chars or '_', got '(not valid)'"); } @Test public void throw_NPE_when_adding_null_column() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("Column cannot be null"); - - new CreateIndexBuilder() - .setTable("issues") - .setName("issues_key") - .addColumn((String) null) - .build(); + assertThatThrownBy(() -> { + new CreateIndexBuilder() + .setTable("issues") + .setName("issues_key") + .addColumn((String) null) + .build(); + }) + .isInstanceOf(NullPointerException.class) + .hasMessage("Column cannot be null"); } private static void verifySql(CreateIndexBuilder builder, String expectedSql) { diff --git a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/CreateTableAsBuilderTest.java b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/CreateTableAsBuilderTest.java index 493efc4949f..4e9211c009c 100644 --- a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/CreateTableAsBuilderTest.java +++ b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/CreateTableAsBuilderTest.java @@ -20,9 +20,7 @@ package org.sonar.server.platform.db.migration.sql; import java.util.List; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.db.dialect.Dialect; import org.sonar.db.dialect.H2; import org.sonar.db.dialect.MsSql; @@ -30,11 +28,10 @@ import org.sonar.db.dialect.Oracle; import org.sonar.db.dialect.PostgreSql; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.server.platform.db.migration.def.VarcharColumnDef.newVarcharColumnDefBuilder; public class CreateTableAsBuilderTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void create_table() { @@ -59,18 +56,18 @@ public class CreateTableAsBuilderTest { "ALTER TABLE issues_copy ALTER COLUMN rule_uuid TYPE VARCHAR (40), ALTER COLUMN rule_uuid SET NOT NULL"); } - @Test public void fail_if_columns_not_set() { - expectedException.expect(IllegalStateException.class); - new CreateTableAsBuilder(new H2(), "issues_copy", "issues") - .build(); + assertThatThrownBy(() -> new CreateTableAsBuilder(new H2(), "issues_copy", "issues") + .build()) + .isInstanceOf(IllegalStateException.class); } @Test public void fail_if_table_not_set() { - expectedException.expect(NullPointerException.class); - new CreateTableAsBuilder(new H2(), null, "issues"); + assertThatThrownBy(() -> new CreateTableAsBuilder(new H2(), null, "issues") + .build()) + .isInstanceOf(NullPointerException.class); } private static void verifySqlWithCast(Dialect dialect, String... expectedSql) { diff --git a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/CreateTableBuilderTest.java b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/CreateTableBuilderTest.java index 6a80d515be8..428e66565c5 100644 --- a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/CreateTableBuilderTest.java +++ b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/CreateTableBuilderTest.java @@ -24,9 +24,7 @@ import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.Arrays; import java.util.List; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.db.dialect.Dialect; import org.sonar.db.dialect.H2; @@ -37,6 +35,7 @@ import org.sonar.server.platform.db.migration.def.ColumnDef; import org.sonar.server.platform.db.migration.def.TinyIntColumnDef; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.fail; import static org.mockito.Mockito.mock; import static org.sonar.server.platform.db.migration.def.BigIntegerColumnDef.newBigIntegerColumnDefBuilder; @@ -56,42 +55,34 @@ public class CreateTableBuilderTest { private static final MsSql MS_SQL = new MsSql(); private static final Dialect[] ALL_DIALECTS = {H2, MS_SQL, POSTGRESQL, ORACLE}; private static final String TABLE_NAME = "table_42"; - - @Rule - public ExpectedException expectedException = ExpectedException.none(); - private CreateTableBuilder underTest = new CreateTableBuilder(mock(Dialect.class), TABLE_NAME); @Test public void constructor_fails_with_NPE_if_dialect_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("dialect can't be null"); - - new CreateTableBuilder(null, TABLE_NAME); + assertThatThrownBy(() -> new CreateTableBuilder(null, TABLE_NAME)) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("dialect can't be null"); } @Test public void constructor_fails_with_NPE_if_tablename_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("Table name can't be null"); - - new CreateTableBuilder(mock(Dialect.class), null); + assertThatThrownBy(() -> new CreateTableBuilder(mock(Dialect.class), null)) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("Table name can't be null"); } @Test public void constructor_throws_IAE_if_table_name_is_not_lowercase() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Table name must be lower case and contain only alphanumeric chars or '_', got 'Tooo"); - - new CreateTableBuilder(mock(Dialect.class), "Tooo"); + assertThatThrownBy(() -> new CreateTableBuilder(mock(Dialect.class), "Tooo")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Table name must be lower case and contain only alphanumeric chars or '_', got 'Tooo"); } @Test public void constructor_throws_IAE_if_table_name_is_26_chars_long() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Table name length can't be more than 25"); - - new CreateTableBuilder(mock(Dialect.class), "abcdefghijklmnopqrstuvwxyz"); + assertThatThrownBy(() -> new CreateTableBuilder(mock(Dialect.class), "abcdefghijklmnopqrstuvwxyz")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Table name length can't be more than 25"); } @Test @@ -107,19 +98,17 @@ public class CreateTableBuilderTest { @Test public void constructor_throws_IAE_if_table_name_starts_with_underscore() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Table name must not start by a number or '_', got '_a'"); - - new CreateTableBuilder(mock(Dialect.class), "_a"); + assertThatThrownBy(() -> new CreateTableBuilder(mock(Dialect.class), "_a")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Table name must not start by a number or '_', got '_a'"); } @Test @UseDataProvider("digitCharsDataProvider") public void constructor_throws_IAE_if_table_name_starts_with_number(char number) { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Table name must not start by a number or '_', got '" + number + "a'"); - - new CreateTableBuilder(mock(Dialect.class), number + "a"); + assertThatThrownBy(() -> new CreateTableBuilder(mock(Dialect.class), number + "a")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Table name must not start by a number or '_', got '" + number + "a'"); } @DataProvider @@ -146,44 +135,39 @@ public class CreateTableBuilderTest { @Test public void build_throws_ISE_if_no_column_has_been_set() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("at least one column must be specified"); - - underTest.build(); + assertThatThrownBy(() -> underTest.build()) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("at least one column must be specified"); } @Test public void addColumn_throws_NPE_if_ColumnDef_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("column def can't be null"); - - underTest.addColumn(null); + assertThatThrownBy(() -> underTest.addColumn(null)) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("column def can't be null"); } @Test public void addPkColumn_throws_NPE_if_ColumnDef_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("column def can't be null"); - - underTest.addPkColumn(null); + assertThatThrownBy(() -> underTest.addPkColumn(null)) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("column def can't be null"); } @Test public void addPkColumn_throws_IAE_when_AUTO_INCREMENT_flag_is_provided_with_column_name_other_than_id() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Auto increment column name must be id"); - - underTest.addPkColumn(newIntegerColumnDefBuilder().setColumnName("toto").build(), AUTO_INCREMENT); + assertThatThrownBy(() -> underTest.addPkColumn(newIntegerColumnDefBuilder().setColumnName("toto").build(), AUTO_INCREMENT)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Auto increment column name must be id"); } @Test public void addPkColumn_throws_ISE_when_adding_multiple_autoincrement_columns() { underTest.addPkColumn(newIntegerColumnDefBuilder().setColumnName("id").setIsNullable(false).build(), AUTO_INCREMENT); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("There can't be more than one auto increment column"); - - underTest.addPkColumn(newIntegerColumnDefBuilder().setColumnName("id").setIsNullable(false).build(), AUTO_INCREMENT); + assertThatThrownBy(() -> underTest.addPkColumn(newIntegerColumnDefBuilder().setColumnName("id").setIsNullable(false).build(), AUTO_INCREMENT)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("There can't be more than one auto increment column"); } @Test @@ -291,43 +275,38 @@ public class CreateTableBuilderTest { @Test public void withPkConstraintName_throws_NPE_if_name_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("Constraint name can't be null"); - - underTest.withPkConstraintName(null); + assertThatThrownBy(() -> underTest.withPkConstraintName(null)) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("Constraint name can't be null"); } @Test public void withPkConstraintName_throws_IAE_if_name_is_not_lowercase() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Constraint name must be lower case and contain only alphanumeric chars or '_', got 'Too'"); - - underTest.withPkConstraintName("Too"); + assertThatThrownBy(() -> underTest.withPkConstraintName("Too")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Constraint name must be lower case and contain only alphanumeric chars or '_', got 'Too'"); } @Test public void withPkConstraintName_throws_IAE_if_name_is_more_than_30_char_long() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Constraint name length can't be more than 30"); - - underTest.withPkConstraintName("abcdefghijklmnopqrstuvwxyzabcdf"); + assertThatThrownBy(() -> underTest.withPkConstraintName("abcdefghijklmnopqrstuvwxyzabcdf")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Constraint name length can't be more than 30"); } @Test public void withPkConstraintName_throws_IAE_if_name_starts_with_underscore() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Constraint name must not start by a number or '_', got '_a'"); - - underTest.withPkConstraintName("_a"); + assertThatThrownBy(() -> underTest.withPkConstraintName("_a")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Constraint name must not start by a number or '_', got '_a'"); } @Test @UseDataProvider("digitCharsDataProvider") public void withPkConstraintName_throws_IAE_if_name_starts_with_number(char number) { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Constraint name must not start by a number or '_', got '" + number + "a'"); - - underTest.withPkConstraintName(number + "a"); + assertThatThrownBy(() -> underTest.withPkConstraintName(number + "a")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Constraint name must not start by a number or '_', got '" + number + "a'"); } @Test diff --git a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/DbPrimaryKeyConstraintFinderTest.java b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/DbPrimaryKeyConstraintFinderTest.java index ce68bdd0f0d..6e41ef1588f 100644 --- a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/DbPrimaryKeyConstraintFinderTest.java +++ b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/DbPrimaryKeyConstraintFinderTest.java @@ -33,7 +33,6 @@ import org.sonar.db.dialect.Oracle; import org.sonar.db.dialect.PostgreSql; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; diff --git a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/DropMsSQLDefaultConstraintsBuilderTest.java b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/DropMsSQLDefaultConstraintsBuilderTest.java index 9aa6d65b95d..2e7c4f988c7 100644 --- a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/DropMsSQLDefaultConstraintsBuilderTest.java +++ b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/DropMsSQLDefaultConstraintsBuilderTest.java @@ -29,9 +29,9 @@ import org.sonar.db.dialect.H2; import org.sonar.db.dialect.MsSql; import org.sonar.db.dialect.Oracle; import org.sonar.db.dialect.PostgreSql; -import org.sonar.server.platform.db.migration.sql.DropMsSQLDefaultConstraintsBuilder; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -40,22 +40,31 @@ public class DropMsSQLDefaultConstraintsBuilderTest { private final Database db = mock(Database.class); - @Test(expected = IllegalArgumentException.class) + @Test public void fail_if_oracle() throws Exception { when(db.getDialect()).thenReturn(new Oracle()); - new DropMsSQLDefaultConstraintsBuilder(db).setTable("snapshots").setColumns("variation_value_2", "variation_value_3").build(); + assertThatThrownBy(() -> { + new DropMsSQLDefaultConstraintsBuilder(db).setTable("snapshots").setColumns("variation_value_2", "variation_value_3").build(); + }) + .isInstanceOf(IllegalArgumentException.class); } - @Test(expected = IllegalArgumentException.class) + @Test public void fail_if_h2() throws Exception { when(db.getDialect()).thenReturn(new H2()); - new DropMsSQLDefaultConstraintsBuilder(db).setTable("snapshots").setColumns("variation_value_2", "variation_value_3").build(); + assertThatThrownBy(() -> { + new DropMsSQLDefaultConstraintsBuilder(db).setTable("snapshots").setColumns("variation_value_2", "variation_value_3").build(); + }) + .isInstanceOf(IllegalArgumentException.class); } - @Test(expected = IllegalArgumentException.class) + @Test public void fail_if_postgres() throws Exception { when(db.getDialect()).thenReturn(new PostgreSql()); - new DropMsSQLDefaultConstraintsBuilder(db).setTable("snapshots").setColumns("variation_value_2", "variation_value_3").build(); + assertThatThrownBy(() -> { + new DropMsSQLDefaultConstraintsBuilder(db).setTable("snapshots").setColumns("variation_value_2", "variation_value_3").build(); + }) + .isInstanceOf(IllegalArgumentException.class); } @Test diff --git a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/DropTableBuilderTest.java b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/DropTableBuilderTest.java index d78246d2e78..2aa93aa7735 100644 --- a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/DropTableBuilderTest.java +++ b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/DropTableBuilderTest.java @@ -19,21 +19,16 @@ */ package org.sonar.server.platform.db.migration.sql; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.db.dialect.H2; import org.sonar.db.dialect.MsSql; import org.sonar.db.dialect.Oracle; import org.sonar.db.dialect.PostgreSql; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class DropTableBuilderTest { - - @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Test public void drop_tables_on_postgresql() { assertThat(new DropTableBuilder(new PostgreSql(), "issues") @@ -56,41 +51,41 @@ public class DropTableBuilderTest { public void drop_columns_on_oracle() { assertThat(new DropTableBuilder(new Oracle(), "issues") .build()).containsExactly( - "BEGIN\n" + - "EXECUTE IMMEDIATE 'DROP SEQUENCE issues_seq';\n" + - "EXCEPTION\n" + - "WHEN OTHERS THEN\n" + - " IF SQLCODE != -2289 THEN\n" + - " RAISE;\n" + - " END IF;\n" + - "END;", - "BEGIN\n" + - "EXECUTE IMMEDIATE 'DROP TRIGGER issues_idt';\n" + - "EXCEPTION\n" + - "WHEN OTHERS THEN\n" + - " IF SQLCODE != -4080 THEN\n" + - " RAISE;\n" + - " END IF;\n" + - "END;", - "BEGIN\n" + - "EXECUTE IMMEDIATE 'DROP TABLE issues';\n" + - "EXCEPTION\n" + - "WHEN OTHERS THEN\n" + - " IF SQLCODE != -942 THEN\n" + - " RAISE;\n" + - " END IF;\n" + - "END;"); + "BEGIN\n" + + "EXECUTE IMMEDIATE 'DROP SEQUENCE issues_seq';\n" + + "EXCEPTION\n" + + "WHEN OTHERS THEN\n" + + " IF SQLCODE != -2289 THEN\n" + + " RAISE;\n" + + " END IF;\n" + + "END;", + "BEGIN\n" + + "EXECUTE IMMEDIATE 'DROP TRIGGER issues_idt';\n" + + "EXCEPTION\n" + + "WHEN OTHERS THEN\n" + + " IF SQLCODE != -4080 THEN\n" + + " RAISE;\n" + + " END IF;\n" + + "END;", + "BEGIN\n" + + "EXECUTE IMMEDIATE 'DROP TABLE issues';\n" + + "EXCEPTION\n" + + "WHEN OTHERS THEN\n" + + " IF SQLCODE != -942 THEN\n" + + " RAISE;\n" + + " END IF;\n" + + "END;"); } @Test public void fail_when_dialect_is_null() { - expectedException.expect(NullPointerException.class); - new DropTableBuilder(null, "issues"); + assertThatThrownBy(() -> new DropTableBuilder(null, "issues")) + .isInstanceOf(NullPointerException.class); } @Test public void fail_when_table_is_null() { - expectedException.expect(NullPointerException.class); - new DropTableBuilder(new PostgreSql(), null); + assertThatThrownBy(() -> new DropTableBuilder(new PostgreSql(), null)) + .isInstanceOf(NullPointerException.class); } } diff --git a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/RenameColumnsBuilderTest.java b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/RenameColumnsBuilderTest.java index ee6f7be1da8..c1faf74cd3c 100644 --- a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/RenameColumnsBuilderTest.java +++ b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/RenameColumnsBuilderTest.java @@ -23,12 +23,10 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang.text.StrSubstitutor; -import org.junit.Rule; import org.junit.experimental.theories.DataPoints; import org.junit.experimental.theories.FromDataPoints; import org.junit.experimental.theories.Theories; import org.junit.experimental.theories.Theory; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.db.dialect.Dialect; import org.sonar.db.dialect.H2; @@ -47,13 +45,10 @@ import org.sonar.server.platform.db.migration.def.VarcharColumnDef; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; @RunWith(Theories.class) public class RenameColumnsBuilderTest { - - @Rule - public ExpectedException expectedException = ExpectedException.none(); - private static final String NEW_COLUMN_NAME = "new_" + randomAlphabetic(6).toLowerCase(); @DataPoints("database") @@ -116,33 +111,31 @@ public class RenameColumnsBuilderTest { } @Theory - public void when_old_column_is_same_as_new_column_ISA_is_thrown ( + public void when_old_column_is_same_as_new_column_ISA_is_thrown( @FromDataPoints("database") DatabaseAndResult database, @FromDataPoints("columnDef") ColumnDef columnDef) { String tableName = "table_" + randomAlphabetic(6).toLowerCase(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Column names must be different"); - - new RenameColumnsBuilder(database.getDialect(), tableName) + assertThatThrownBy(() -> new RenameColumnsBuilder(database.getDialect(), tableName) .renameColumn(NEW_COLUMN_NAME, columnDef) - .build(); + .build()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Column names must be different"); } @Theory - public void when_new_column_contains_illegal_character_ISA_is_thrown ( + public void when_new_column_contains_illegal_character_ISA_is_thrown( @FromDataPoints("database") DatabaseAndResult database, @FromDataPoints("columnDef") ColumnDef columnDef, @FromDataPoints("illegalColumnName") String illegalColumnName) { String tableName = "table_" + randomAlphabetic(6).toLowerCase(); - expectedException.expect(IllegalArgumentException.class); - - new RenameColumnsBuilder(database.getDialect(), tableName) + assertThatThrownBy(() -> new RenameColumnsBuilder(database.getDialect(), tableName) .renameColumn(illegalColumnName, columnDef) - .build(); + .build()) + .isInstanceOf(IllegalArgumentException.class); } private static class DatabaseAndResult { diff --git a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/RenameTableBuilderTest.java b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/RenameTableBuilderTest.java index d639bd23c52..70b1d6dcd93 100644 --- a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/RenameTableBuilderTest.java +++ b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/sql/RenameTableBuilderTest.java @@ -20,9 +20,7 @@ package org.sonar.server.platform.db.migration.sql; import java.util.List; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.db.dialect.Dialect; import org.sonar.db.dialect.H2; import org.sonar.db.dialect.MsSql; @@ -30,12 +28,9 @@ import org.sonar.db.dialect.Oracle; import org.sonar.db.dialect.PostgreSql; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class RenameTableBuilderTest { - - @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Test public void rename_table_on_h2() { verifySql(new H2(), "ALTER TABLE foo RENAME TO bar"); @@ -67,18 +62,16 @@ public class RenameTableBuilderTest { @Test public void throw_IAE_if_name_is_not_valid() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Table name must be lower case and contain only alphanumeric chars or '_', got '(not valid)'"); - - new RenameTableBuilder(new H2()).setName("(not valid)").build(); + assertThatThrownBy(() -> new RenameTableBuilder(new H2()).setName("(not valid)").build()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Table name must be lower case and contain only alphanumeric chars or '_', got '(not valid)'"); } @Test public void throw_IAE_if_new_name_is_not_valid() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Table name must be lower case and contain only alphanumeric chars or '_', got '(not valid)'"); - - new RenameTableBuilder(new H2()).setName("foo").setNewName("(not valid)").build(); + assertThatThrownBy(() -> new RenameTableBuilder(new H2()).setName("foo").setNewName("(not valid)").build()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Table name must be lower case and contain only alphanumeric chars or '_', got '(not valid)'"); } private static void verifySql(Dialect dialect, String... expectedSql) { diff --git a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/step/DataChangeTest.java b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/step/DataChangeTest.java index 58f181a4f79..dc4b92bb1b9 100644 --- a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/step/DataChangeTest.java +++ b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/step/DataChangeTest.java @@ -30,12 +30,12 @@ import javax.annotation.Nullable; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.db.CoreDbTester; import org.sonar.server.platform.db.migration.step.Select.Row; import org.sonar.server.platform.db.migration.step.Select.RowReader; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.fail; public class DataChangeTest { @@ -45,8 +45,6 @@ public class DataChangeTest { @Rule public CoreDbTester db = CoreDbTester.createForSchema(DataChangeTest.class, "schema.sql"); - @Rule - public ExpectedException thrown = ExpectedException.none(); @Before public void setUp() { @@ -113,36 +111,36 @@ public class DataChangeTest { public void display_current_row_details_if_error_during_get() throws Exception { insertPersons(); - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Error during processing of row: [id=2]"); - - new DataChange(db.database()) { - @Override - public void execute(Context context) throws SQLException { - context.prepareSelect("select id from persons where id>=?").setLong(1, 2L).get((RowReader) row -> { - throw new IllegalStateException("Unexpected error"); - }); - } - }.execute(); - + assertThatThrownBy(() -> { + new DataChange(db.database()) { + @Override + public void execute(Context context) throws SQLException { + context.prepareSelect("select id from persons where id>=?").setLong(1, 2L).get((RowReader) row -> { + throw new IllegalStateException("Unexpected error"); + }); + } + }.execute(); + }) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Error during processing of row: [id=2]"); } @Test public void display_current_row_details_if_error_during_list() throws Exception { insertPersons(); - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Error during processing of row: [id=2]"); - - new DataChange(db.database()) { - @Override - public void execute(Context context) throws SQLException { - context.prepareSelect("select id from persons where id>=?").setLong(1, 2L).list((RowReader) row -> { - throw new IllegalStateException("Unexpected error"); - }); - } - }.execute(); - + assertThatThrownBy(() -> { + new DataChange(db.database()) { + @Override + public void execute(Context context) throws SQLException { + context.prepareSelect("select id from persons where id>=?").setLong(1, 2L).list((RowReader) row -> { + throw new IllegalStateException("Unexpected error"); + }); + } + }.execute(); + }) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Error during processing of row: [id=2]"); } @Test @@ -157,9 +155,8 @@ public class DataChangeTest { } }; - thrown.expect(SQLException.class); - - change.execute(); + assertThatThrownBy(() -> change.execute()) + .isInstanceOf(SQLException.class); } @Test @@ -353,19 +350,20 @@ public class DataChangeTest { public void display_current_row_details_if_error_during_scroll() throws Exception { insertPersons(); - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Error during processing of row: [id=1]"); - - new DataChange(db.database()) { - @Override - public void execute(Context context) throws SQLException { - final Upsert upsert = context.prepareUpsert("update persons set login=?, age=? where id=?"); - context.prepareSelect("select id from persons").scroll(row -> { - throw new IllegalStateException("Unexpected error"); - }); - upsert.commit().close(); - } - }.execute(); + assertThatThrownBy(() -> { + new DataChange(db.database()) { + @Override + public void execute(Context context) throws SQLException { + final Upsert upsert = context.prepareUpsert("update persons set login=?, age=? where id=?"); + context.prepareSelect("select id from persons").scroll(row -> { + throw new IllegalStateException("Unexpected error"); + }); + upsert.commit().close(); + } + }.execute(); + }) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Error during processing of row: [id=1]"); } @Test @@ -398,20 +396,21 @@ public class DataChangeTest { public void display_current_row_details_if_error_during_mass_update() throws Exception { insertPersons(); - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Error during processing of row: [id=2]"); - - new DataChange(db.database()) { - @Override - public void execute(Context context) throws SQLException { - MassUpdate massUpdate = context.prepareMassUpdate(); - massUpdate.select("select id from persons where id>=?").setLong(1, 2L); - massUpdate.update("update persons set login=?, age=? where id=?"); - massUpdate.execute((row, update) -> { - throw new IllegalStateException("Unexpected error"); - }); - } - }.execute(); + assertThatThrownBy(() -> { + new DataChange(db.database()) { + @Override + public void execute(Context context) throws SQLException { + MassUpdate massUpdate = context.prepareMassUpdate(); + massUpdate.select("select id from persons where id>=?").setLong(1, 2L); + massUpdate.update("update persons set login=?, age=? where id=?"); + massUpdate.execute((row, update) -> { + throw new IllegalStateException("Unexpected error"); + }); + } + }.execute(); + }) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Error during processing of row: [id=2]"); } @Test diff --git a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/step/DropIndexBuilderTest.java b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/step/DropIndexBuilderTest.java index d7a5cb339b7..b37e7802897 100644 --- a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/step/DropIndexBuilderTest.java +++ b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/step/DropIndexBuilderTest.java @@ -20,9 +20,7 @@ package org.sonar.server.platform.db.migration.step; import java.util.List; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.db.dialect.Dialect; import org.sonar.db.dialect.H2; import org.sonar.db.dialect.MsSql; @@ -30,11 +28,10 @@ import org.sonar.db.dialect.Oracle; import org.sonar.db.dialect.PostgreSql; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class DropIndexBuilderTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void drop_index_in_table() { @@ -54,43 +51,47 @@ public class DropIndexBuilderTest { @Test public void throw_NPE_if_table_name_is_missing() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("Table name can't be null"); - - new DropIndexBuilder(new H2()) - .setName("issues_key") - .build(); + assertThatThrownBy(() -> { + new DropIndexBuilder(new H2()) + .setName("issues_key") + .build(); + }) + .isInstanceOf(NullPointerException.class) + .hasMessage("Table name can't be null"); } @Test public void throw_IAE_if_table_name_is_not_valid() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Table name must be lower case and contain only alphanumeric chars or '_', got '(not valid)'"); - - new DropIndexBuilder(new H2()) - .setTable("(not valid)") - .setName("issues_key") - .build(); + assertThatThrownBy(() -> { + new DropIndexBuilder(new H2()) + .setTable("(not valid)") + .setName("issues_key") + .build(); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Table name must be lower case and contain only alphanumeric chars or '_', got '(not valid)'"); } @Test public void throw_NPE_if_index_name_is_missing() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("Index name can't be null"); - - new DropIndexBuilder(new H2()) - .setTable("issues") - .build(); + assertThatThrownBy(() -> { + new DropIndexBuilder(new H2()) + .setTable("issues") + .build(); + }) + .isInstanceOf(NullPointerException.class) + .hasMessage("Index name can't be null"); } @Test public void throw_IAE_if_index_name_is_not_valid() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Index name must contain only alphanumeric chars or '_', got '(not valid)'"); - - new DropIndexBuilder(new H2()) - .setTable("issues") - .setName("(not valid)") - .build(); + assertThatThrownBy(() -> { + new DropIndexBuilder(new H2()) + .setTable("issues") + .setName("(not valid)") + .build(); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Index name must contain only alphanumeric chars or '_', got '(not valid)'"); } } diff --git a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/step/MigrationNumberTest.java b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/step/MigrationNumberTest.java index 787bbb484a1..f6e5c294635 100644 --- a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/step/MigrationNumberTest.java +++ b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/step/MigrationNumberTest.java @@ -20,14 +20,12 @@ package org.sonar.server.platform.db.migration.step; import java.util.Random; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.test.TestUtils; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + public class MigrationNumberTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void constructor_is_private() { @@ -36,10 +34,9 @@ public class MigrationNumberTest { @Test public void validate_throws_IAE_if_argument_is_less_then_0() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Migration number must be >= 0"); - - MigrationNumber.validate(-(Math.abs(new Random().nextInt()) + 1)); + assertThatThrownBy(() -> MigrationNumber.validate(-(Math.abs(new Random().nextInt()) + 1))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Migration number must be >= 0"); } @Test diff --git a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/step/MigrationStepExecutionExceptionTest.java b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/step/MigrationStepExecutionExceptionTest.java index a49a76158d3..f7b132e4c13 100644 --- a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/step/MigrationStepExecutionExceptionTest.java +++ b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/step/MigrationStepExecutionExceptionTest.java @@ -19,15 +19,12 @@ */ package org.sonar.server.platform.db.migration.step; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class MigrationStepExecutionExceptionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private RegisteredMigrationStep step = new RegisteredMigrationStep(1, "foo", MigrationStep.class); private MigrationStepExecutionException underTest = new MigrationStepExecutionException( @@ -40,18 +37,20 @@ public class MigrationStepExecutionExceptionTest { @Test public void constructor_throws_NPE_if_step_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("RegisteredMigrationStep can't be null"); - - new MigrationStepExecutionException(null, new NullPointerException("Some cause")); + assertThatThrownBy(() -> { + new MigrationStepExecutionException(null, new NullPointerException("Some cause")); + }) + .isInstanceOf(NullPointerException.class) + .hasMessage("RegisteredMigrationStep can't be null"); } @Test public void constructor_throws_NPE_if_cause_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("cause can't be null"); - - new MigrationStepExecutionException(new RegisteredMigrationStep(1, "foo", MigrationStep.class), null); + assertThatThrownBy(() -> { + new MigrationStepExecutionException(new RegisteredMigrationStep(1, "foo", MigrationStep.class), null); + }) + .isInstanceOf(NullPointerException.class) + .hasMessage("cause can't be null"); } @Test diff --git a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/step/MigrationStepRegistryImplTest.java b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/step/MigrationStepRegistryImplTest.java index 06eb4ab38c5..a04f369b251 100644 --- a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/step/MigrationStepRegistryImplTest.java +++ b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/step/MigrationStepRegistryImplTest.java @@ -21,66 +21,65 @@ package org.sonar.server.platform.db.migration.step; import java.util.List; import java.util.Random; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class MigrationStepRegistryImplTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private MigrationStepRegistryImpl underTest = new MigrationStepRegistryImpl(); @Test public void add_fails_with_IAE_if_migrationNumber_is_less_than_0() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Migration number must be >= 0"); - - underTest.add(-Math.abs(new Random().nextLong() + 1), "sdsd", MigrationStep.class); + assertThatThrownBy(() -> { + underTest.add(-Math.abs(new Random().nextLong() + 1), "sdsd", MigrationStep.class); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Migration number must be >= 0"); } @Test public void add_fails_with_NPE_if_description_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("description can't be null"); - - underTest.add(12, null, MigrationStep.class); + assertThatThrownBy(() -> { + underTest.add(12, null, MigrationStep.class); + }) + .isInstanceOf(NullPointerException.class) + .hasMessage("description can't be null"); } @Test public void add_fails_with_IAE_if_description_is_empty() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("description can't be empty"); - - underTest.add(12, "", MigrationStep.class); + assertThatThrownBy(() -> { + underTest.add(12, "", MigrationStep.class); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("description can't be empty"); } @Test public void add_fails_with_NPE_is_migrationstep_class_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("MigrationStep class can't be null"); - - underTest.add(12, "sdsd", null); + assertThatThrownBy(() -> { + underTest.add(12, "sdsd", null); + }) + .isInstanceOf(NullPointerException.class) + .hasMessage("MigrationStep class can't be null"); } @Test public void add_fails_with_ISE_when_called_twice_with_same_migration_number() { underTest.add(12, "dsd", MigrationStep.class); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("A migration is already registered for migration number '12'"); - - underTest.add(12, "dfsdf", MigrationStep.class); + assertThatThrownBy(() -> underTest.add(12, "dfsdf", MigrationStep.class)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("A migration is already registered for migration number '12'"); } @Test public void build_fails_with_ISE_if_registry_is_empty() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Registry is empty"); - - underTest.build(); + assertThatThrownBy(() -> underTest.build()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Registry is empty"); } @Test diff --git a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/step/MigrationStepsImplTest.java b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/step/MigrationStepsImplTest.java index 19f328c61a9..f330fc601e0 100644 --- a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/step/MigrationStepsImplTest.java +++ b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/step/MigrationStepsImplTest.java @@ -23,15 +23,12 @@ import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class MigrationStepsImplTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private MigrationStepsImpl underTest = new MigrationStepsImpl(Arrays.asList( new RegisteredMigrationStep(1, "mmmmmm", MigrationStep.class), @@ -44,28 +41,27 @@ public class MigrationStepsImplTest { @Test public void constructor_fails_with_NPE_if_argument_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("steps can't be null"); - - new MigrationStepsImpl(null); + assertThatThrownBy(() -> new MigrationStepsImpl(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("steps can't be null"); } @Test public void constructor_fails_with_IAE_if_argument_is_empty() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("steps can't be empty"); - - new MigrationStepsImpl(Collections.emptyList()); + assertThatThrownBy(() -> new MigrationStepsImpl(Collections.emptyList())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("steps can't be empty"); } @Test public void constructor_fails_with_NPE_if_argument_contains_a_null() { - expectedException.expect(NullPointerException.class); - - new MigrationStepsImpl(Arrays.asList( - new RegisteredMigrationStep(12, "sdsd", MigrationStep.class), - null, - new RegisteredMigrationStep(88, "q", MigrationStep.class))); + assertThatThrownBy(() -> { + new MigrationStepsImpl(Arrays.asList( + new RegisteredMigrationStep(12, "sdsd", MigrationStep.class), + null, + new RegisteredMigrationStep(88, "q", MigrationStep.class))); + }) + .isInstanceOf(NullPointerException.class); } @Test @@ -81,10 +77,9 @@ public class MigrationStepsImplTest { @Test public void readFrom_throws_IAE_if_number_is_less_than_0() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Migration number must be >= 0"); - - underTest.readFrom(-1); + assertThatThrownBy(() -> underTest.readFrom(-1)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Migration number must be >= 0"); } @Test diff --git a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/step/MigrationStepsProviderTest.java b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/step/MigrationStepsProviderTest.java index 120f8c6acdc..bffbce029b6 100644 --- a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/step/MigrationStepsProviderTest.java +++ b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/step/MigrationStepsProviderTest.java @@ -20,13 +20,12 @@ package org.sonar.server.platform.db.migration.step; import java.util.Random; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.InOrder; import org.sonar.server.platform.db.migration.version.DbVersion; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.inOrder; @@ -35,8 +34,6 @@ import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; public class MigrationStepsProviderTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private InternalMigrationStepRegistry internalMigrationStepRegistry = mock(InternalMigrationStepRegistry.class); private MigrationStepsProvider underTest = new MigrationStepsProvider(); @@ -46,10 +43,9 @@ public class MigrationStepsProviderTest { IllegalStateException expected = new IllegalStateException("faking ISE because registry is empty"); when(internalMigrationStepRegistry.build()).thenThrow(expected); - expectedException.expect(expected.getClass()); - expectedException.expectMessage(expected.getMessage()); - - underTest.provide(internalMigrationStepRegistry); + assertThatThrownBy(() -> underTest.provide(internalMigrationStepRegistry)) + .isInstanceOf(expected.getClass()) + .hasMessage(expected.getMessage()); } @Test diff --git a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/step/RegisteredMigrationStepTest.java b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/step/RegisteredMigrationStepTest.java index 49d4b67c7c1..dbb67840613 100644 --- a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/step/RegisteredMigrationStepTest.java +++ b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/step/RegisteredMigrationStepTest.java @@ -19,30 +19,25 @@ */ package org.sonar.server.platform.db.migration.step; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class RegisteredMigrationStepTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void constructor_throws_NPE_if_description_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("description can't be null"); - - new RegisteredMigrationStep(1, null, MigrationStep.class); + assertThatThrownBy(() -> new RegisteredMigrationStep(1, null, MigrationStep.class)) + .isInstanceOf(NullPointerException.class) + .hasMessage("description can't be null"); } @Test public void constructor_throws_NPE_if_MigrationStep_class_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("MigrationStep class can't be null"); - - new RegisteredMigrationStep(1, "", null); + assertThatThrownBy(() -> new RegisteredMigrationStep(1, "", null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("MigrationStep class can't be null"); } @Test diff --git a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/step/UpsertImplTest.java b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/step/UpsertImplTest.java index 0679a4c360a..f08f0a3852a 100644 --- a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/step/UpsertImplTest.java +++ b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/step/UpsertImplTest.java @@ -20,26 +20,22 @@ package org.sonar.server.platform.db.migration.step; import java.sql.Connection; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; import static org.mockito.Mockito.mock; public class UpsertImplTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void setBatchSize_throws_IAE_if_value_is_negative() throws Exception { UpsertImpl underTest = create(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("size must be positive. Got -1"); - - underTest.setBatchSize(-1); + assertThatThrownBy(() -> underTest.setBatchSize(-1)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("size must be positive. Got -1"); } @Test diff --git a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v91/CreateAuditTableTest.java b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v91/CreateAuditTableTest.java index 30a67f44027..63cea2297f8 100644 --- a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v91/CreateAuditTableTest.java +++ b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v91/CreateAuditTableTest.java @@ -19,12 +19,11 @@ */ package org.sonar.server.platform.db.migration.version.v91; +import java.sql.SQLException; import org.junit.Rule; import org.junit.Test; import org.sonar.db.CoreDbTester; -import java.sql.SQLException; - public class CreateAuditTableTest { private static final String TABLE_NAME = "audits"; diff --git a/server/sonar-main/src/test/java/org/sonar/application/AppFileSystemTest.java b/server/sonar-main/src/test/java/org/sonar/application/AppFileSystemTest.java index b4c69fdfa56..d432962458d 100644 --- a/server/sonar-main/src/test/java/org/sonar/application/AppFileSystemTest.java +++ b/server/sonar-main/src/test/java/org/sonar/application/AppFileSystemTest.java @@ -30,12 +30,12 @@ import org.apache.commons.io.FileUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.sonar.application.config.TestAppSettings; import org.sonar.process.sharedmemoryfile.AllProcessesCommands; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.process.ProcessProperties.Property.PATH_DATA; import static org.sonar.process.ProcessProperties.Property.PATH_HOME; import static org.sonar.process.ProcessProperties.Property.PATH_LOGS; @@ -47,8 +47,6 @@ public class AppFileSystemTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private File homeDir; private File dataDir; @@ -179,10 +177,9 @@ public class AppFileSystemTest { assertThat(file.createNewFile()).isTrue(); settings.getProps().set(property, file.getAbsolutePath()); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Property '" + property + "' is not valid, not a directory: " + file.getAbsolutePath()); - - underTest.reset(); + assertThatThrownBy(() -> underTest.reset()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Property '" + property + "' is not valid, not a directory: " + file.getAbsolutePath()); } @Test @@ -192,10 +189,9 @@ public class AppFileSystemTest { FileUtils.forceMkdir(logsDir); FileUtils.touch(dataDir); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Property 'sonar.path.data' is not valid, not a directory: " + dataDir.getAbsolutePath()); - - underTest.reset(); + assertThatThrownBy(() -> underTest.reset()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Property 'sonar.path.data' is not valid, not a directory: " + dataDir.getAbsolutePath()); } } diff --git a/server/sonar-main/src/test/java/org/sonar/application/AppLoggingTest.java b/server/sonar-main/src/test/java/org/sonar/application/AppLoggingTest.java index 9da2b90899c..1e153ea4be0 100644 --- a/server/sonar-main/src/test/java/org/sonar/application/AppLoggingTest.java +++ b/server/sonar-main/src/test/java/org/sonar/application/AppLoggingTest.java @@ -36,7 +36,6 @@ import org.junit.AfterClass; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.slf4j.LoggerFactory; import org.sonar.application.config.AppSettings; @@ -46,6 +45,7 @@ import org.sonar.process.logging.LogbackJsonLayout; import org.sonar.process.logging.PatternLayoutEncoder; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.slf4j.Logger.ROOT_LOGGER_NAME; import static org.sonar.application.process.StreamGobbler.LOGGER_GOBBLER; import static org.sonar.process.ProcessProperties.Property.CLUSTER_ENABLED; @@ -55,8 +55,6 @@ public class AppLoggingTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private File logDir; @@ -232,20 +230,18 @@ public class AppLoggingTest { public void fail_with_IAE_if_global_property_unsupported_level() { settings.getProps().set("sonar.log.level", "ERROR"); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("log level ERROR in property sonar.log.level is not a supported value (allowed levels are [TRACE, DEBUG, INFO])"); - - underTest.configure(); + assertThatThrownBy(() -> underTest.configure()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("log level ERROR in property sonar.log.level is not a supported value (allowed levels are [TRACE, DEBUG, INFO])"); } @Test public void fail_with_IAE_if_app_property_unsupported_level() { settings.getProps().set("sonar.log.level.app", "ERROR"); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("log level ERROR in property sonar.log.level.app is not a supported value (allowed levels are [TRACE, DEBUG, INFO])"); - - underTest.configure(); + assertThatThrownBy(() -> underTest.configure()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("log level ERROR in property sonar.log.level.app is not a supported value (allowed levels are [TRACE, DEBUG, INFO])"); } @Test diff --git a/server/sonar-main/src/test/java/org/sonar/application/AppReloaderImplTest.java b/server/sonar-main/src/test/java/org/sonar/application/AppReloaderImplTest.java index ecab4a40801..6c15a43240f 100644 --- a/server/sonar-main/src/test/java/org/sonar/application/AppReloaderImplTest.java +++ b/server/sonar-main/src/test/java/org/sonar/application/AppReloaderImplTest.java @@ -21,15 +21,14 @@ package org.sonar.application; import com.google.common.collect.ImmutableMap; import java.io.IOException; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.application.config.AppSettings; import org.sonar.application.config.AppSettingsLoader; import org.sonar.application.config.TestAppSettings; import org.sonar.process.MessageException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.data.MapEntry.entry; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -43,8 +42,6 @@ import static org.sonar.process.ProcessProperties.Property.PATH_WEB; public class AppReloaderImplTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private final AppSettingsLoader settingsLoader = mock(AppSettingsLoader.class); private final FileSystem fs = mock(FileSystem.class); @@ -72,14 +69,15 @@ public class AppReloaderImplTest { public void throw_ISE_if_cluster_is_enabled() throws IOException { AppSettings settings = new TestAppSettings(ImmutableMap.of(CLUSTER_ENABLED.getKey(), "true")); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Restart is not possible with cluster mode"); + assertThatThrownBy(() -> { + underTest.reload(settings); - underTest.reload(settings); - - verifyZeroInteractions(logging); - verifyZeroInteractions(state); - verifyZeroInteractions(fs); + verifyZeroInteractions(logging); + verifyZeroInteractions(state); + verifyZeroInteractions(fs); + }) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Restart is not possible with cluster mode"); } @Test @@ -100,13 +98,14 @@ public class AppReloaderImplTest { AppSettings newSettings = new TestAppSettings(ImmutableMap.of(propertyKey, "val2")); when(settingsLoader.load()).thenReturn(newSettings); - expectedException.expect(MessageException.class); - expectedException.expectMessage("Property [" + propertyKey + "] cannot be changed on restart: [val1] => [val2]"); - - underTest.reload(settings); + assertThatThrownBy(() -> { + underTest.reload(settings); - verifyZeroInteractions(logging); - verifyZeroInteractions(state); - verifyZeroInteractions(fs); + verifyZeroInteractions(logging); + verifyZeroInteractions(state); + verifyZeroInteractions(fs); + }) + .isInstanceOf(MessageException.class) + .hasMessage("Property [" + propertyKey + "] cannot be changed on restart: [val1] => [val2]"); } } diff --git a/server/sonar-main/src/test/java/org/sonar/application/SchedulerImplTest.java b/server/sonar-main/src/test/java/org/sonar/application/SchedulerImplTest.java index 34600dc7bdc..0d71b51b67f 100644 --- a/server/sonar-main/src/test/java/org/sonar/application/SchedulerImplTest.java +++ b/server/sonar-main/src/test/java/org/sonar/application/SchedulerImplTest.java @@ -28,7 +28,6 @@ import java.io.InputStream; import java.util.ArrayList; import java.util.EnumMap; import java.util.List; -import java.util.Properties; import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -37,7 +36,6 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.DisableOnDebug; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.junit.rules.TestRule; import org.junit.rules.Timeout; @@ -73,8 +71,6 @@ public class SchedulerImplTest { @Rule public TestRule safeguardTimeout = new DisableOnDebug(Timeout.seconds(60)); @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); private Level initialLevel; diff --git a/server/sonar-main/src/test/java/org/sonar/application/cluster/AppNodesClusterHostsConsistencyTest.java b/server/sonar-main/src/test/java/org/sonar/application/cluster/AppNodesClusterHostsConsistencyTest.java index 0107499267a..42a8c2e6332 100644 --- a/server/sonar-main/src/test/java/org/sonar/application/cluster/AppNodesClusterHostsConsistencyTest.java +++ b/server/sonar-main/src/test/java/org/sonar/application/cluster/AppNodesClusterHostsConsistencyTest.java @@ -38,15 +38,14 @@ import java.util.concurrent.locks.Lock; import java.util.function.Consumer; import org.junit.After; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.application.config.TestAppSettings; import org.sonar.process.cluster.hz.DistributedAnswer; import org.sonar.process.cluster.hz.DistributedCall; import org.sonar.process.cluster.hz.DistributedCallback; import org.sonar.process.cluster.hz.HazelcastMember; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; @@ -54,8 +53,6 @@ import static org.mockito.Mockito.when; import static org.sonar.process.ProcessProperties.Property.CLUSTER_HZ_HOSTS; public class AppNodesClusterHostsConsistencyTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @SuppressWarnings("unchecked") private final Consumer logger = mock(Consumer.class); @@ -115,10 +112,9 @@ public class AppNodesClusterHostsConsistencyTest { TestAppSettings settings = new TestAppSettings(); AppNodesClusterHostsConsistency.setInstance(member, settings); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Instance is already set"); - - AppNodesClusterHostsConsistency.setInstance(member, settings); + assertThatThrownBy(() -> AppNodesClusterHostsConsistency.setInstance(member, settings)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Instance is already set"); } @Test @@ -127,10 +123,9 @@ public class AppNodesClusterHostsConsistencyTest { TestHazelcastMember member2 = new TestHazelcastMember(Collections.emptyMap(), newLocalHostMember(2, true)); AppNodesClusterHostsConsistency.setInstance(member1, new TestAppSettings()); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Instance is already set"); - - AppNodesClusterHostsConsistency.setInstance(member2, new TestAppSettings()); + assertThatThrownBy(() -> AppNodesClusterHostsConsistency.setInstance(member2, new TestAppSettings())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Instance is already set"); } private Member newLocalHostMember(int port) throws UnknownHostException { diff --git a/server/sonar-main/src/test/java/org/sonar/application/cluster/health/SearchNodeHealthProviderTest.java b/server/sonar-main/src/test/java/org/sonar/application/cluster/health/SearchNodeHealthProviderTest.java index 681bd2769a7..8e6fa5c55b8 100644 --- a/server/sonar-main/src/test/java/org/sonar/application/cluster/health/SearchNodeHealthProviderTest.java +++ b/server/sonar-main/src/test/java/org/sonar/application/cluster/health/SearchNodeHealthProviderTest.java @@ -22,9 +22,7 @@ package org.sonar.application.cluster.health; import java.util.Properties; import java.util.Random; import javax.annotation.Nullable; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.application.cluster.ClusterAppState; import org.sonar.process.NetworkUtils; import org.sonar.process.ProcessId; @@ -34,16 +32,15 @@ import org.sonar.process.cluster.health.NodeHealth; import static java.lang.String.valueOf; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_HOST; -import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_NAME; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_HZ_PORT; +import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_NAME; public class SearchNodeHealthProviderTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private final Random random = new Random(); private SearchNodeHealthProvider.Clock clock = mock(SearchNodeHealthProvider.Clock.class); @@ -54,10 +51,9 @@ public class SearchNodeHealthProviderTest { public void constructor_throws_IAE_if_property_node_name_is_not_set() { Props props = new Props(new Properties()); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Missing property: sonar.cluster.node.name"); - - new SearchNodeHealthProvider(props, clusterAppState, networkUtils); + assertThatThrownBy(() -> new SearchNodeHealthProvider(props, clusterAppState, networkUtils)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Missing property: sonar.cluster.node.name"); } @Test @@ -66,9 +62,8 @@ public class SearchNodeHealthProviderTest { properties.put(CLUSTER_NODE_NAME.getKey(), randomAlphanumeric(3)); Props props = new Props(properties); - expectedException.expect(NullPointerException.class); - - new SearchNodeHealthProvider(props, clusterAppState, networkUtils, clock); + assertThatThrownBy(() -> new SearchNodeHealthProvider(props, clusterAppState, networkUtils, clock)) + .isInstanceOf(NullPointerException.class); } @Test @@ -78,10 +73,9 @@ public class SearchNodeHealthProviderTest { when(networkUtils.getHostname()).thenReturn(randomAlphanumeric(34)); Props props = new Props(properties); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Missing property: sonar.cluster.node.port"); - - new SearchNodeHealthProvider(props, clusterAppState, networkUtils, clock); + assertThatThrownBy(() -> new SearchNodeHealthProvider(props, clusterAppState, networkUtils, clock)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Missing property: sonar.cluster.node.port"); } @Test @@ -93,10 +87,9 @@ public class SearchNodeHealthProviderTest { when(networkUtils.getHostname()).thenReturn(randomAlphanumeric(34)); Props props = new Props(properties); - expectedException.expect(NumberFormatException.class); - expectedException.expectMessage("For input string: \"" + port + "\""); - - new SearchNodeHealthProvider(props, clusterAppState, networkUtils, clock); + assertThatThrownBy(() -> new SearchNodeHealthProvider(props, clusterAppState, networkUtils, clock)) + .isInstanceOf(NumberFormatException.class) + .hasMessage("For input string: \"" + port + "\""); } @Test diff --git a/server/sonar-main/src/test/java/org/sonar/application/command/AbstractCommandTest.java b/server/sonar-main/src/test/java/org/sonar/application/command/AbstractCommandTest.java index be553fc9a67..da6ac85da04 100644 --- a/server/sonar-main/src/test/java/org/sonar/application/command/AbstractCommandTest.java +++ b/server/sonar-main/src/test/java/org/sonar/application/command/AbstractCommandTest.java @@ -28,7 +28,6 @@ import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.mockito.Mockito; import org.sonar.process.ProcessId; @@ -36,33 +35,34 @@ import org.sonar.process.System2; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.when; public class AbstractCommandTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void constructor_throws_NPE_of_ProcessId_is_null() throws IOException { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("ProcessId can't be null"); - - new AbstractCommand(null, temp.newFolder(), System2.INSTANCE) { + assertThatThrownBy(() -> { + new AbstractCommand(null, temp.newFolder(), System2.INSTANCE) { - }; + }; + }) + .isInstanceOf(NullPointerException.class) + .hasMessage("ProcessId can't be null"); } @Test public void constructor_throws_NPE_of_workDir_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("workDir can't be null"); - - new AbstractCommand(ProcessId.WEB_SERVER, null, System2.INSTANCE) { + assertThatThrownBy(() -> { + new AbstractCommand(ProcessId.WEB_SERVER, null, System2.INSTANCE) { - }; + }; + }) + .isInstanceOf(NullPointerException.class) + .hasMessage("workDir can't be null"); } @Test @@ -72,10 +72,9 @@ public class AbstractCommandTest { }; - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("key can't be null"); - - underTest.setEnvVariable(null, randomAlphanumeric(30)); + assertThatThrownBy(() -> underTest.setEnvVariable(null, randomAlphanumeric(30))) + .isInstanceOf(NullPointerException.class) + .hasMessage("key can't be null"); } @Test @@ -85,10 +84,9 @@ public class AbstractCommandTest { }; - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("value can't be null"); - - underTest.setEnvVariable(randomAlphanumeric(30), null); + assertThatThrownBy(() -> underTest.setEnvVariable(randomAlphanumeric(30), null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("value can't be null"); } @Test diff --git a/server/sonar-main/src/test/java/org/sonar/application/command/CommandFactoryImplTest.java b/server/sonar-main/src/test/java/org/sonar/application/command/CommandFactoryImplTest.java index 637f472bcdb..d73d9d0b2ec 100644 --- a/server/sonar-main/src/test/java/org/sonar/application/command/CommandFactoryImplTest.java +++ b/server/sonar-main/src/test/java/org/sonar/application/command/CommandFactoryImplTest.java @@ -29,7 +29,6 @@ import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.mockito.Mockito; import org.sonar.application.es.EsInstallation; @@ -41,14 +40,13 @@ import org.sonar.process.Props; import org.sonar.process.System2; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.entry; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class CommandFactoryImplTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public TemporaryFolder temp = new TemporaryFolder(); @@ -111,10 +109,9 @@ public class CommandFactoryImplTest { @Test public void createEsCommand_throws_ISE_if_es_binary_is_not_found() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Cannot find elasticsearch binary"); - - newFactory(new Properties()).createEsCommand(); + assertThatThrownBy(() -> newFactory(new Properties()).createEsCommand()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Cannot find elasticsearch binary"); } @Test diff --git a/server/sonar-main/src/test/java/org/sonar/application/command/EsJvmOptionsTest.java b/server/sonar-main/src/test/java/org/sonar/application/command/EsJvmOptionsTest.java index a4c7c3bcc91..b2d772c39aa 100644 --- a/server/sonar-main/src/test/java/org/sonar/application/command/EsJvmOptionsTest.java +++ b/server/sonar-main/src/test/java/org/sonar/application/command/EsJvmOptionsTest.java @@ -25,21 +25,18 @@ import java.io.IOException; import java.util.Properties; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.sonar.process.Props; -import org.sonar.test.ExceptionCauseMatcher; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; @RunWith(DataProviderRunner.class) public class EsJvmOptionsTest { @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private Properties properties = new Properties(); @@ -162,10 +159,9 @@ public class EsJvmOptionsTest { File notAFile = temporaryFolder.newFolder(); EsJvmOptions underTest = new EsJvmOptions(new Props(properties), temporaryFolder.newFolder()); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Cannot write Elasticsearch jvm options file"); - expectedException.expectCause(ExceptionCauseMatcher.hasType(IOException.class)); - - underTest.writeToJvmOptionFile(notAFile); + assertThatThrownBy(() -> underTest.writeToJvmOptionFile(notAFile)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Cannot write Elasticsearch jvm options file") + .hasRootCauseInstanceOf(IOException.class); } } diff --git a/server/sonar-main/src/test/java/org/sonar/application/command/JvmOptionsTest.java b/server/sonar-main/src/test/java/org/sonar/application/command/JvmOptionsTest.java index c045f7d1d7a..8e39f3a9463 100644 --- a/server/sonar-main/src/test/java/org/sonar/application/command/JvmOptionsTest.java +++ b/server/sonar-main/src/test/java/org/sonar/application/command/JvmOptionsTest.java @@ -33,9 +33,8 @@ import java.util.Random; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; -import org.junit.Rule; +import org.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.process.MessageException; import org.sonar.process.Props; @@ -44,12 +43,11 @@ import static java.lang.String.valueOf; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.fail; @RunWith(DataProviderRunner.class) public class JvmOptionsTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private final Random random = new Random(); private final String randomPropertyName = randomAlphanumeric(3); @@ -67,9 +65,7 @@ public class JvmOptionsTest { @Test public void constructor_throws_NPE_if_argument_is_null() { - expectJvmOptionNotNullNPE(); - - new JvmOptions(null); + expectJvmOptionNotNullNPE(() -> new JvmOptions(null)); } @Test @@ -80,10 +76,9 @@ public class JvmOptionsTest { Stream.of(new Option(null, "value"))) .flatMap(s -> s)); - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("JVM option prefix can't be null"); - - new JvmOptions(mandatoryJvmOptions); + assertThatThrownBy(() -> new JvmOptions(mandatoryJvmOptions)) + .isInstanceOf(NullPointerException.class) + .hasMessage("JVM option prefix can't be null"); } @Test @@ -95,10 +90,9 @@ public class JvmOptionsTest { Stream.of(new Option(emptyString, "value"))) .flatMap(s -> s)); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("JVM option prefix can't be empty"); - - new JvmOptions(mandatoryJvmOptions); + assertThatThrownBy(() -> new JvmOptions(mandatoryJvmOptions)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("JVM option prefix can't be empty"); } @Test @@ -110,9 +104,7 @@ public class JvmOptionsTest { Stream.of(new Option(invalidPrefix, "value"))) .flatMap(s -> s)); - expectJvmOptionNotEmptyAndStartByDashIAE(); - - new JvmOptions(mandatoryJvmOptions); + expectJvmOptionNotEmptyAndStartByDashIAE(() -> new JvmOptions(mandatoryJvmOptions)); } @Test @@ -123,10 +115,9 @@ public class JvmOptionsTest { Stream.of(new Option("-prefix", null))) .flatMap(s -> s)); - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("JVM option value can't be null"); - - new JvmOptions(mandatoryJvmOptions); + assertThatThrownBy(() -> new JvmOptions(mandatoryJvmOptions)) + .isInstanceOf(NullPointerException.class) + .hasMessage("JVM option value can't be null"); } @Test @@ -143,24 +134,19 @@ public class JvmOptionsTest { @Test public void add_throws_NPE_if_argument_is_null() { - expectJvmOptionNotNullNPE(); - - underTest.add(null); + expectJvmOptionNotNullNPE(() -> underTest.add(null)); } @Test @UseDataProvider("variousEmptyStrings") public void add_throws_IAE_if_argument_is_empty(String emptyString) { - expectJvmOptionNotEmptyAndStartByDashIAE(); - - underTest.add(emptyString); + expectJvmOptionNotEmptyAndStartByDashIAE(() -> underTest.add(emptyString)); } @Test public void add_throws_IAE_if_argument_does_not_start_with_dash() { - expectJvmOptionNotEmptyAndStartByDashIAE(); + expectJvmOptionNotEmptyAndStartByDashIAE(() -> underTest.add(randomAlphanumeric(3))); - underTest.add(randomAlphanumeric(3)); } @Test @@ -227,16 +213,12 @@ public class JvmOptionsTest { @Test public void addFromMandatoryProperty_fails_with_IAE_if_property_does_not_exist() { - expectMissingPropertyIAE(this.randomPropertyName); - - underTest.addFromMandatoryProperty(new Props(properties), this.randomPropertyName); + expectMissingPropertyIAE(() -> underTest.addFromMandatoryProperty(new Props(properties), this.randomPropertyName), this.randomPropertyName); } @Test public void addFromMandatoryProperty_fails_with_IAE_if_property_contains_an_empty_value() { - expectMissingPropertyIAE(this.randomPropertyName); - - underTest.addFromMandatoryProperty(new Props(properties), randomPropertyName); + expectMissingPropertyIAE(() -> underTest.addFromMandatoryProperty(new Props(properties), randomPropertyName), this.randomPropertyName); } @Test @@ -254,9 +236,7 @@ public class JvmOptionsTest { public void addFromMandatoryProperty_fails_with_MessageException_if_property_does_not_start_with_dash_after_trimmed(String emptyString) { properties.put(randomPropertyName, emptyString + "foo -bar"); - expectJvmOptionNotEmptyAndStartByDashMessageException(randomPropertyName, "foo"); - - underTest.addFromMandatoryProperty(new Props(properties), randomPropertyName); + expectJvmOptionNotEmptyAndStartByDashMessageException(() -> underTest.addFromMandatoryProperty(new Props(properties), randomPropertyName), randomPropertyName, "foo"); } @Test @@ -337,12 +317,11 @@ public class JvmOptionsTest { JvmOptions underTest = new JvmOptions(ImmutableMap.of(randomPrefix, randomValue)); - expectedException.expect(MessageException.class); - expectedException.expectMessage("a JVM option can't overwrite mandatory JVM options. " + - "The following JVM options defined by property '" + randomPropertyName + "' are invalid: " + - overriding1 + " overwrites " + randomPrefix + randomValue + ", " + overriding2 + " overwrites " + randomPrefix + randomValue); - - underTest.addFromMandatoryProperty(new Props(properties), randomPropertyName); + assertThatThrownBy(() -> underTest.addFromMandatoryProperty(new Props(properties), randomPropertyName)) + .isInstanceOf(MessageException.class) + .hasMessage("a JVM option can't overwrite mandatory JVM options. " + + "The following JVM options defined by property '" + randomPropertyName + "' are invalid: " + + overriding1 + " overwrites " + randomPrefix + randomValue + ", " + overriding2 + " overwrites " + randomPrefix + randomValue); } @Test @@ -362,25 +341,29 @@ public class JvmOptionsTest { assertThat(underTest.toString()).isEqualTo("[-foo, -bar]"); } - private void expectJvmOptionNotNullNPE() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("a JVM option can't be null"); + private void expectJvmOptionNotNullNPE(ThrowingCallable callback) { + assertThatThrownBy(callback) + .isInstanceOf(NullPointerException.class) + .hasMessage("a JVM option can't be null"); } - private void expectJvmOptionNotEmptyAndStartByDashIAE() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("a JVM option can't be empty and must start with '-'"); + private void expectJvmOptionNotEmptyAndStartByDashIAE(ThrowingCallable callback) { + assertThatThrownBy(callback) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("a JVM option can't be empty and must start with '-'"); } - private void expectJvmOptionNotEmptyAndStartByDashMessageException(String randomPropertyName, String option) { - expectedException.expect(MessageException.class); - expectedException.expectMessage("a JVM option can't be empty and must start with '-'. " + - "The following JVM options defined by property '" + randomPropertyName + "' are invalid: " + option); + private void expectJvmOptionNotEmptyAndStartByDashMessageException(ThrowingCallable callback, String randomPropertyName, String option) { + assertThatThrownBy(callback) + .isInstanceOf(MessageException.class) + .hasMessage("a JVM option can't be empty and must start with '-'. " + + "The following JVM options defined by property '" + randomPropertyName + "' are invalid: " + option); } - public void expectMissingPropertyIAE(String randomPropertyName) { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Missing property: " + randomPropertyName); + public void expectMissingPropertyIAE(ThrowingCallable callback, String randomPropertyName) { + assertThatThrownBy(callback) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Missing property: " + randomPropertyName); } @DataProvider() diff --git a/server/sonar-main/src/test/java/org/sonar/application/config/AppSettingsLoaderImplTest.java b/server/sonar-main/src/test/java/org/sonar/application/config/AppSettingsLoaderImplTest.java index 25be8bab784..0a6a756f232 100644 --- a/server/sonar-main/src/test/java/org/sonar/application/config/AppSettingsLoaderImplTest.java +++ b/server/sonar-main/src/test/java/org/sonar/application/config/AppSettingsLoaderImplTest.java @@ -27,21 +27,19 @@ import org.apache.commons.io.FileUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.sonar.core.extension.ServiceLoaderWrapper; import org.sonar.process.System2; import static java.nio.charset.StandardCharsets.UTF_8; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.data.MapEntry.entry; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class AppSettingsLoaderImplTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public TemporaryFolder temp = new TemporaryFolder(); @@ -115,10 +113,9 @@ public class AppSettingsLoaderImplTest { FileUtils.forceMkdir(propsFileAsDir); AppSettingsLoaderImpl underTest = new AppSettingsLoaderImpl(system, new String[0], homeDir, serviceLoaderWrapper); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Cannot open file " + propsFileAsDir.getAbsolutePath()); - - underTest.load(); + assertThatThrownBy(() -> underTest.load()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Cannot open file " + propsFileAsDir.getAbsolutePath()); } @Test diff --git a/server/sonar-main/src/test/java/org/sonar/application/config/CommandLineParserTest.java b/server/sonar-main/src/test/java/org/sonar/application/config/CommandLineParserTest.java index 0b2dbfa9e1b..5995ed90606 100644 --- a/server/sonar-main/src/test/java/org/sonar/application/config/CommandLineParserTest.java +++ b/server/sonar-main/src/test/java/org/sonar/application/config/CommandLineParserTest.java @@ -20,17 +20,12 @@ package org.sonar.application.config; import java.util.Properties; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class CommandLineParserTest { - - @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Test public void parseArguments() { System.setProperty("CommandLineParserTest.unused", "unused"); @@ -53,9 +48,8 @@ public class CommandLineParserTest { assertThat(p.getProperty("sonar.foo")).isEqualTo("bar"); assertThat(p.getProperty("sonar.whitespace")).isEqualTo("foo bar"); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Command-line argument must start with -D, for example -Dsonar.jdbc.username=sonar. Got: sonar.bad=true"); - - CommandLineParser.argumentsToProperties(new String[] {"-Dsonar.foo=bar", "sonar.bad=true"}); + assertThatThrownBy(() -> CommandLineParser.argumentsToProperties(new String[] {"-Dsonar.foo=bar", "sonar.bad=true"})) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Command-line argument must start with -D, for example -Dsonar.jdbc.username=sonar. Got: sonar.bad=true"); } } diff --git a/server/sonar-main/src/test/java/org/sonar/application/config/FileSystemSettingsTest.java b/server/sonar-main/src/test/java/org/sonar/application/config/FileSystemSettingsTest.java index 06de61a000e..95cfbe80344 100644 --- a/server/sonar-main/src/test/java/org/sonar/application/config/FileSystemSettingsTest.java +++ b/server/sonar-main/src/test/java/org/sonar/application/config/FileSystemSettingsTest.java @@ -24,7 +24,6 @@ import java.util.Properties; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.sonar.process.Props; @@ -39,8 +38,6 @@ public class FileSystemSettingsTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private FileSystemSettings underTest = new FileSystemSettings(); private File homeDir; diff --git a/server/sonar-main/src/test/java/org/sonar/application/config/JdbcSettingsTest.java b/server/sonar-main/src/test/java/org/sonar/application/config/JdbcSettingsTest.java index e7fabff08ca..64b8b3f98c7 100644 --- a/server/sonar-main/src/test/java/org/sonar/application/config/JdbcSettingsTest.java +++ b/server/sonar-main/src/test/java/org/sonar/application/config/JdbcSettingsTest.java @@ -26,12 +26,12 @@ import org.apache.commons.io.FileUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.sonar.process.MessageException; import org.sonar.process.Props; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.application.config.JdbcSettings.Provider; import static org.sonar.process.ProcessProperties.Property.JDBC_DRIVER_PATH; import static org.sonar.process.ProcessProperties.Property.JDBC_URL; @@ -39,8 +39,6 @@ import static org.sonar.process.ProcessProperties.Property.PATH_HOME; public class JdbcSettingsTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public TemporaryFolder temp = new TemporaryFolder(); @@ -92,20 +90,18 @@ public class JdbcSettingsTest { public void fail_with_MessageException_when_provider_is_not_supported() { Props props = newProps(JDBC_URL.getKey(), "jdbc:microsoft:sqlserver://localhost"); - expectedException.expect(MessageException.class); - expectedException.expectMessage("Unsupported JDBC driver provider: microsoft"); - - underTest.resolveProviderAndEnforceNonnullJdbcUrl(props); + assertThatThrownBy(() -> underTest.resolveProviderAndEnforceNonnullJdbcUrl(props)) + .isInstanceOf(MessageException.class) + .hasMessage("Unsupported JDBC driver provider: microsoft"); } @Test public void fail_with_MessageException_when_url_does_not_have_jdbc_prefix() { Props props = newProps(JDBC_URL.getKey(), "oracle:thin:@localhost/XE"); - expectedException.expect(MessageException.class); - expectedException.expectMessage("Bad format of JDBC URL: oracle:thin:@localhost/XE"); - - underTest.resolveProviderAndEnforceNonnullJdbcUrl(props); + assertThatThrownBy(() -> underTest.resolveProviderAndEnforceNonnullJdbcUrl(props)) + .isInstanceOf(MessageException.class) + .hasMessage("Bad format of JDBC URL: oracle:thin:@localhost/XE"); } @Test @@ -159,20 +155,18 @@ public class JdbcSettingsTest { @Test public void driver_dir_does_not_exist() { - expectedException.expect(MessageException.class); - expectedException.expectMessage("Directory does not exist: extensions/jdbc-driver/oracle"); - - underTest.driverPath(homeDir, Provider.ORACLE); + assertThatThrownBy(() -> underTest.driverPath(homeDir, Provider.ORACLE)) + .isInstanceOf(MessageException.class) + .hasMessage("Directory does not exist: extensions/jdbc-driver/oracle"); } @Test public void no_files_in_driver_dir() throws Exception { FileUtils.forceMkdir(new File(homeDir, "extensions/jdbc-driver/oracle")); - expectedException.expect(MessageException.class); - expectedException.expectMessage("Directory does not contain JDBC driver: extensions/jdbc-driver/oracle"); - - underTest.driverPath(homeDir, Provider.ORACLE); + assertThatThrownBy(() -> underTest.driverPath(homeDir, Provider.ORACLE)) + .isInstanceOf(MessageException.class) + .hasMessage("Directory does not contain JDBC driver: extensions/jdbc-driver/oracle"); } @Test @@ -180,10 +174,9 @@ public class JdbcSettingsTest { FileUtils.touch(new File(homeDir, "extensions/jdbc-driver/oracle/ojdbc5.jar")); FileUtils.touch(new File(homeDir, "extensions/jdbc-driver/oracle/ojdbc6.jar")); - expectedException.expect(MessageException.class); - expectedException.expectMessage("Directory must contain only one JAR file: extensions/jdbc-driver/oracle"); - - underTest.driverPath(homeDir, Provider.ORACLE); + assertThatThrownBy(() -> underTest.driverPath(homeDir, Provider.ORACLE)) + .isInstanceOf(MessageException.class) + .hasMessage("Directory must contain only one JAR file: extensions/jdbc-driver/oracle"); } private Props newProps(String... params) { diff --git a/server/sonar-main/src/test/java/org/sonar/application/es/EsInstallationTest.java b/server/sonar-main/src/test/java/org/sonar/application/es/EsInstallationTest.java index bb1f4006a60..891563fc180 100644 --- a/server/sonar-main/src/test/java/org/sonar/application/es/EsInstallationTest.java +++ b/server/sonar-main/src/test/java/org/sonar/application/es/EsInstallationTest.java @@ -24,11 +24,11 @@ import java.io.IOException; import java.util.Properties; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.sonar.process.Props; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.process.ProcessProperties.Property.PATH_DATA; import static org.sonar.process.ProcessProperties.Property.PATH_HOME; import static org.sonar.process.ProcessProperties.Property.PATH_LOGS; @@ -38,17 +38,14 @@ public class EsInstallationTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void constructor_fails_with_IAE_if_sq_home_property_is_not_defined() { Props props = new Props(new Properties()); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Property sonar.path.home is not set"); - - new EsInstallation(props); + assertThatThrownBy(() -> new EsInstallation(props)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Property sonar.path.home is not set"); } @Test @@ -57,10 +54,9 @@ public class EsInstallationTest { props.set(PATH_DATA.getKey(), temp.newFolder().getAbsolutePath()); props.set(PATH_HOME.getKey(), temp.newFolder().getAbsolutePath()); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Property sonar.path.temp is not set"); - - new EsInstallation(props); + assertThatThrownBy(() -> new EsInstallation(props)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Property sonar.path.temp is not set"); } @Test @@ -68,10 +64,9 @@ public class EsInstallationTest { Props props = new Props(new Properties()); props.set(PATH_HOME.getKey(), temp.newFolder().getAbsolutePath()); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Missing property: sonar.path.data"); - - new EsInstallation(props); + assertThatThrownBy(() -> new EsInstallation(props)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Missing property: sonar.path.data"); } @Test diff --git a/server/sonar-main/src/test/java/org/sonar/application/es/EsYmlSettingsTest.java b/server/sonar-main/src/test/java/org/sonar/application/es/EsYmlSettingsTest.java index 7001fa4a6be..021f985629e 100644 --- a/server/sonar-main/src/test/java/org/sonar/application/es/EsYmlSettingsTest.java +++ b/server/sonar-main/src/test/java/org/sonar/application/es/EsYmlSettingsTest.java @@ -24,17 +24,15 @@ import java.io.IOException; import java.util.HashMap; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class EsYmlSettingsTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void test_generation_of_file() throws IOException { @@ -55,9 +53,8 @@ public class EsYmlSettingsTest { File yamlFile = temp.newFile(); yamlFile.setReadOnly(); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Cannot write Elasticsearch yml settings file"); - - new EsYmlSettings(new HashMap<>()).writeToYmlSettingsFile(yamlFile); + assertThatThrownBy(() -> new EsYmlSettings(new HashMap<>()).writeToYmlSettingsFile(yamlFile)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Cannot write Elasticsearch yml settings file"); } } diff --git a/server/sonar-main/src/test/java/org/sonar/application/process/ManagedProcessHandlerTest.java b/server/sonar-main/src/test/java/org/sonar/application/process/ManagedProcessHandlerTest.java index 31a296352b4..ef49a2b407b 100644 --- a/server/sonar-main/src/test/java/org/sonar/application/process/ManagedProcessHandlerTest.java +++ b/server/sonar-main/src/test/java/org/sonar/application/process/ManagedProcessHandlerTest.java @@ -26,13 +26,13 @@ import org.awaitility.Awaitility; import org.junit.Rule; import org.junit.Test; import org.junit.rules.DisableOnDebug; -import org.junit.rules.ExpectedException; import org.junit.rules.TestRule; import org.junit.rules.Timeout; import org.mockito.Mockito; import org.sonar.process.ProcessId; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.verify; @@ -43,8 +43,6 @@ public class ManagedProcessHandlerTest { private static final ProcessId A_PROCESS_ID = ProcessId.ELASTICSEARCH; - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public TestRule safeguardTimeout = new DisableOnDebug(Timeout.seconds(60)); @@ -105,13 +103,14 @@ public class ManagedProcessHandlerTest { public void start_throws_exception_and_move_to_state_STOPPED_if_execution_of_command_fails() { ManagedProcessHandler underTest = newHanderBuilder(A_PROCESS_ID).build(); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("error"); - - underTest.start(() -> { - throw new IllegalStateException("error"); - }); - assertThat(underTest.getState()).isEqualTo(ManagedProcessLifecycle.State.STOPPED); + assertThatThrownBy(() -> { + underTest.start(() -> { + throw new IllegalStateException("error"); + }); + assertThat(underTest.getState()).isEqualTo(ManagedProcessLifecycle.State.STOPPED); + }) + .isInstanceOf(IllegalStateException.class) + .hasMessage("error"); } @Test diff --git a/server/sonar-main/src/test/java/org/sonar/application/process/ProcessCommandsManagedProcessTest.java b/server/sonar-main/src/test/java/org/sonar/application/process/ProcessCommandsManagedProcessTest.java index 6e414ad7fc4..082e775d91c 100644 --- a/server/sonar-main/src/test/java/org/sonar/application/process/ProcessCommandsManagedProcessTest.java +++ b/server/sonar-main/src/test/java/org/sonar/application/process/ProcessCommandsManagedProcessTest.java @@ -24,8 +24,8 @@ import java.io.InputStream; import java.util.concurrent.TimeUnit; import org.junit.Test; import org.mockito.Mockito; -import org.sonar.process.sharedmemoryfile.ProcessCommands; import org.sonar.process.ProcessId; +import org.sonar.process.sharedmemoryfile.ProcessCommands; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; @@ -33,8 +33,6 @@ import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; - - public class ProcessCommandsManagedProcessTest { @Test diff --git a/server/sonar-process/src/main/java/org/sonar/process/ProcessId.java b/server/sonar-process/src/main/java/org/sonar/process/ProcessId.java index 59140512af6..f6f58c290de 100644 --- a/server/sonar-process/src/main/java/org/sonar/process/ProcessId.java +++ b/server/sonar-process/src/main/java/org/sonar/process/ProcessId.java @@ -31,8 +31,6 @@ public enum ProcessId { private final String key; private final int ipcIndex; private final String logFilenamePrefix; - - ProcessId(String key, int ipcIndex, String logFilenamePrefix) { this.key = key; this.ipcIndex = ipcIndex; diff --git a/server/sonar-process/src/main/java/org/sonar/process/ProcessProperties.java b/server/sonar-process/src/main/java/org/sonar/process/ProcessProperties.java index fe9e97951e8..c23d684c859 100644 --- a/server/sonar-process/src/main/java/org/sonar/process/ProcessProperties.java +++ b/server/sonar-process/src/main/java/org/sonar/process/ProcessProperties.java @@ -131,8 +131,6 @@ public class ProcessProperties { CLUSTER_ES_TRUSTSTORE("sonar.cluster.es.ssl.truststore"), CLUSTER_ES_KEYSTORE_PASSWORD("sonar.cluster.es.ssl.keystorePassword"), CLUSTER_ES_TRUSTSTORE_PASSWORD("sonar.cluster.es.ssl.truststorePassword"), - - // search node only settings CLUSTER_ES_HOSTS("sonar.cluster.es.hosts"), CLUSTER_ES_DISCOVERY_SEED_HOSTS("sonar.cluster.es.discovery.seed.hosts"), diff --git a/server/sonar-process/src/test/java/org/sonar/process/FileUtils2Test.java b/server/sonar-process/src/test/java/org/sonar/process/FileUtils2Test.java index a48b9f5ac71..af2afddf91f 100644 --- a/server/sonar-process/src/test/java/org/sonar/process/FileUtils2Test.java +++ b/server/sonar-process/src/test/java/org/sonar/process/FileUtils2Test.java @@ -27,26 +27,23 @@ import java.nio.file.attribute.BasicFileAttributes; import javax.annotation.CheckForNull; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.SystemUtils; +import org.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import static java.nio.charset.StandardCharsets.UTF_8; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assume.assumeTrue; public class FileUtils2Test { @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void cleanDirectory_throws_NPE_if_file_is_null() throws IOException { - expectDirectoryCanNotBeNullNPE(); - - FileUtils2.cleanDirectory(null); + expectDirectoryCanNotBeNullNPE(() -> FileUtils2.cleanDirectory(null)); } @Test @@ -58,10 +55,9 @@ public class FileUtils2Test { public void cleanDirectory_throws_IAE_if_argument_is_a_file() throws IOException { File file = temporaryFolder.newFile(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("'" + file.getAbsolutePath() + "' is not a directory"); - - FileUtils2.cleanDirectory(file); + assertThatThrownBy(() -> FileUtils2.cleanDirectory(file)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("'" + file.getAbsolutePath() + "' is not a directory"); } @Test @@ -178,9 +174,7 @@ public class FileUtils2Test { @Test public void deleteDirectory_throws_NPE_if_argument_is_null() throws IOException { - expectDirectoryCanNotBeNullNPE(); - - FileUtils2.deleteDirectory(null); + expectDirectoryCanNotBeNullNPE(() -> FileUtils2.deleteDirectory(null)); } @Test @@ -194,10 +188,9 @@ public class FileUtils2Test { public void deleteDirectory_throws_IOE_if_argument_is_a_file() throws IOException { File file = temporaryFolder.newFile(); - expectedException.expect(IOException.class); - expectedException.expectMessage("Directory '" + file.getAbsolutePath() + "' is a file"); - - FileUtils2.deleteDirectory(file); + assertThatThrownBy(() -> FileUtils2.deleteDirectory(file)) + .isInstanceOf(IOException.class) + .hasMessage("Directory '" + file.getAbsolutePath() + "' is a file"); } @Test @@ -210,10 +203,9 @@ public class FileUtils2Test { assertThat(file1).isRegularFile(); assertThat(symLink).isSymbolicLink(); - expectedException.expect(IOException.class); - expectedException.expectMessage("Directory '" + symLink.toFile().getAbsolutePath() + "' is a symbolic link"); - - FileUtils2.deleteDirectory(symLink.toFile()); + assertThatThrownBy(() -> FileUtils2.deleteDirectory(symLink.toFile())) + .isInstanceOf(IOException.class) + .hasMessage("Directory '" + symLink.toFile().getAbsolutePath() + "' is a symbolic link"); } @Test @@ -276,9 +268,8 @@ public class FileUtils2Test { Path path = temporaryFolder.newFile().toPath(); Files.delete(path); - expectedException.expect(IOException.class); - - FileUtils2.sizeOf(path); + assertThatThrownBy(() -> FileUtils2.sizeOf(path)) + .isInstanceOf(IOException.class); } @Test @@ -297,9 +288,10 @@ public class FileUtils2Test { .isEqualTo(FileUtils2.sizeOf(child.toPath())); } - private void expectDirectoryCanNotBeNullNPE() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("Directory can not be null"); + private void expectDirectoryCanNotBeNullNPE(ThrowingCallable callback) { + assertThatThrownBy(callback) + .isInstanceOf(NullPointerException.class) + .hasMessage("Directory can not be null"); } @CheckForNull diff --git a/server/sonar-process/src/test/java/org/sonar/process/JmxTest.java b/server/sonar-process/src/test/java/org/sonar/process/JmxTest.java index 5313876d868..856b7878c1b 100644 --- a/server/sonar-process/src/test/java/org/sonar/process/JmxTest.java +++ b/server/sonar-process/src/test/java/org/sonar/process/JmxTest.java @@ -24,20 +24,17 @@ import javax.annotation.CheckForNull; import javax.management.InstanceNotFoundException; import javax.management.ObjectInstance; import javax.management.ObjectName; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.process.jmx.Fake; import org.sonar.process.jmx.FakeMBean; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class JmxTest { static final String FAKE_NAME = "SonarQube:name=Fake"; - @Rule - public ExpectedException expectedException = ExpectedException.none(); FakeMBean mbean = new Fake(); @@ -60,18 +57,16 @@ public class JmxTest { @Test public void register_fails_if_mbean_interface_can_not_be_found() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Can not find the MBean interface of class java.lang.String"); - - Jmx.register(FAKE_NAME, "not a mbean"); + assertThatThrownBy(() -> Jmx.register(FAKE_NAME, "not a mbean")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Can not find the MBean interface of class java.lang.String"); } @Test public void register_fails_if_name_is_not_valid() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Can not register MBean [/]"); - - Jmx.register("/", new Fake()); + assertThatThrownBy(() -> Jmx.register("/", new Fake())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Can not register MBean [/]"); } @Test diff --git a/server/sonar-process/src/test/java/org/sonar/process/NetworkUtilsImplTest.java b/server/sonar-process/src/test/java/org/sonar/process/NetworkUtilsImplTest.java index 063d502aa0a..5dddd8622fc 100644 --- a/server/sonar-process/src/test/java/org/sonar/process/NetworkUtilsImplTest.java +++ b/server/sonar-process/src/test/java/org/sonar/process/NetworkUtilsImplTest.java @@ -27,9 +27,7 @@ import java.util.HashSet; import java.util.Optional; import java.util.Set; import org.hamcrest.CoreMatchers; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.assertj.core.api.Assertions.assertThat; @@ -37,8 +35,6 @@ import static org.junit.Assume.assumeThat; public class NetworkUtilsImplTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private NetworkUtilsImpl underTest = new NetworkUtilsImpl(); diff --git a/server/sonar-process/src/test/java/org/sonar/process/ProcessIdTest.java b/server/sonar-process/src/test/java/org/sonar/process/ProcessIdTest.java index 17e2da74d4d..e17b77b7921 100644 --- a/server/sonar-process/src/test/java/org/sonar/process/ProcessIdTest.java +++ b/server/sonar-process/src/test/java/org/sonar/process/ProcessIdTest.java @@ -21,16 +21,13 @@ package org.sonar.process; import java.util.HashSet; import java.util.Set; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class ProcessIdTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void test_constants() { @@ -60,17 +57,15 @@ public class ProcessIdTest { @Test public void fromKey_throws_IAE_if_key_is_null() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Process [null] does not exist"); - - ProcessId.fromKey(null); + assertThatThrownBy(() -> ProcessId.fromKey(null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Process [null] does not exist"); } @Test public void fromKey_throws_IAE_if_key_does_not_exist() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Process [foo] does not exist"); - - ProcessId.fromKey("foo"); + assertThatThrownBy(() -> ProcessId.fromKey("foo")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Process [foo] does not exist"); } } diff --git a/server/sonar-process/src/test/java/org/sonar/process/PropsTest.java b/server/sonar-process/src/test/java/org/sonar/process/PropsTest.java index 9821fd0bb19..ebbb0e557ab 100644 --- a/server/sonar-process/src/test/java/org/sonar/process/PropsTest.java +++ b/server/sonar-process/src/test/java/org/sonar/process/PropsTest.java @@ -28,11 +28,11 @@ import java.util.Properties; import org.apache.commons.lang.RandomStringUtils; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.fail; @RunWith(DataProviderRunner.class) @@ -40,8 +40,6 @@ public class PropsTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test @UseDataProvider("beforeAndAfterBlanks") @@ -89,10 +87,9 @@ public class PropsTest { public void nonNullValue_throws_IAE_on_non_existing_key() { Props props = new Props(new Properties()); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Missing property: other"); - - props.nonNullValue("other"); + assertThatThrownBy(() -> props.nonNullValue("other")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Missing property: other"); } @Test diff --git a/server/sonar-process/src/test/java/org/sonar/process/SystemExitTest.java b/server/sonar-process/src/test/java/org/sonar/process/SystemExitTest.java index f75569ab83a..d97a98808a3 100644 --- a/server/sonar-process/src/test/java/org/sonar/process/SystemExitTest.java +++ b/server/sonar-process/src/test/java/org/sonar/process/SystemExitTest.java @@ -19,9 +19,8 @@ */ package org.sonar.process; -import org.junit.Test; - import java.util.concurrent.atomic.AtomicInteger; +import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; diff --git a/server/sonar-process/src/test/java/org/sonar/process/cluster/NodeTypeTest.java b/server/sonar-process/src/test/java/org/sonar/process/cluster/NodeTypeTest.java index fd34e55090f..3f96799ebf5 100644 --- a/server/sonar-process/src/test/java/org/sonar/process/cluster/NodeTypeTest.java +++ b/server/sonar-process/src/test/java/org/sonar/process/cluster/NodeTypeTest.java @@ -19,16 +19,13 @@ */ package org.sonar.process.cluster; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class NodeTypeTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void test_parse() { @@ -38,9 +35,8 @@ public class NodeTypeTest { @Test public void parse_an_unknown_value_must_throw_IAE() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Invalid value: XYZ"); - - NodeType.parse("XYZ"); + assertThatThrownBy(() -> NodeType.parse("XYZ")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Invalid value: XYZ"); } } diff --git a/server/sonar-process/src/test/java/org/sonar/process/cluster/health/HealthStateRefresherTest.java b/server/sonar-process/src/test/java/org/sonar/process/cluster/health/HealthStateRefresherTest.java index 7f72e819238..f9c6e4ffd94 100644 --- a/server/sonar-process/src/test/java/org/sonar/process/cluster/health/HealthStateRefresherTest.java +++ b/server/sonar-process/src/test/java/org/sonar/process/cluster/health/HealthStateRefresherTest.java @@ -24,7 +24,6 @@ import java.util.Random; import java.util.concurrent.TimeUnit; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; import org.sonar.process.LoggingRule; @@ -41,8 +40,6 @@ import static org.slf4j.event.Level.DEBUG; import static org.slf4j.event.Level.ERROR; public class HealthStateRefresherTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public LoggingRule logging = new LoggingRule(HealthStateRefresher.class); diff --git a/server/sonar-process/src/test/java/org/sonar/process/cluster/health/NodeDetailsTest.java b/server/sonar-process/src/test/java/org/sonar/process/cluster/health/NodeDetailsTest.java index 92f736a1208..ab4ebedf871 100644 --- a/server/sonar-process/src/test/java/org/sonar/process/cluster/health/NodeDetailsTest.java +++ b/server/sonar-process/src/test/java/org/sonar/process/cluster/health/NodeDetailsTest.java @@ -23,17 +23,14 @@ import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.util.Random; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.process.cluster.health.NodeDetails.newNodeDetailsBuilder; public class NodeDetailsTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private Random random = new Random(); private NodeDetailsTestSupport testSupport = new NodeDetailsTestSupport(random); @@ -42,82 +39,72 @@ public class NodeDetailsTest { @Test public void setType_throws_NPE_if_arg_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("type can't be null"); - - builderUnderTest.setType(null); + assertThatThrownBy(() -> builderUnderTest.setType(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("type can't be null"); } @Test public void setName_throws_NPE_if_arg_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("name can't be null"); - - builderUnderTest.setName(null); + assertThatThrownBy(() -> builderUnderTest.setName(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("name can't be null"); } @Test public void setName_throws_IAE_if_arg_is_empty() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("name can't be empty"); - - builderUnderTest.setName(""); + assertThatThrownBy(() -> builderUnderTest.setName("")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("name can't be empty"); } @Test public void setName_throws_IAE_if_arg_is_empty_after_trim() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("name can't be empty"); - - builderUnderTest.setName(" "); + assertThatThrownBy(() -> builderUnderTest.setName(" ")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("name can't be empty"); } @Test public void setHost_throws_NPE_if_arg_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("host can't be null"); - - builderUnderTest.setHost(null); + assertThatThrownBy(() -> builderUnderTest.setHost(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("host can't be null"); } @Test public void setHost_throws_IAE_if_arg_is_empty() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("host can't be empty"); - - builderUnderTest.setHost(""); + assertThatThrownBy(() -> builderUnderTest.setHost("")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("host can't be empty"); } @Test public void setHost_throws_IAE_if_arg_is_empty_after_trim() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("host can't be empty"); - - builderUnderTest.setHost(" "); + assertThatThrownBy(() -> builderUnderTest.setHost(" ")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("host can't be empty"); } @Test public void setPort_throws_IAE_if_arg_is_less_than_1() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("port must be > 0"); - - builderUnderTest.setPort(-random.nextInt(5)); + assertThatThrownBy(() -> builderUnderTest.setPort(-random.nextInt(5))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("port must be > 0"); } @Test public void setStarted_throws_IAE_if_arg_is_less_than_1() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("startedAt must be > 0"); - - builderUnderTest.setStartedAt(-random.nextInt(5)); + assertThatThrownBy(() -> builderUnderTest.setStartedAt(-random.nextInt(5))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("startedAt must be > 0"); } @Test public void build_throws_NPE_if_type_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("type can't be null"); - - builderUnderTest.build(); + assertThatThrownBy(() -> builderUnderTest.build()) + .isInstanceOf(NullPointerException.class) + .hasMessage("type can't be null"); } @Test @@ -125,10 +112,9 @@ public class NodeDetailsTest { builderUnderTest .setType(randomType); - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("name can't be null"); - - builderUnderTest.build(); + assertThatThrownBy(() -> builderUnderTest.build()) + .isInstanceOf(NullPointerException.class) + .hasMessage("name can't be null"); } @Test @@ -137,10 +123,9 @@ public class NodeDetailsTest { .setType(randomType) .setName(randomAlphanumeric(2)); - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("host can't be null"); - - builderUnderTest.build(); + assertThatThrownBy(() -> builderUnderTest.build()) + .isInstanceOf(NullPointerException.class) + .hasMessage("host can't be null"); } @Test @@ -150,10 +135,9 @@ public class NodeDetailsTest { .setName(randomAlphanumeric(2)) .setHost(randomAlphanumeric(3)); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("port must be > 0"); - - builderUnderTest.build(); + assertThatThrownBy(() -> builderUnderTest.build()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("port must be > 0"); } @Test @@ -164,10 +148,9 @@ public class NodeDetailsTest { .setHost(randomAlphanumeric(3)) .setPort(1 + random.nextInt(33)); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("startedAt must be > 0"); - - builderUnderTest.build(); + assertThatThrownBy(() -> builderUnderTest.build()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("startedAt must be > 0"); } @Test diff --git a/server/sonar-process/src/test/java/org/sonar/process/cluster/health/NodeHealthTest.java b/server/sonar-process/src/test/java/org/sonar/process/cluster/health/NodeHealthTest.java index 067fafb49d0..d69d6a5c1b2 100644 --- a/server/sonar-process/src/test/java/org/sonar/process/cluster/health/NodeHealthTest.java +++ b/server/sonar-process/src/test/java/org/sonar/process/cluster/health/NodeHealthTest.java @@ -25,17 +25,14 @@ import java.io.ObjectInputStream; import java.util.Arrays; import java.util.Random; import java.util.stream.IntStream; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.process.cluster.health.NodeHealth.newNodeHealthBuilder; public class NodeHealthTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private Random random = new Random(); private NodeDetailsTestSupport testSupport = new NodeDetailsTestSupport(random); @@ -44,36 +41,32 @@ public class NodeHealthTest { @Test public void setStatus_throws_NPE_if_arg_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("status can't be null"); - - builderUnderTest.setStatus(null); + assertThatThrownBy(() -> builderUnderTest.setStatus(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("status can't be null"); } @Test public void setDetails_throws_NPE_if_arg_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("details can't be null"); - - builderUnderTest.setDetails(null); + assertThatThrownBy(() -> builderUnderTest.setDetails(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("details can't be null"); } @Test public void build_throws_NPE_if_status_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("status can't be null"); - - builderUnderTest.build(); + assertThatThrownBy(() -> builderUnderTest.build()) + .isInstanceOf(NullPointerException.class) + .hasMessage("status can't be null"); } @Test public void build_throws_NPE_if_details_is_null() { builderUnderTest.setStatus(randomStatus); - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("details can't be null"); - - builderUnderTest.build(); + assertThatThrownBy(() -> builderUnderTest.build()) + .isInstanceOf(NullPointerException.class) + .hasMessage("details can't be null"); } @Test diff --git a/server/sonar-process/src/test/java/org/sonar/process/cluster/health/SharedHealthStateImplTest.java b/server/sonar-process/src/test/java/org/sonar/process/cluster/health/SharedHealthStateImplTest.java index fdd9b44bfc7..98a9bba3f38 100644 --- a/server/sonar-process/src/test/java/org/sonar/process/cluster/health/SharedHealthStateImplTest.java +++ b/server/sonar-process/src/test/java/org/sonar/process/cluster/health/SharedHealthStateImplTest.java @@ -27,7 +27,6 @@ import java.util.UUID; import java.util.stream.IntStream; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.slf4j.event.Level; import org.sonar.process.LoggingRule; import org.sonar.process.cluster.hz.HazelcastMember; @@ -35,6 +34,7 @@ import org.sonar.process.cluster.hz.HazelcastMember; import static java.util.Collections.singleton; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -46,8 +46,6 @@ import static org.sonar.process.cluster.health.NodeHealth.newNodeHealthBuilder; public class SharedHealthStateImplTest { private static final String MAP_SQ_HEALTH_STATE = "sq_health_state"; - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public LoggingRule logging = new LoggingRule(SharedHealthStateImpl.class); @@ -58,10 +56,9 @@ public class SharedHealthStateImplTest { @Test public void write_fails_with_NPE_if_arg_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("nodeHealth can't be null"); - - underTest.writeMine(null); + assertThatThrownBy(() -> underTest.writeMine(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("nodeHealth can't be null"); } @Test diff --git a/server/sonar-process/src/test/java/org/sonar/process/cluster/hz/DistributedAnswerTest.java b/server/sonar-process/src/test/java/org/sonar/process/cluster/hz/DistributedAnswerTest.java index 4562615320b..8e3b0508a22 100644 --- a/server/sonar-process/src/test/java/org/sonar/process/cluster/hz/DistributedAnswerTest.java +++ b/server/sonar-process/src/test/java/org/sonar/process/cluster/hz/DistributedAnswerTest.java @@ -22,19 +22,16 @@ package org.sonar.process.cluster.hz; import com.hazelcast.cluster.Member; import java.io.IOException; import java.util.UUID; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.process.cluster.hz.HazelcastMember.Attribute.NODE_NAME; public class DistributedAnswerTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private final Member member = newMember(UUID.randomUUID()); private final DistributedAnswer underTest = new DistributedAnswer<>(); @@ -117,10 +114,9 @@ public class DistributedAnswerTest { underTest.setAnswer(newMember(uuid), "baz"); underTest.setTimedOut(newMember(otherUuid)); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Distributed cluster action timed out in cluster nodes " + otherUuid); - - underTest.propagateExceptions(); + assertThatThrownBy(underTest::propagateExceptions) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Distributed cluster action timed out in cluster nodes " + otherUuid); } @Test @@ -131,10 +127,9 @@ public class DistributedAnswerTest { underTest.setAnswer(newMember(bar), "baz"); underTest.setFailed(newMember(foo), new IOException("BOOM")); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Distributed cluster action in cluster nodes " + foo + " (other nodes may have timed out)"); - - underTest.propagateExceptions(); + assertThatThrownBy(underTest::propagateExceptions) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Distributed cluster action in cluster nodes " + foo + " (other nodes may have timed out)"); } private static Member newMember(UUID uuid) { diff --git a/server/sonar-process/src/test/java/org/sonar/process/cluster/hz/HazelcastMemberBuilderTest.java b/server/sonar-process/src/test/java/org/sonar/process/cluster/hz/HazelcastMemberBuilderTest.java index 1586ef7e9e7..f9e1a06c374 100644 --- a/server/sonar-process/src/test/java/org/sonar/process/cluster/hz/HazelcastMemberBuilderTest.java +++ b/server/sonar-process/src/test/java/org/sonar/process/cluster/hz/HazelcastMemberBuilderTest.java @@ -20,7 +20,6 @@ package org.sonar.process.cluster.hz; import java.net.InetAddress; -import java.util.Collections; import org.junit.Rule; import org.junit.Test; import org.junit.rules.DisableOnDebug; diff --git a/server/sonar-process/src/test/java/org/sonar/process/cluster/hz/HazelcastMemberImplTest.java b/server/sonar-process/src/test/java/org/sonar/process/cluster/hz/HazelcastMemberImplTest.java index eebdff9b9d3..6d8f4a44323 100644 --- a/server/sonar-process/src/test/java/org/sonar/process/cluster/hz/HazelcastMemberImplTest.java +++ b/server/sonar-process/src/test/java/org/sonar/process/cluster/hz/HazelcastMemberImplTest.java @@ -32,7 +32,6 @@ import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.DisableOnDebug; -import org.junit.rules.ExpectedException; import org.junit.rules.TestRule; import org.junit.rules.Timeout; import org.sonar.process.NetworkUtilsImpl; @@ -42,8 +41,6 @@ import static org.assertj.core.api.Assertions.assertThat; public class HazelcastMemberImplTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public TestRule safeguardTimeout = new DisableOnDebug(Timeout.seconds(60)); diff --git a/server/sonar-process/src/test/java/org/sonar/process/logging/LogLevelConfigTest.java b/server/sonar-process/src/test/java/org/sonar/process/logging/LogLevelConfigTest.java index 59c23fcae16..a9cf5d6ae5f 100644 --- a/server/sonar-process/src/test/java/org/sonar/process/logging/LogLevelConfigTest.java +++ b/server/sonar-process/src/test/java/org/sonar/process/logging/LogLevelConfigTest.java @@ -22,28 +22,24 @@ package org.sonar.process.logging; import ch.qos.logback.classic.Level; import java.util.Collections; import org.apache.commons.lang.RandomStringUtils; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.process.ProcessId; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Fail.fail; import static org.sonar.process.logging.LogLevelConfig.newBuilder; public class LogLevelConfigTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private final String rootLoggerName = RandomStringUtils.randomAlphabetic(20); private LogLevelConfig.Builder underTest = newBuilder(rootLoggerName); @Test public void newBuilder_throws_NPE_if_rootLoggerName_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("rootLoggerName can't be null"); - - newBuilder(null); + assertThatThrownBy(() -> newBuilder(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("rootLoggerName can't be null"); } @Test @@ -75,52 +71,46 @@ public class LogLevelConfigTest { @Test public void builder_rootLevelFor_fails_with_ProcessId_if_loggerName_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("ProcessId can't be null"); - - underTest.rootLevelFor(null); + assertThatThrownBy(() -> underTest.rootLevelFor(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("ProcessId can't be null"); } @Test public void builder_rootLevelFor_fails_with_ISE_if_called_twice() { underTest.rootLevelFor(ProcessId.ELASTICSEARCH); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Configuration by property already registered for " + rootLoggerName); - - underTest.rootLevelFor(ProcessId.WEB_SERVER); + assertThatThrownBy(() -> underTest.rootLevelFor(ProcessId.WEB_SERVER)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Configuration by property already registered for " + rootLoggerName); } @Test public void builder_levelByDomain_fails_with_NPE_if_loggerName_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("loggerName can't be null"); - - underTest.levelByDomain(null, ProcessId.WEB_SERVER, LogDomain.JMX); + assertThatThrownBy(() -> underTest.levelByDomain(null, ProcessId.WEB_SERVER, LogDomain.JMX)) + .isInstanceOf(NullPointerException.class) + .hasMessage("loggerName can't be null"); } @Test public void builder_levelByDomain_fails_with_IAE_if_loggerName_is_empty() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("loggerName can't be empty"); - - underTest.levelByDomain("", ProcessId.WEB_SERVER, LogDomain.JMX); + assertThatThrownBy(() -> underTest.levelByDomain("", ProcessId.WEB_SERVER, LogDomain.JMX)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("loggerName can't be empty"); } @Test public void builder_levelByDomain_fails_with_NPE_if_ProcessId_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("ProcessId can't be null"); - - underTest.levelByDomain("bar", null, LogDomain.JMX); + assertThatThrownBy(() -> underTest.levelByDomain("bar", null, LogDomain.JMX)) + .isInstanceOf(NullPointerException.class) + .hasMessage("ProcessId can't be null"); } @Test public void builder_levelByDomain_fails_with_NPE_if_LogDomain_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("LogDomain can't be null"); - - underTest.levelByDomain("bar", ProcessId.WEB_SERVER, null); + assertThatThrownBy(() -> underTest.levelByDomain("bar", ProcessId.WEB_SERVER, null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("LogDomain can't be null"); } @Test @@ -139,34 +129,30 @@ public class LogLevelConfigTest { public void builder_levelByDomain_fails_with_ISE_if_loggerName_has_immutableLevel() { underTest.immutableLevel("bar", Level.INFO); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Configuration hardcoded level already registered for bar"); - - underTest.levelByDomain("bar", ProcessId.WEB_SERVER, LogDomain.JMX); + assertThatThrownBy(() -> underTest.levelByDomain("bar", ProcessId.WEB_SERVER, LogDomain.JMX)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Configuration hardcoded level already registered for bar"); } @Test public void builder_immutableLevel_fails_with_NPE_if_logger_name_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("loggerName can't be null"); - - underTest.immutableLevel(null, Level.ERROR); + assertThatThrownBy(() -> underTest.immutableLevel(null, Level.ERROR)) + .isInstanceOf(NullPointerException.class) + .hasMessage("loggerName can't be null"); } @Test public void builder_immutableLevel_fails_with_IAE_if_logger_name_is_empty() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("loggerName can't be empty"); - - underTest.immutableLevel("", Level.ERROR); + assertThatThrownBy(() -> underTest.immutableLevel("", Level.ERROR)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("loggerName can't be empty"); } @Test public void builder_immutableLevel_fails_with_NPE_if_level_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("level can't be null"); - - underTest.immutableLevel("foo", null); + assertThatThrownBy(() -> underTest.immutableLevel("foo", null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("level can't be null"); } @Test @@ -182,20 +168,18 @@ public class LogLevelConfigTest { public void builder_fails_with_ISE_if_immutableLevel_called_twice_for_same_logger() { underTest.immutableLevel("foo", Level.INFO); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Configuration hardcoded level already registered for foo"); - - underTest.immutableLevel("foo", Level.DEBUG); + assertThatThrownBy(() -> underTest.immutableLevel("foo", Level.DEBUG)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Configuration hardcoded level already registered for foo"); } @Test public void builder_fails_with_ISE_if_logger_has_domain_config() { underTest.levelByDomain("pop", ProcessId.WEB_SERVER, LogDomain.JMX); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Configuration by property already registered for pop"); - - underTest.immutableLevel("pop", Level.DEBUG); + assertThatThrownBy(() -> underTest.immutableLevel("pop", Level.DEBUG)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Configuration by property already registered for pop"); } private static void expectUnsupportedOperationException(Runnable runnable) { diff --git a/server/sonar-process/src/test/java/org/sonar/process/logging/LogbackHelperTest.java b/server/sonar-process/src/test/java/org/sonar/process/logging/LogbackHelperTest.java index 022587fcd73..bddd62d0406 100644 --- a/server/sonar-process/src/test/java/org/sonar/process/logging/LogbackHelperTest.java +++ b/server/sonar-process/src/test/java/org/sonar/process/logging/LogbackHelperTest.java @@ -49,7 +49,6 @@ import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.sonar.process.MessageException; @@ -58,6 +57,7 @@ import org.sonar.process.Props; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.fail; import static org.slf4j.Logger.ROOT_LOGGER_NAME; import static org.sonar.process.ProcessProperties.Property.PATH_LOGS; @@ -68,8 +68,6 @@ public class LogbackHelperTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private Props props = new Props(new Properties()); private LogbackHelper underTest = new LogbackHelper(); @@ -307,10 +305,9 @@ public class LogbackHelperTest { public void apply_fails_with_IAE_if_LogLevelConfig_does_not_have_ROOT_LOGGER_NAME_of_LogBack() { LogLevelConfig logLevelConfig = LogLevelConfig.newBuilder(randomAlphanumeric(2)).build(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Value of LogLevelConfig#rootLoggerName must be \"ROOT\""); - - underTest.apply(logLevelConfig, props); + assertThatThrownBy(() -> underTest.apply(logLevelConfig, props)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Value of LogLevelConfig#rootLoggerName must be \"ROOT\""); } @Test @@ -319,10 +316,9 @@ public class LogbackHelperTest { props.set("sonar.log.level", "ERROR"); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("log level ERROR in property sonar.log.level is not a supported value (allowed levels are [TRACE, DEBUG, INFO])"); - - underTest.apply(config, props); + assertThatThrownBy(() -> underTest.apply(config, props)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("log level ERROR in property sonar.log.level is not a supported value (allowed levels are [TRACE, DEBUG, INFO])"); } @Test @@ -331,10 +327,9 @@ public class LogbackHelperTest { props.set("sonar.log.level.web", "ERROR"); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("log level ERROR in property sonar.log.level.web is not a supported value (allowed levels are [TRACE, DEBUG, INFO])"); - - underTest.apply(config, props); + assertThatThrownBy(() -> underTest.apply(config, props)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("log level ERROR in property sonar.log.level.web is not a supported value (allowed levels are [TRACE, DEBUG, INFO])"); } @Test @@ -419,10 +414,9 @@ public class LogbackHelperTest { props.set("sonar.log.level.web.jmx", "ERROR"); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("log level ERROR in property sonar.log.level.web.jmx is not a supported value (allowed levels are [TRACE, DEBUG, INFO])"); - - underTest.apply(config, props); + assertThatThrownBy(() -> underTest.apply(config, props)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("log level ERROR in property sonar.log.level.web.jmx is not a supported value (allowed levels are [TRACE, DEBUG, INFO])"); } @Test diff --git a/server/sonar-process/src/test/java/org/sonar/process/logging/LogbackJsonLayoutTest.java b/server/sonar-process/src/test/java/org/sonar/process/logging/LogbackJsonLayoutTest.java index 4c05a92684f..0a855a4378b 100644 --- a/server/sonar-process/src/test/java/org/sonar/process/logging/LogbackJsonLayoutTest.java +++ b/server/sonar-process/src/test/java/org/sonar/process/logging/LogbackJsonLayoutTest.java @@ -100,7 +100,7 @@ public class LogbackJsonLayoutTest { JsonLog json = new Gson().fromJson(log, JsonLog.class); assertThat(json.stacktrace).hasSizeGreaterThan(5); assertThat(json.stacktrace[0]).isEqualTo("java.lang.IllegalStateException: BOOM"); - assertThat(json.stacktrace[1]).startsWith("at org.sonar.process.logging.LogbackJsonLayoutTest.test_log_with_throwable_and_cause(LogbackJsonLayoutTest.java:"); + assertThat(json.stacktrace[1]).contains("at org.sonar.process.logging.LogbackJsonLayoutTest.test_log_with_throwable_and_cause"); assertThat(json.stacktrace) .contains("\tCaused by: ") .contains("\tjava.lang.IllegalArgumentException: Root cause"); diff --git a/server/sonar-process/src/test/java/org/sonar/process/sharedmemoryfile/AllProcessesCommandsTest.java b/server/sonar-process/src/test/java/org/sonar/process/sharedmemoryfile/AllProcessesCommandsTest.java index 65ca1431098..5821162fd59 100644 --- a/server/sonar-process/src/test/java/org/sonar/process/sharedmemoryfile/AllProcessesCommandsTest.java +++ b/server/sonar-process/src/test/java/org/sonar/process/sharedmemoryfile/AllProcessesCommandsTest.java @@ -24,10 +24,10 @@ import java.io.IOException; import org.apache.commons.io.FileUtils; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.fail; import static org.sonar.process.sharedmemoryfile.ProcessCommands.MAX_PROCESSES; @@ -43,8 +43,6 @@ public class AllProcessesCommandsTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void fail_to_init_if_dir_does_not_exist() throws Exception { @@ -191,10 +189,9 @@ public class AllProcessesCommandsTest { try (AllProcessesCommands commands = new AllProcessesCommands(temp.newFolder())) { int processNumber = -2; - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Process number " + processNumber + " is not valid"); - - commands.createAfterClean(processNumber); + assertThatThrownBy(() -> commands.createAfterClean(processNumber)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Process number " + processNumber + " is not valid"); } } @@ -203,10 +200,9 @@ public class AllProcessesCommandsTest { try (AllProcessesCommands commands = new AllProcessesCommands(temp.newFolder())) { int processNumber = MAX_PROCESSES + 1; - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Process number " + processNumber + " is not valid"); - - commands.createAfterClean(processNumber); + assertThatThrownBy(() -> commands.createAfterClean(processNumber)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Process number " + processNumber + " is not valid"); } } diff --git a/server/sonar-process/src/test/java/org/sonar/process/sharedmemoryfile/DefaultProcessCommandsTest.java b/server/sonar-process/src/test/java/org/sonar/process/sharedmemoryfile/DefaultProcessCommandsTest.java index 1754e976cfe..ae9227a2cc9 100644 --- a/server/sonar-process/src/test/java/org/sonar/process/sharedmemoryfile/DefaultProcessCommandsTest.java +++ b/server/sonar-process/src/test/java/org/sonar/process/sharedmemoryfile/DefaultProcessCommandsTest.java @@ -22,12 +22,13 @@ package org.sonar.process.sharedmemoryfile; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; +import org.assertj.core.api.ThrowableAssert; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.fail; import static org.sonar.process.sharedmemoryfile.ProcessCommands.MAX_PROCESSES; @@ -37,8 +38,6 @@ public class DefaultProcessCommandsTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void fail_to_init_if_dir_does_not_exist() throws Exception { @@ -170,76 +169,71 @@ public class DefaultProcessCommandsTest { public void main_fails_if_processNumber_is_less_than_0() throws Exception { int processNumber = -2; - expectProcessNumberNoValidIAE(processNumber); - + expectProcessNumberNoValidIAE(() -> { + try ( DefaultProcessCommands main = DefaultProcessCommands.main(temp.newFolder(), processNumber);) { - try (DefaultProcessCommands main = DefaultProcessCommands.main(temp.newFolder(), processNumber)) { + } + }, processNumber); - } } @Test public void main_fails_if_processNumber_is_higher_than_MAX_PROCESSES() throws Exception { int processNumber = MAX_PROCESSES + 1; - expectProcessNumberNoValidIAE(processNumber); + expectProcessNumberNoValidIAE(() -> { + try (DefaultProcessCommands main = DefaultProcessCommands.main(temp.newFolder(), processNumber)) { - try (DefaultProcessCommands main = DefaultProcessCommands.main(temp.newFolder(), processNumber)) { - - } + } + }, processNumber); } @Test public void main_fails_if_processNumber_is_MAX_PROCESSES() throws Exception { int processNumber = MAX_PROCESSES; - expectProcessNumberNoValidIAE(processNumber); - - try (DefaultProcessCommands main = DefaultProcessCommands.main(temp.newFolder(), processNumber)) { + expectProcessNumberNoValidIAE(() -> { + try (DefaultProcessCommands main = DefaultProcessCommands.main(temp.newFolder(), processNumber)) { - } + } + }, processNumber); } @Test public void secondary_fails_if_processNumber_is_less_than_0() throws Exception { int processNumber = -2; - expectProcessNumberNoValidIAE(processNumber); - - DefaultProcessCommands.secondary(temp.newFolder(), processNumber); + expectProcessNumberNoValidIAE(() -> DefaultProcessCommands.secondary(temp.newFolder(), processNumber), processNumber); } @Test public void secondary_fails_if_processNumber_is_higher_than_MAX_PROCESSES() throws Exception { int processNumber = MAX_PROCESSES + 1; - expectProcessNumberNoValidIAE(processNumber); - - try (DefaultProcessCommands secondary = DefaultProcessCommands.secondary(temp.newFolder(), processNumber)) { + expectProcessNumberNoValidIAE(() -> { + try (DefaultProcessCommands secondary = DefaultProcessCommands.secondary(temp.newFolder(), processNumber)) { - } + } + }, processNumber); } @Test public void reset_fails_if_processNumber_is_less_than_0() throws Exception { int processNumber = -2; - expectProcessNumberNoValidIAE(processNumber); - - DefaultProcessCommands.reset(temp.newFolder(), processNumber); + expectProcessNumberNoValidIAE(() -> DefaultProcessCommands.reset(temp.newFolder(), processNumber), processNumber); } @Test public void reset_fails_if_processNumber_is_higher_than_MAX_PROCESSES() throws Exception { int processNumber = MAX_PROCESSES + 1; - expectProcessNumberNoValidIAE(processNumber); - - DefaultProcessCommands.reset(temp.newFolder(), processNumber); + expectProcessNumberNoValidIAE(() -> DefaultProcessCommands.reset(temp.newFolder(), processNumber), processNumber); } - private void expectProcessNumberNoValidIAE(int processNumber) { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Process number " + processNumber + " is not valid"); + private void expectProcessNumberNoValidIAE(ThrowableAssert.ThrowingCallable callback, int processNumber) { + assertThatThrownBy(callback) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Process number " + processNumber + " is not valid"); } } diff --git a/server/sonar-server-common/src/main/java/org/sonar/server/notification/DefaultNotificationManager.java b/server/sonar-server-common/src/main/java/org/sonar/server/notification/DefaultNotificationManager.java index 8988c8358b2..04f39dbb523 100644 --- a/server/sonar-server-common/src/main/java/org/sonar/server/notification/DefaultNotificationManager.java +++ b/server/sonar-server-common/src/main/java/org/sonar/server/notification/DefaultNotificationManager.java @@ -58,8 +58,6 @@ public class DefaultNotificationManager implements NotificationManager { private NotificationChannel[] notificationChannels; private final DbClient dbClient; - - private boolean alreadyLoggedDeserializationIssue = false; /** diff --git a/server/sonar-server-common/src/main/java/org/sonar/server/notification/NotificationManager.java b/server/sonar-server-common/src/main/java/org/sonar/server/notification/NotificationManager.java index 4dbae19a15b..d04f395d8a6 100644 --- a/server/sonar-server-common/src/main/java/org/sonar/server/notification/NotificationManager.java +++ b/server/sonar-server-common/src/main/java/org/sonar/server/notification/NotificationManager.java @@ -62,8 +62,6 @@ public interface NotificationManager { */ Multimap findSubscribedRecipientsForDispatcher(NotificationDispatcher dispatcher, String projectKey, SubscriberPermissionsOnProject subscriberPermissionsOnProject); - - @Immutable final class EmailRecipient { private final String login; diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/async/AsyncExecutionImplTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/async/AsyncExecutionImplTest.java index 2dfae3a5dca..255843fc6a1 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/async/AsyncExecutionImplTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/async/AsyncExecutionImplTest.java @@ -21,15 +21,13 @@ package org.sonar.server.async; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.utils.log.LogTester; import org.sonar.api.utils.log.LoggerLevel; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class AsyncExecutionImplTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public LogTester logTester = new LogTester(); @@ -38,9 +36,8 @@ public class AsyncExecutionImplTest { @Test public void addToQueue_fails_with_NPE_if_Runnable_is_null() { - expectedException.expect(NullPointerException.class); - - underTest.addToQueue(null); + assertThatThrownBy(() -> underTest.addToQueue(null)) + .isInstanceOf(NullPointerException.class); } @Test @@ -60,9 +57,8 @@ public class AsyncExecutionImplTest { throw expected; }; - expectedException.expect(Error.class); - expectedException.expectMessage(expected.getMessage()); - - underTest.addToQueue(runnable); + assertThatThrownBy(() -> underTest.addToQueue(runnable)) + .isInstanceOf(Error.class) + .hasMessage(expected.getMessage()); } } diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/component/index/ComponentIndexerTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/component/index/ComponentIndexerTest.java index 0ff178eb394..7eb09b5023f 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/component/index/ComponentIndexerTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/component/index/ComponentIndexerTest.java @@ -19,6 +19,8 @@ */ package org.sonar.server.component.index; +import java.util.Arrays; +import java.util.Collection; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.junit.Rule; @@ -45,8 +47,6 @@ import static org.sonar.server.component.index.ComponentIndexDefinition.TYPE_COM import static org.sonar.server.es.ProjectIndexer.Cause.PROJECT_CREATION; import static org.sonar.server.es.ProjectIndexer.Cause.PROJECT_DELETION; import static org.sonar.server.es.newindex.DefaultIndexSettingsElement.SORTABLE_ANALYZER; -import java.util.Arrays; -import java.util.Collection; public class ComponentIndexerTest { diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/component/index/SuggestionQueryTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/component/index/SuggestionQueryTest.java index d8e29e8a7ed..afd691c0dd7 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/component/index/SuggestionQueryTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/component/index/SuggestionQueryTest.java @@ -19,31 +19,26 @@ */ package org.sonar.server.component.index; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class SuggestionQueryTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void should_fail_with_IAE_if_query_is_empty() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Query must be at least two characters long"); - - SuggestionQuery.builder().setQuery(""); + assertThatThrownBy(() -> SuggestionQuery.builder().setQuery("")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Query must be at least two characters long"); } @Test public void should_fail_with_IAE_if_query_is_one_character_long() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Query must be at least two characters long"); - - SuggestionQuery.builder().setQuery("a"); + assertThatThrownBy(() -> SuggestionQuery.builder().setQuery("a")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Query must be at least two characters long"); } @Test @@ -57,20 +52,18 @@ public class SuggestionQueryTest { public void should_fail_with_IAE_if_limit_is_negative() { SuggestionQuery.Builder query = SuggestionQuery.builder().setQuery("ab"); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Limit has to be strictly positive"); - - query.setLimit(-1); + assertThatThrownBy(() -> query.setLimit(-1)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Limit has to be strictly positive"); } @Test public void should_fail_with_IAE_if_limit_is_zero() { SuggestionQuery.Builder query = SuggestionQuery.builder().setQuery("ab"); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Limit has to be strictly positive"); - - query.setLimit(0); + assertThatThrownBy(() -> query.setLimit(0)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Limit has to be strictly positive"); } @Test diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/es/EsClientProviderTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/es/EsClientProviderTest.java index 336cb99f938..50930afec54 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/es/EsClientProviderTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/es/EsClientProviderTest.java @@ -26,13 +26,13 @@ import org.elasticsearch.client.RestHighLevelClient; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.utils.log.LogTester; import org.sonar.api.utils.log.LoggerLevel; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.process.ProcessProperties.Property.CLUSTER_ENABLED; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NAME; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_TYPE; @@ -43,8 +43,6 @@ import static org.sonar.process.ProcessProperties.Property.SEARCH_PORT; public class EsClientProviderTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public LogTester logTester = new LogTester(); @@ -112,10 +110,9 @@ public class EsClientProviderTest { settings.setProperty(CLUSTER_NODE_TYPE.getKey(), "application"); settings.setProperty(CLUSTER_SEARCH_HOSTS.getKey(), format("%s:100000,%s:8081", localhostHostname, localhostHostname)); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(format("Port number out of range: %s:100000", localhostHostname)); - - underTest.provide(settings.asConfig()); + assertThatThrownBy(() -> underTest.provide(settings.asConfig())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage(format("Port number out of range: %s:100000", localhostHostname)); } @Test @@ -125,10 +122,9 @@ public class EsClientProviderTest { settings.setProperty(SEARCH_HOST.getKey(), "localhost"); settings.setProperty(SEARCH_PORT.getKey(), "100000"); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Port out of range: 100000"); - - underTest.provide(settings.asConfig()); + assertThatThrownBy(() -> underTest.provide(settings.asConfig())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Port out of range: 100000"); } @Test diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/es/EsClientTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/es/EsClientTest.java index 7c9cc59da2c..68d21eaad86 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/es/EsClientTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/es/EsClientTest.java @@ -35,6 +35,7 @@ import org.junit.Test; import org.mockito.ArgumentMatcher; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; @@ -162,10 +163,11 @@ public class EsClientTest { verify(restClient).close(); } - @Test(expected = ElasticsearchException.class) + @Test public void should_rethrow_ex_when_close_client_throws() throws IOException { doThrow(IOException.class).when(restClient).close(); - underTest.close(); + assertThatThrownBy(() -> underTest.close()) + .isInstanceOf(ElasticsearchException.class); } @Test @@ -182,13 +184,15 @@ public class EsClientTest { assertThat(underTest.nodesStats()).isNotNull(); } - @Test(expected = ElasticsearchException.class) + @Test public void should_rethrow_ex_on_node_stat_fail() throws Exception { when(restClient.performRequest(argThat(new RawRequestMatcher( "GET", "/_nodes/stats/fs,process,jvm,indices,breaker")))) .thenThrow(IOException.class); - underTest.nodesStats(); + + assertThatThrownBy(() -> underTest.nodesStats()) + .isInstanceOf(ElasticsearchException.class); } @Test @@ -205,13 +209,15 @@ public class EsClientTest { assertThat(underTest.indicesStats()).isNotNull(); } - @Test(expected = ElasticsearchException.class) + @Test public void should_rethrow_ex_on_indices_stat_fail() throws Exception { when(restClient.performRequest(argThat(new RawRequestMatcher( "GET", "/_stats")))) .thenThrow(IOException.class); - underTest.indicesStats(); + + assertThatThrownBy(() -> underTest.indicesStats()) + .isInstanceOf(ElasticsearchException.class); } @Test @@ -229,13 +235,15 @@ public class EsClientTest { assertThat(underTest.clusterStats()).isNotNull(); } - @Test(expected = ElasticsearchException.class) + @Test public void should_rethrow_ex_on_cluster_stat_fail() throws Exception { when(restClient.performRequest(argThat(new RawRequestMatcher( "GET", "/_cluster/stats")))) .thenThrow(IOException.class); - underTest.clusterStats(); + + assertThatThrownBy(() -> underTest.clusterStats()) + .isInstanceOf(ElasticsearchException.class); } @Test diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/es/IndexDefinitionContextTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/es/IndexDefinitionContextTest.java index c216599dab4..2ece2bba56e 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/es/IndexDefinitionContextTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/es/IndexDefinitionContextTest.java @@ -23,23 +23,20 @@ import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.Locale; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.api.config.internal.MapSettings; import org.sonar.server.es.newindex.SettingsConfiguration; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.server.es.newindex.SettingsConfiguration.newBuilder; @RunWith(DataProviderRunner.class) public class IndexDefinitionContextTest { private SettingsConfiguration emptySettingsConfiguration = newBuilder(new MapSettings().asConfig()).build(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void create_indices() { @@ -58,10 +55,9 @@ public class IndexDefinitionContextTest { context.create(index1, emptySettingsConfiguration); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Index already exists: " + index1.getName()); - - context.create(index2, emptySettingsConfiguration); + assertThatThrownBy(() -> context.create(index2, emptySettingsConfiguration)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Index already exists: " + index1.getName()); } @DataProvider diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/es/IndexTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/es/IndexTest.java index 7c90b5f09f0..b94c1a2c414 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/es/IndexTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/es/IndexTest.java @@ -23,37 +23,29 @@ import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.Locale; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; @RunWith(DataProviderRunner.class) public class IndexTest { - - @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Test @UseDataProvider("nullOrEmpty") public void simple_index_constructor_fails_with_IAE_if_index_name_is_null_or_empty(String nullOrEmpty) { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Index name can't be null nor empty"); - - Index.simple(nullOrEmpty); + assertThatThrownBy(() -> Index.simple(nullOrEmpty)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Index name can't be null nor empty"); } @Test @UseDataProvider("nullOrEmpty") public void withRelations_index_constructor_fails_with_IAE_if_index_name_is_null_or_empty(String nullOrEmpty) { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Index name can't be null nor empty"); - - Index.withRelations(nullOrEmpty); - + assertThatThrownBy(() -> Index.withRelations(nullOrEmpty)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Index name can't be null nor empty"); } @DataProvider @@ -66,18 +58,16 @@ public class IndexTest { @Test public void simple_index_name_must_not_contain_upper_case_char() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Index name must be lower-case letters or '_all': Issues"); - - Index.simple("Issues"); + assertThatThrownBy(() -> Index.simple("Issues")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Index name must be lower-case letters or '_all': Issues"); } @Test public void withRelations_index_name_must_not_contain_upper_case_char() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Index name must be lower-case letters or '_all': Issues"); - - Index.withRelations("Issues"); + assertThatThrownBy(() -> Index.withRelations("Issues")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Index name must be lower-case letters or '_all': Issues"); } @Test @@ -85,10 +75,9 @@ public class IndexTest { // doesn't fail Index.simple("_all"); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Index name must be lower-case letters or '_all': _"); - - Index.simple("_"); + assertThatThrownBy(() -> Index.simple("_")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Index name must be lower-case letters or '_all': _"); } @Test @@ -96,10 +85,9 @@ public class IndexTest { // doesn't fail Index.withRelations("_all"); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Index name must be lower-case letters or '_all': _"); - - Index.withRelations("_"); + assertThatThrownBy(() -> Index.withRelations("_")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Index name must be lower-case letters or '_all': _"); } @Test @@ -128,10 +116,9 @@ public class IndexTest { public void getJoinField_throws_ISE_on_simple_index() { Index underTest = Index.simple("foo"); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Only index accepting relations has a join field"); - - underTest.getJoinField(); + assertThatThrownBy(underTest::getJoinField) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Only index accepting relations has a join field"); } @Test diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/es/IndexTypeTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/es/IndexTypeTest.java index a62d8f2fdc5..510d9574c23 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/es/IndexTypeTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/es/IndexTypeTest.java @@ -22,21 +22,18 @@ package org.sonar.server.es; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.server.es.IndexType.IndexMainType; import org.sonar.server.es.IndexType.IndexRelationType; import org.sonar.server.es.IndexType.SimpleIndexMainType; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; @RunWith(DataProviderRunner.class) public class IndexTypeTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void parseMainType_from_main_type_without_relations() { @@ -74,10 +71,9 @@ public class IndexTypeTest { @Test public void parse_throws_IAE_if_invalid_format() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Unsupported IndexType value: foo"); - - IndexType.parseMainType("foo"); + assertThatThrownBy(() -> IndexType.parseMainType("foo")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Unsupported IndexType value: foo"); } @Test @@ -85,10 +81,9 @@ public class IndexTypeTest { public void main_fails_with_IAE_if_index_name_is_null_or_empty(String nullOrEmpty) { Index index = Index.simple("foo"); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("type name can't be null nor empty"); - - IndexType.main(index, nullOrEmpty); + assertThatThrownBy(() -> IndexType.main(index, nullOrEmpty)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("type name can't be null nor empty"); } @Test @@ -97,10 +92,9 @@ public class IndexTypeTest { Index index = Index.withRelations("foo"); IndexMainType mainType = IndexType.main(index, "foobar"); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("type name can't be null nor empty"); - - IndexType.relation(mainType, nullOrEmpty); + assertThatThrownBy(() -> IndexType.relation(mainType, nullOrEmpty)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("type name can't be null nor empty"); } @DataProvider diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/es/NewIndexSettingsConfigurationTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/es/NewIndexSettingsConfigurationTest.java index afcac24a843..51b5d7e69ba 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/es/NewIndexSettingsConfigurationTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/es/NewIndexSettingsConfigurationTest.java @@ -20,48 +20,42 @@ package org.sonar.server.es; import java.util.Random; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.config.Configuration; import org.sonar.server.es.newindex.SettingsConfiguration; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.sonar.server.es.newindex.SettingsConfiguration.newBuilder; public class NewIndexSettingsConfigurationTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private Configuration mockConfiguration = mock(Configuration.class); @Test public void newBuilder_fails_with_NPE_when_Configuration_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("configuration can't be null"); - - newBuilder(null); + assertThatThrownBy(() -> newBuilder(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("configuration can't be null"); } @Test public void setDefaultNbOfShards_fails_with_IAE_if_argument_is_zero() { SettingsConfiguration.Builder underTest = newBuilder(mockConfiguration); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("defaultNbOfShards must be >= 1"); - - underTest.setDefaultNbOfShards(0); + assertThatThrownBy(() -> underTest.setDefaultNbOfShards(0)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("defaultNbOfShards must be >= 1"); } @Test public void setDefaultNbOfShards_fails_with_IAE_if_argument_is_less_than_zero() { SettingsConfiguration.Builder underTest = newBuilder(mockConfiguration); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("defaultNbOfShards must be >= 1"); - - underTest.setDefaultNbOfShards(-1 - new Random().nextInt(10)); + assertThatThrownBy(() -> underTest.setDefaultNbOfShards(-1 - new Random().nextInt(10))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("defaultNbOfShards must be >= 1"); } @Test @@ -89,20 +83,18 @@ public class NewIndexSettingsConfigurationTest { public void setRefreshInterval_fails_with_IAE_if_argument_is_zero() { SettingsConfiguration.Builder underTest = newBuilder(mockConfiguration); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("refreshInterval must be either -1 or strictly positive"); - - underTest.setRefreshInterval(0); + assertThatThrownBy(() -> underTest.setRefreshInterval(0)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("refreshInterval must be either -1 or strictly positive"); } @Test public void setRefreshInterval_fails_with_IAE_if_argument_is_less_than_minus_1() { SettingsConfiguration.Builder underTest = newBuilder(mockConfiguration); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("refreshInterval must be either -1 or strictly positive"); - - underTest.setRefreshInterval(-2 - new Random().nextInt(10)); + assertThatThrownBy(() -> underTest.setRefreshInterval(-2 - new Random().nextInt(10))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("refreshInterval must be either -1 or strictly positive"); } @Test diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/es/OneToManyResilientIndexingListenerTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/es/OneToManyResilientIndexingListenerTest.java index 1f0dba354cd..8e9051a39a3 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/es/OneToManyResilientIndexingListenerTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/es/OneToManyResilientIndexingListenerTest.java @@ -24,7 +24,6 @@ import java.util.Collection; import java.util.List; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.es.EsQueueDto; @@ -42,8 +41,6 @@ public class OneToManyResilientIndexingListenerTest { public EsTester es = EsTester.create(); @Rule public DbTester db = DbTester.create(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void ES_QUEUE_rows_are_deleted_when_all_docs_are_successfully_indexed() { diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/es/OneToOneResilientIndexingListenerTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/es/OneToOneResilientIndexingListenerTest.java index 37d29093ac2..855466ee9b3 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/es/OneToOneResilientIndexingListenerTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/es/OneToOneResilientIndexingListenerTest.java @@ -24,7 +24,6 @@ import java.util.Collection; import java.util.List; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.es.EsQueueDto; @@ -42,8 +41,6 @@ public class OneToOneResilientIndexingListenerTest { public EsTester es = EsTester.create(); @Rule public DbTester db = DbTester.create(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void onSuccess_deletes_rows_from_ES_QUEUE_table() { diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/es/SearchOptionsTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/es/SearchOptionsTest.java index c1bc854fec1..b8989416330 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/es/SearchOptionsTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/es/SearchOptionsTest.java @@ -20,18 +20,15 @@ package org.sonar.server.es; import java.io.StringWriter; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.utils.text.JsonWriter; import org.sonar.test.JsonAssert; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class SearchOptionsTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private SearchOptions underTest = new SearchOptions(); @@ -64,38 +61,37 @@ public class SearchOptionsTest { @Test public void fail_if_page_is_not_strictly_positive() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Page must be greater or equal to 1 (got 0)"); - new SearchOptions().setPage(0, 10); + assertThatThrownBy(() -> new SearchOptions().setPage(0, 10)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Page must be greater or equal to 1 (got 0)"); } @Test public void fail_if_ps_is_zero() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Page size must be between 1 and 500 (got 0)"); - new SearchOptions().setPage(1, 0); + assertThatThrownBy(() -> new SearchOptions().setPage(1, 0)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Page size must be between 1 and 500 (got 0)"); } @Test public void fail_if_ps_is_negative() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Page size must be between 1 and 500 (got -1)"); - new SearchOptions().setPage(2, -1); + assertThatThrownBy(() -> new SearchOptions().setPage(2, -1)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Page size must be between 1 and 500 (got -1)"); } @Test public void fail_if_ps_is_over_limit() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Page size must be between 1 and 500 (got 510)"); - new SearchOptions().setPage(3, SearchOptions.MAX_PAGE_SIZE + 10); + assertThatThrownBy(() -> new SearchOptions().setPage(3, SearchOptions.MAX_PAGE_SIZE + 10)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Page size must be between 1 and 500 (got 510)"); } @Test public void fail_if_result_after_first_10_000() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Can return only the first 10000 results. 10500th result asked."); - - underTest.setPage(21, 500); + assertThatThrownBy(() -> underTest.setPage(21, 500)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Can return only the first 10000 results. 10500th result asked."); } @Test @@ -103,9 +99,9 @@ public class SearchOptionsTest { SearchOptions options = new SearchOptions().setLimit(42); assertThat(options.getLimit()).isEqualTo(42); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Page size must be between 1 and 500 (got 510)"); - options.setLimit(SearchOptions.MAX_PAGE_SIZE + 10); + assertThatThrownBy(() -> options.setLimit(SearchOptions.MAX_PAGE_SIZE + 10)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Page size must be between 1 and 500 (got 510)"); } @Test diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/es/StartupIndexerTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/es/StartupIndexerTest.java index cfeb6750231..6575f81d997 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/es/StartupIndexerTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/es/StartupIndexerTest.java @@ -21,16 +21,13 @@ package org.sonar.server.es; import java.util.Collections; import org.assertj.core.api.Assertions; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.server.es.StartupIndexer.Type.SYNCHRONOUS; public class StartupIndexerTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private StartupIndexer underTest = () -> null; @@ -41,18 +38,16 @@ public class StartupIndexerTest { @Test public void triggerAsyncIndexOnStartup() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("ASYNCHRONE StartupIndexer must implement initAsyncIndexOnStartup"); - - underTest.triggerAsyncIndexOnStartup(Collections.emptySet()); + assertThatThrownBy(() -> underTest.triggerAsyncIndexOnStartup(Collections.emptySet())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("ASYNCHRONE StartupIndexer must implement initAsyncIndexOnStartup"); } @Test public void indexOnStartup() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("SYNCHRONE StartupIndexer must implement indexOnStartup"); - - underTest.indexOnStartup(Collections.emptySet()); + assertThatThrownBy(() -> underTest.indexOnStartup(Collections.emptySet())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("SYNCHRONE StartupIndexer must implement indexOnStartup"); } } diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/es/newindex/NewIndexTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/es/newindex/NewIndexTest.java index 95585d7fcbe..3fb3ef6b174 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/es/newindex/NewIndexTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/es/newindex/NewIndexTest.java @@ -26,9 +26,7 @@ import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.Map; import org.elasticsearch.cluster.metadata.IndexMetadata; import org.elasticsearch.common.settings.Settings; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.api.config.internal.MapSettings; import org.sonar.server.es.Index; @@ -37,6 +35,7 @@ import org.sonar.server.es.IndexType.IndexMainType; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.data.MapEntry.entry; import static org.sonar.process.ProcessProperties.Property.CLUSTER_ENABLED; import static org.sonar.process.ProcessProperties.Property.SEARCH_REPLICAS; @@ -45,8 +44,6 @@ import static org.sonar.server.es.newindex.SettingsConfiguration.newBuilder; @RunWith(DataProviderRunner.class) public class NewIndexTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private static final String someIndexName = randomAlphabetic(5).toLowerCase(); private MapSettings settings = new MapSettings(); @@ -192,10 +189,9 @@ public class NewIndexTest { public void fail_when_nested_with_no_field(NewIndex newIndex, TypeMapping typeMapping) { NestedFieldBuilder nestedFieldBuilder = typeMapping.nestedFieldBuilder("measures"); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("At least one sub-field must be declared in nested property 'measures'"); - - nestedFieldBuilder.build(); + assertThatThrownBy(() -> nestedFieldBuilder.build()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("At least one sub-field must be declared in nested property 'measures'"); } @Test @@ -308,10 +304,9 @@ public class NewIndexTest { SettingsConfiguration settingsConfiguration = newBuilder(settings.asConfig()).setDefaultNbOfShards(5).build(); IndexMainType mainType = IndexType.main(index, "foo"); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("The property 'sonar.search.replicas' is not an int value: For input string: \"ꝱꝲꝳପ\""); - - new SimplestNewIndex(mainType, settingsConfiguration); + assertThatThrownBy(() -> new SimplestNewIndex(mainType, settingsConfiguration)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("The property 'sonar.search.replicas' is not an int value: For input string: \"ꝱꝲꝳପ\""); } @Test @@ -360,10 +355,9 @@ public class NewIndexTest { } }; - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Index is not configured to accept relations. Update IndexDefinition.Descriptor instance for this index"); - - underTest.createTypeMapping(indexRelationType); + assertThatThrownBy(() -> underTest.createTypeMapping(indexRelationType)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Index is not configured to accept relations. Update IndexDefinition.Descriptor instance for this index"); } @DataProvider diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/es/newindex/NewRegularIndexTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/es/newindex/NewRegularIndexTest.java index 3298ca8dd42..13f23d58af8 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/es/newindex/NewRegularIndexTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/es/newindex/NewRegularIndexTest.java @@ -25,9 +25,7 @@ import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.Locale; import java.util.Map; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.api.config.internal.MapSettings; import org.sonar.server.es.Index; @@ -35,6 +33,7 @@ import org.sonar.server.es.IndexType; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.entry; import static org.sonar.server.es.newindex.DefaultIndexSettings.NORMS; import static org.sonar.server.es.newindex.DefaultIndexSettings.STORE; @@ -45,8 +44,6 @@ import static org.sonar.server.es.newindex.SettingsConfiguration.newBuilder; public class NewRegularIndexTest { private static final String SOME_INDEX_NAME = randomAlphabetic(10).toLowerCase(Locale.ENGLISH); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private MapSettings settings = new MapSettings(); private SettingsConfiguration defaultSettingsConfiguration = newBuilder(settings.asConfig()).build(); @@ -56,10 +53,9 @@ public class NewRegularIndexTest { public void getMainType_fails_with_ISE_if_createTypeMapping_with_IndexMainType_has_not_been_called(Index index) { NewRegularIndex newIndex = new NewRegularIndex(index, defaultSettingsConfiguration); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Main type has not been defined"); - - newIndex.getMainType(); + assertThatThrownBy(() -> newIndex.getMainType()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Main type has not been defined"); } @Test @@ -68,10 +64,9 @@ public class NewRegularIndexTest { NewRegularIndex underTest = new NewRegularIndex(index, defaultSettingsConfiguration); underTest.createTypeMapping(IndexType.main(index, "foo")); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Main type can only be defined once"); - - underTest.createTypeMapping(IndexType.main(index, "foo")); + assertThatThrownBy(() -> underTest.createTypeMapping(IndexType.main(index, "foo"))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Main type can only be defined once"); } @Test @@ -79,10 +74,9 @@ public class NewRegularIndexTest { Index index = Index.withRelations(SOME_INDEX_NAME); NewRegularIndex underTest = new NewRegularIndex(index, defaultSettingsConfiguration); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Mapping for main type must be created first"); - - underTest.createTypeMapping(IndexType.relation(IndexType.main(index, "foo"), "bar")); + assertThatThrownBy(() -> underTest.createTypeMapping(IndexType.relation(IndexType.main(index, "foo"), "bar"))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Mapping for main type must be created first"); } @Test @@ -92,10 +86,9 @@ public class NewRegularIndexTest { NewRegularIndex underTest = new NewRegularIndex(index, defaultSettingsConfiguration); underTest.createTypeMapping(mainType); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("main type of relation must be "+ mainType); - - underTest.createTypeMapping(IndexType.relation(IndexType.main(index, "donut"), "bar")); + assertThatThrownBy(() -> underTest.createTypeMapping(IndexType.relation(IndexType.main(index, "donut"), "bar"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("main type of relation must be "+ mainType); } @Test @@ -103,10 +96,9 @@ public class NewRegularIndexTest { public void build_fails_with_ISE_if_no_mainType_is_defined(Index index) { NewRegularIndex underTest = new NewRegularIndex(index, defaultSettingsConfiguration); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Mapping for main type must be defined"); - - underTest.build(); + assertThatThrownBy(() -> underTest.build()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Mapping for main type must be defined"); } @DataProvider @@ -123,10 +115,9 @@ public class NewRegularIndexTest { NewRegularIndex underTest = new NewRegularIndex(index, defaultSettingsConfiguration); underTest.createTypeMapping(IndexType.main(index, "foo")); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("At least one relation must be defined when index accepts relations"); - - underTest.build(); + assertThatThrownBy(() -> underTest.build()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("At least one relation must be defined when index accepts relations"); } @Test diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/es/searchrequest/SimpleFieldTopAggregationDefinitionTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/es/searchrequest/SimpleFieldTopAggregationDefinitionTest.java index 7c3db76aa3d..155c48d1652 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/es/searchrequest/SimpleFieldTopAggregationDefinitionTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/es/searchrequest/SimpleFieldTopAggregationDefinitionTest.java @@ -24,26 +24,23 @@ import java.util.Set; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.apache.commons.lang.RandomStringUtils; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class SimpleFieldTopAggregationDefinitionTest { private static final Random RANDOM = new Random(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void fieldName_cannot_be_null() { boolean sticky = RANDOM.nextBoolean(); - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("fieldName can't be null"); - new SimpleFieldTopAggregationDefinition(null, sticky); + assertThatThrownBy(() -> new SimpleFieldTopAggregationDefinition(null, sticky)) + .isInstanceOf(NullPointerException.class) + .hasMessage("fieldName can't be null"); } @Test diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/es/textsearch/ComponentTextSearchQueryFactoryTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/es/textsearch/ComponentTextSearchQueryFactoryTest.java index 5cd769da7e6..e6406b295b3 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/es/textsearch/ComponentTextSearchQueryFactoryTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/es/textsearch/ComponentTextSearchQueryFactoryTest.java @@ -20,18 +20,15 @@ package org.sonar.server.es.textsearch; import org.elasticsearch.index.query.QueryBuilder; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.server.es.textsearch.ComponentTextSearchQueryFactory.ComponentTextSearchQuery; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.server.es.textsearch.ComponentTextSearchQueryFactory.createQuery; import static org.sonar.test.JsonAssert.assertJson; public class ComponentTextSearchQueryFactoryTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void create_query() { @@ -59,34 +56,32 @@ public class ComponentTextSearchQueryFactoryTest { @Test public void fail_to_create_query_when_no_feature() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("features cannot be empty"); - - createQuery(ComponentTextSearchQuery.builder() - .setQueryText("SonarQube").setFieldKey("key").setFieldName("name").build()); + assertThatThrownBy(() -> { + createQuery(ComponentTextSearchQuery.builder() + .setQueryText("SonarQube").setFieldKey("key").setFieldName("name").build()); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("features cannot be empty"); } @Test public void fail_to_create_query_when_no_query_text() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("query text cannot be null"); - - ComponentTextSearchQuery.builder().setFieldKey("key").setFieldName("name").build(); + assertThatThrownBy(() -> ComponentTextSearchQuery.builder().setFieldKey("key").setFieldName("name").build()) + .isInstanceOf(NullPointerException.class) + .hasMessage("query text cannot be null"); } @Test public void fail_to_create_query_when_no_field_key() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("field key cannot be null"); - - ComponentTextSearchQuery.builder().setQueryText("SonarQube").setFieldName("name").build(); + assertThatThrownBy(() -> ComponentTextSearchQuery.builder().setQueryText("SonarQube").setFieldName("name").build()) + .isInstanceOf(NullPointerException.class) + .hasMessage("field key cannot be null"); } @Test public void fail_to_create_query_when_no_field_name() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("field name cannot be null"); - - ComponentTextSearchQuery.builder().setQueryText("SonarQube").setFieldKey("key").build(); + assertThatThrownBy(() -> ComponentTextSearchQuery.builder().setQueryText("SonarQube").setFieldKey("key").build()) + .isInstanceOf(NullPointerException.class) + .hasMessage("field name cannot be null"); } } diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/favorite/FavoriteUpdaterTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/favorite/FavoriteUpdaterTest.java index 1831d917d26..762f5d7add8 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/favorite/FavoriteUpdaterTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/favorite/FavoriteUpdaterTest.java @@ -22,7 +22,6 @@ package org.sonar.server.favorite; import java.util.stream.IntStream; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.DbTester; @@ -31,11 +30,10 @@ import org.sonar.db.property.PropertyQuery; import org.sonar.db.user.UserDto; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class FavoriteUpdaterTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester db = DbTester.create(); @@ -106,10 +104,9 @@ public class FavoriteUpdaterTest { user.getUuid(), user.getLogin())); ComponentDto project = db.components().insertPrivateProject(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("You cannot have more than 100 favorites on components with qualifier 'TRK'"); - - underTest.add(dbSession, project, user.getUuid(), user.getLogin(), true); + assertThatThrownBy(() -> underTest.add(dbSession, project, user.getUuid(), user.getLogin(), true)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("You cannot have more than 100 favorites on components with qualifier 'TRK'"); } @Test @@ -119,10 +116,9 @@ public class FavoriteUpdaterTest { underTest.add(dbSession, project, user.getUuid(), user.getLogin(), true); assertFavorite(project, user); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(String.format("Component '%s' is already a favorite", project.getKey())); - - underTest.add(dbSession, project, user.getUuid(), user.getLogin(), true); + assertThatThrownBy(() -> underTest.add(dbSession, project, user.getUuid(), user.getLogin(), true)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage(String.format("Component '%s' is already a favorite", project.getKey())); } private void assertFavorite(ComponentDto project, UserDto user) { diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/issue/IssueFieldsSetterTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/issue/IssueFieldsSetterTest.java index db0b72d46e5..8b5908b9c63 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/issue/IssueFieldsSetterTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/issue/IssueFieldsSetterTest.java @@ -24,9 +24,7 @@ import java.util.Date; import java.util.Map; import java.util.Random; import org.apache.commons.lang.time.DateUtils; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.utils.Duration; import org.sonar.core.issue.DefaultIssue; import org.sonar.core.issue.FieldDiffs; @@ -34,7 +32,7 @@ import org.sonar.core.issue.IssueChangeContext; import org.sonar.db.user.UserDto; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.rules.ExpectedException.none; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.db.user.UserTesting.newUserDto; import static org.sonar.server.issue.IssueFieldsSetter.ASSIGNEE; import static org.sonar.server.issue.IssueFieldsSetter.RESOLUTION; @@ -45,8 +43,6 @@ import static org.sonar.server.issue.IssueFieldsSetter.UNUSED; public class IssueFieldsSetterTest { - @Rule - public ExpectedException thrown = none(); private DefaultIssue issue = new DefaultIssue(); private IssueChangeContext context = IssueChangeContext.createUser(new Date(), "user_uuid"); @@ -125,9 +121,9 @@ public class IssueFieldsSetterTest { public void fail_with_ISE_when_setting_new_assignee_on_already_assigned_issue() { issue.setAssigneeUuid("user_uuid"); - thrown.expect(IllegalStateException.class); - thrown.expectMessage("It's not possible to update the assignee with this method, please use assign()"); - underTest.setNewAssignee(issue, "another_user_uuid", context); + assertThatThrownBy(() -> underTest.setNewAssignee(issue, "another_user_uuid", context)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("It's not possible to update the assignee with this method, please use assign()"); } @Test @@ -507,9 +503,9 @@ public class IssueFieldsSetterTest { public void fail_with_ISE_when_setting_new_author_on_issue() { issue.setAuthorLogin("simon"); - thrown.expect(IllegalStateException.class); - thrown.expectMessage("It's not possible to update the author with this method, please use setAuthorLogin()"); - underTest.setNewAuthor(issue, "julien", context); + assertThatThrownBy(() -> underTest.setNewAuthor(issue, "julien", context)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("It's not possible to update the author with this method, please use setAuthorLogin()"); } @Test diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/issue/index/IssueIndexerTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/issue/index/IssueIndexerTest.java index 2b8aba6f249..490f3373e3f 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/issue/index/IssueIndexerTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/issue/index/IssueIndexerTest.java @@ -30,7 +30,6 @@ import org.assertj.core.api.Assertions; import org.elasticsearch.search.SearchHit; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.resources.Qualifiers; import org.sonar.api.utils.log.LogTester; import org.sonar.api.utils.log.LoggerLevel; @@ -57,7 +56,7 @@ import static java.util.Collections.emptyList; import static java.util.Collections.emptySet; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.rules.ExpectedException.none; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.db.component.ComponentTesting.newFileDto; import static org.sonar.server.issue.IssueDocTesting.newDoc; import static org.sonar.server.issue.index.IssueIndexDefinition.TYPE_ISSUE; @@ -71,8 +70,6 @@ public class IssueIndexerTest { @Rule public DbTester db = DbTester.create(); @Rule - public ExpectedException expectedException = none(); - @Rule public LogTester logTester = new LogTester(); private final IssueIndexer underTest = new IssueIndexer(es.client(), db.getDbClient(), new IssueIteratorFactory(db.getDbClient()), null); @@ -162,8 +159,8 @@ public class IssueIndexerTest { try { // FIXME : test also message - expectedException.expect(IllegalStateException.class); - underTest.indexOnStartup(emptySet()); + assertThatThrownBy(() -> underTest.indexOnStartup(emptySet())) + .isInstanceOf(IllegalStateException.class); } finally { assertThatIndexHasSize(0); assertThatEsQueueTableHasSize(0); @@ -213,8 +210,8 @@ public class IssueIndexerTest { try { // FIXME : test also message - expectedException.expect(IllegalStateException.class); - underTest.indexOnAnalysis(issue.getProjectUuid()); + assertThatThrownBy(() -> underTest.indexOnAnalysis(issue.getProjectUuid())) + .isInstanceOf(IllegalStateException.class); } finally { assertThatIndexHasSize(0); assertThatEsQueueTableHasSize(0); @@ -447,8 +444,8 @@ public class IssueIndexerTest { try { // FIXME : test also message - expectedException.expect(IllegalStateException.class); - underTest.deleteByKeys("P1", asList("Issue1")); + assertThatThrownBy(() -> underTest.deleteByKeys("P1", asList("Issue1"))) + .isInstanceOf(IllegalStateException.class); } finally { assertThatIndexHasOnly("Issue1"); assertThatEsQueueTableHasSize(0); diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/ChangesOnMyIssuesEmailTemplateTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/ChangesOnMyIssuesEmailTemplateTest.java index 4b57f1288fd..be945442cd8 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/ChangesOnMyIssuesEmailTemplateTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/ChangesOnMyIssuesEmailTemplateTest.java @@ -34,7 +34,6 @@ import java.util.stream.IntStream; import java.util.stream.Stream; import org.elasticsearch.common.util.set.Sets; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.api.config.EmailSettings; import org.sonar.api.notifications.Notification; @@ -55,6 +54,7 @@ import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toSet; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.api.issue.Issue.STATUS_CLOSED; @@ -80,8 +80,6 @@ public class ChangesOnMyIssuesEmailTemplateTest { private static final String[] ISSUE_STATUSES = {STATUS_OPEN, STATUS_RESOLVED, STATUS_CONFIRMED, STATUS_REOPENED, STATUS_CLOSED}; private static final String[] SECURITY_HOTSPOTS_STATUSES = {STATUS_TO_REVIEW, STATUS_REVIEWED}; - @org.junit.Rule - public ExpectedException expectedException = ExpectedException.none(); private I18n i18n = mock(I18n.class); private EmailSettings emailSettings = mock(EmailSettings.class); @@ -98,10 +96,9 @@ public class ChangesOnMyIssuesEmailTemplateTest { public void formats_fails_with_ISE_if_change_from_Analysis_and_no_issue() { AnalysisChange analysisChange = newAnalysisChange(); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("changedIssues can't be empty"); - - underTest.format(new ChangesOnMyIssuesNotification(analysisChange, Collections.emptySet())); + assertThatThrownBy(() -> underTest.format(new ChangesOnMyIssuesNotification(analysisChange, Collections.emptySet()))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("changedIssues can't be empty"); } @Test diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/NewIssuesStatisticsTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/NewIssuesStatisticsTest.java index b860a3f1154..cd94d5baf70 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/NewIssuesStatisticsTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/issue/notification/NewIssuesStatisticsTest.java @@ -30,9 +30,7 @@ import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import javax.annotation.CheckForNull; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.issue.Issue; import org.sonar.api.rule.RuleKey; import org.sonar.api.rules.RuleType; @@ -43,10 +41,9 @@ import org.sonar.server.issue.notification.NewIssuesStatistics.Metric; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class NewIssuesStatisticsTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private final Random random = new Random(); private RuleType randomRuleTypeExceptHotspot = RuleType.values()[random.nextInt(RuleType.values().length - 1)]; @@ -57,9 +54,8 @@ public class NewIssuesStatisticsTest { String assignee = randomAlphanumeric(10); DefaultIssue issue = new DefaultIssue().setType(null).setAssigneeUuid(assignee).setNew(new Random().nextBoolean()); - expectedException.expect(NullPointerException.class); - - underTest.add(issue); + assertThatThrownBy(() -> underTest.add(issue)) + .isInstanceOf(NullPointerException.class); } @Test diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/issue/workflow/StateTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/issue/workflow/StateTest.java index 8af46819497..8bbb5d0f252 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/issue/workflow/StateTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/issue/workflow/StateTest.java @@ -19,40 +19,35 @@ */ package org.sonar.server.issue.workflow; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class StateTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private Transition t1 = Transition.builder("close").from("OPEN").to("CLOSED").build(); @Test public void key_should_be_set() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("State key must be set"); - - new State("", new Transition[0]); + assertThatThrownBy(() -> new State("", new Transition[0])) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("State key must be set"); } @Test public void no_duplicated_out_transitions() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Transition 'close' is declared several times from the originating state 'CLOSE'"); - - new State("CLOSE", new Transition[] {t1, t1}); + assertThatThrownBy(() -> new State("CLOSE", new Transition[] {t1, t1})) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Transition 'close' is declared several times from the originating state 'CLOSE'"); } @Test public void fail_when_transition_is_unknown() { State state = new State("VALIDATED", new Transition[0]); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Transition from state VALIDATED does not exist: Unknown Transition"); - - state.transition("Unknown Transition"); + assertThatThrownBy(() -> state.transition("Unknown Transition")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Transition from state VALIDATED does not exist: Unknown Transition"); } } diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/log/ServerLoggingTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/log/ServerLoggingTest.java index fdfa469c39d..4e1cc6ff769 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/log/ServerLoggingTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/log/ServerLoggingTest.java @@ -28,7 +28,6 @@ import java.io.IOException; import org.apache.commons.lang.RandomStringUtils; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.sonar.api.config.internal.MapSettings; @@ -39,6 +38,7 @@ import org.sonar.process.logging.LogLevelConfig; import org.sonar.process.logging.LogbackHelper; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.spy; @@ -56,8 +56,6 @@ public class ServerLoggingTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private final String rootLoggerName = RandomStringUtils.randomAlphabetic(20); private LogbackHelper logbackHelper = spy(new LogbackHelper()); @@ -123,17 +121,15 @@ public class ServerLoggingTest { @Test public void changeLevel_fails_with_IAE_when_level_is_ERROR() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("ERROR log level is not supported (allowed levels are [TRACE, DEBUG, INFO])"); - - underTest.changeLevel(ERROR); + assertThatThrownBy(() -> underTest.changeLevel(ERROR)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("ERROR log level is not supported (allowed levels are [TRACE, DEBUG, INFO])"); } @Test public void changeLevel_fails_with_IAE_when_level_is_WARN() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("WARN log level is not supported (allowed levels are [TRACE, DEBUG, INFO])"); - - underTest.changeLevel(WARN); + assertThatThrownBy(() -> underTest.changeLevel(WARN)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("WARN log level is not supported (allowed levels are [TRACE, DEBUG, INFO])"); } } diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/measure/DebtRatingGridTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/measure/DebtRatingGridTest.java index 3a8f7acea6b..ac292c1186a 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/measure/DebtRatingGridTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/measure/DebtRatingGridTest.java @@ -20,11 +20,10 @@ package org.sonar.server.measure; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.server.measure.Rating.A; import static org.sonar.server.measure.Rating.B; import static org.sonar.server.measure.Rating.C; @@ -34,10 +33,6 @@ import static org.sonar.server.measure.Rating.E; public class DebtRatingGridTest { private DebtRatingGrid ratingGrid; - - @Rule - public ExpectedException throwable = ExpectedException.none(); - @Before public void setUp() { double[] gridValues = new double[] {0.1, 0.2, 0.5, 1}; @@ -78,23 +73,23 @@ public class DebtRatingGridTest { @Test public void fail_on_invalid_density() { - throwable.expect(IllegalArgumentException.class); - throwable.expectMessage("Invalid value '-1.0'"); - - ratingGrid.getRatingForDensity(-1); + assertThatThrownBy(() -> ratingGrid.getRatingForDensity(-1)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Invalid value '-1.0'"); } @Test public void fail_to_concert_invalid_value() { - throwable.expect(IllegalArgumentException.class); - Rating.valueOf(10); + assertThatThrownBy(() -> Rating.valueOf(10)) + .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_on_invalid_grid() { - throwable.expect(IllegalStateException.class); - throwable.expectMessage("Rating grid should contains 4 values"); - - ratingGrid = new DebtRatingGrid(new double[] {0.1, 0.2, 0.5}); + assertThatThrownBy(() -> { + ratingGrid = new DebtRatingGrid(new double[] {0.1, 0.2, 0.5}); + }) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Rating grid should contains 4 values"); } } diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/notification/DefaultNotificationManagerTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/notification/DefaultNotificationManagerTest.java index 896e379ce61..7149f7a2ad1 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/notification/DefaultNotificationManagerTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/notification/DefaultNotificationManagerTest.java @@ -32,16 +32,12 @@ import java.util.Set; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.InOrder; import org.sonar.api.notifications.Notification; import org.sonar.api.notifications.NotificationChannel; import org.sonar.api.utils.System2; import org.sonar.api.web.UserRole; -import org.sonar.core.util.UuidFactory; -import org.sonar.core.util.UuidFactoryFast; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.EmailSubscriberDto; @@ -57,6 +53,7 @@ import static com.google.common.collect.Sets.newHashSet; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anySet; @@ -73,8 +70,6 @@ import static org.sonar.server.notification.NotificationManager.SubscriberPermis public class DefaultNotificationManagerTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private DefaultNotificationManager underTest; @@ -270,20 +265,18 @@ public class DefaultNotificationManagerTest { public void findSubscribedEmailRecipients_fails_with_NPE_if_projectKey_is_null() { String dispatcherKey = randomAlphabetic(12); - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("projectKey is mandatory"); - - underTest.findSubscribedEmailRecipients(dispatcherKey, null, ALL_MUST_HAVE_ROLE_USER); + assertThatThrownBy(() -> underTest.findSubscribedEmailRecipients(dispatcherKey, null, ALL_MUST_HAVE_ROLE_USER)) + .isInstanceOf(NullPointerException.class) + .hasMessage("projectKey is mandatory"); } @Test public void findSubscribedEmailRecipients_with_logins_fails_with_NPE_if_projectKey_is_null() { String dispatcherKey = randomAlphabetic(12); - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("projectKey is mandatory"); - - underTest.findSubscribedEmailRecipients(dispatcherKey, null, ImmutableSet.of(), ALL_MUST_HAVE_ROLE_USER); + assertThatThrownBy(() -> underTest.findSubscribedEmailRecipients(dispatcherKey, null, ImmutableSet.of(), ALL_MUST_HAVE_ROLE_USER)) + .isInstanceOf(NullPointerException.class) + .hasMessage("projectKey is mandatory"); } @Test @@ -291,10 +284,9 @@ public class DefaultNotificationManagerTest { String dispatcherKey = randomAlphabetic(12); String projectKey = randomAlphabetic(6); - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("logins can't be null"); - - underTest.findSubscribedEmailRecipients(dispatcherKey, projectKey, null, ALL_MUST_HAVE_ROLE_USER); + assertThatThrownBy(() -> underTest.findSubscribedEmailRecipients(dispatcherKey, projectKey, null, ALL_MUST_HAVE_ROLE_USER)) + .isInstanceOf(NullPointerException.class) + .hasMessage("logins can't be null"); } @Test diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/notification/EmailRecipientTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/notification/EmailRecipientTest.java index 334575d88db..dc3fcf339fa 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/notification/EmailRecipientTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/notification/EmailRecipientTest.java @@ -19,36 +19,31 @@ */ package org.sonar.server.notification; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.server.notification.NotificationManager.EmailRecipient; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class EmailRecipientTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void constructor_fails_with_NPE_if_login_is_null() { String email = randomAlphabetic(12); - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("login can't be null"); - - new EmailRecipient(null, email); + assertThatThrownBy(() -> new EmailRecipient(null, email)) + .isInstanceOf(NullPointerException.class) + .hasMessage("login can't be null"); } @Test public void constructor_fails_with_NPE_if_email_is_null() { String login = randomAlphabetic(12); - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("email can't be null"); - - new EmailRecipient(login, null); + assertThatThrownBy(() -> new EmailRecipient(login, null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("email can't be null"); } @Test diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/notification/NotificationServiceTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/notification/NotificationServiceTest.java index 08c35383246..194609a74b0 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/notification/NotificationServiceTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/notification/NotificationServiceTest.java @@ -27,15 +27,14 @@ import java.util.Random; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.notifications.Notification; import org.sonar.db.DbClient; import org.sonar.db.property.PropertiesDao; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.anyCollection; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; @@ -46,8 +45,6 @@ import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; public class NotificationServiceTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private final DbClient dbClient = mock(DbClient.class); private final PropertiesDao propertiesDao = mock(PropertiesDao.class); @@ -65,10 +62,9 @@ public class NotificationServiceTest { .collect(Collectors.toList()); NotificationService underTest = new NotificationService(dbClient, new NotificationHandler[] {handler}); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Type of notification objects must be a subtype of Notification"); - - underTest.deliverEmails(notifications); + assertThatThrownBy(() -> underTest.deliverEmails(notifications)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Type of notification objects must be a subtype of Notification"); } @Test diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/permission/index/AuthorizationDocTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/permission/index/AuthorizationDocTest.java index 62ec6566e28..6f8a2b18d86 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/permission/index/AuthorizationDocTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/permission/index/AuthorizationDocTest.java @@ -25,21 +25,18 @@ import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.List; import java.util.Random; import java.util.stream.IntStream; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.server.es.Index; import org.sonar.server.es.IndexType; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Fail.fail; @RunWith(DataProviderRunner.class) public class AuthorizationDocTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void idOf_returns_argument_with_a_prefix() { @@ -50,17 +47,15 @@ public class AuthorizationDocTest { @Test public void idOf_fails_with_NPE_if_argument_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("projectUuid can't be null"); - - AuthorizationDoc.idOf(null); + assertThatThrownBy(() -> AuthorizationDoc.idOf(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("projectUuid can't be null"); } @Test public void projectUuidOf_fails_with_NPE_if_argument_is_null() { - expectedException.expect(NullPointerException.class); - - AuthorizationDoc.projectUuidOf(null); + assertThatThrownBy(() -> AuthorizationDoc.projectUuidOf(null)) + .isInstanceOf(NullPointerException.class); } @Test @@ -84,10 +79,9 @@ public class AuthorizationDocTest { IndexType.IndexMainType mainType = IndexType.main(Index.simple("foo"), "bar"); AuthorizationDoc underTest = AuthorizationDoc.fromDto(mainType, dto); - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("projectUuid can't be null"); - - underTest.getId(); + assertThatThrownBy(() -> underTest.getId()) + .isInstanceOf(NullPointerException.class) + .hasMessage("projectUuid can't be null"); } @Test diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/platform/ServerLifecycleNotifierTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/platform/ServerLifecycleNotifierTest.java index c536cd865e5..3cbef0d39bd 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/platform/ServerLifecycleNotifierTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/platform/ServerLifecycleNotifierTest.java @@ -19,7 +19,6 @@ */ package org.sonar.server.platform; -import java.io.File; import java.util.Date; import org.junit.Before; import org.junit.Test; diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/platform/StartupMetadataProviderTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/platform/StartupMetadataProviderTest.java index aa59b1782f4..68cc7c03f08 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/platform/StartupMetadataProviderTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/platform/StartupMetadataProviderTest.java @@ -21,7 +21,6 @@ package org.sonar.server.platform; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.CoreProperties; import org.sonar.api.SonarEdition; import org.sonar.api.SonarQubeSide; @@ -33,6 +32,7 @@ import org.sonar.db.DbTester; import org.sonar.db.property.PropertyDto; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; @@ -42,8 +42,6 @@ public class StartupMetadataProviderTest { private static final long A_DATE = 1_500_000_000_000L; - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); @@ -95,9 +93,9 @@ public class StartupMetadataProviderTest { SonarRuntime runtime = SonarRuntimeImpl.forSonarQube(Version.create(6, 1), SonarQubeSide.COMPUTE_ENGINE, SonarEdition.COMMUNITY); when(webServer.isStartupLeader()).thenReturn(false); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Property sonar.core.startTime is missing in database"); - underTest.provide(system, runtime, webServer, dbTester.getDbClient()); + assertThatThrownBy(() -> underTest.provide(system, runtime, webServer, dbTester.getDbClient())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Property sonar.core.startTime is missing in database"); } private void testLoadingFromDatabase(SonarRuntime runtime, boolean isStartupLeader) { diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/platform/TempFolderProviderTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/platform/TempFolderProviderTest.java index 421b849a2ba..108c22444a7 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/platform/TempFolderProviderTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/platform/TempFolderProviderTest.java @@ -23,7 +23,6 @@ import java.io.File; import org.apache.commons.io.FileUtils; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.sonar.api.utils.TempFolder; @@ -33,8 +32,6 @@ import static org.mockito.Mockito.when; public class TempFolderProviderTest { - @Rule - public ExpectedException throwable = ExpectedException.none(); @Rule public TemporaryFolder temp = new TemporaryFolder(); diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/platform/UrlSettingsTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/platform/UrlSettingsTest.java index f05cf4dc846..832145e2650 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/platform/UrlSettingsTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/platform/UrlSettingsTest.java @@ -19,15 +19,14 @@ */ package org.sonar.server.platform; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.config.PropertyDefinitions; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.utils.System2; import org.sonar.core.config.CorePropertyDefinitions; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.CoreProperties.SERVER_BASE_URL; public class UrlSettingsTest { @@ -36,8 +35,6 @@ public class UrlSettingsTest { private static final String PORT_PORPERTY = "sonar.web.port"; private static final String CONTEXT_PROPERTY = "sonar.web.context"; - @Rule - public ExpectedException expectedException = ExpectedException.none(); private MapSettings settings = new MapSettings(new PropertyDefinitions(System2.INSTANCE, CorePropertyDefinitions.all())); @@ -161,8 +158,9 @@ public class UrlSettingsTest { public void getBaseUrl_throws_when_port_not_an_int() { settings.setProperty(PORT_PORPERTY, "not a number"); - expectedException.expect(IllegalStateException.class); - underTest().getBaseUrl(); + assertThatThrownBy(() -> underTest().getBaseUrl()) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("The property 'sonar.web.port' is not an int value"); } @Test diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/platform/WebServerImplTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/platform/WebServerImplTest.java index 44c02d326b4..1ca39c7b16f 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/platform/WebServerImplTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/platform/WebServerImplTest.java @@ -19,17 +19,13 @@ */ package org.sonar.server.platform; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.config.internal.MapSettings; import static org.assertj.core.api.Assertions.assertThat; public class WebServerImplTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private MapSettings settings = new MapSettings(); diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/platform/monitoring/cluster/ProcessInfoProviderTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/platform/monitoring/cluster/ProcessInfoProviderTest.java index 2bad5f08533..5bd9310efea 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/platform/monitoring/cluster/ProcessInfoProviderTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/platform/monitoring/cluster/ProcessInfoProviderTest.java @@ -20,9 +20,7 @@ package org.sonar.server.platform.monitoring.cluster; import java.util.List; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.process.systeminfo.SystemInfoSection; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; @@ -30,8 +28,6 @@ import static org.assertj.core.api.Assertions.assertThat; public class ProcessInfoProviderTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void remove_global_sections_from_results() { diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/platform/serverid/ServerIdChecksumTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/platform/serverid/ServerIdChecksumTest.java index 3438d709a84..c9da5949241 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/platform/serverid/ServerIdChecksumTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/platform/serverid/ServerIdChecksumTest.java @@ -19,28 +19,24 @@ */ package org.sonar.server.platform.serverid; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.config.internal.MapSettings; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.process.ProcessProperties.Property.JDBC_URL; public class ServerIdChecksumTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void compute_throws_ISE_if_jdbcUrl_property_is_not_set() { ServerIdChecksum underTest = new ServerIdChecksum(new MapSettings().asConfig(), null /*doesn't matter*/); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Missing JDBC URL"); - - underTest.computeFor("foo"); + assertThatThrownBy(() -> underTest.computeFor("foo")) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Missing JDBC URL"); } @Test diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/plugins/InstalledPluginReferentialFactoryTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/plugins/InstalledPluginReferentialFactoryTest.java index 33883061aea..3044f98e5a9 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/plugins/InstalledPluginReferentialFactoryTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/plugins/InstalledPluginReferentialFactoryTest.java @@ -25,6 +25,7 @@ import org.sonar.core.platform.PluginRepository; import static com.google.common.collect.Lists.newArrayList; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -43,11 +44,12 @@ public class InstalledPluginReferentialFactoryTest { assertThat(factory.getInstalledPluginReferential().getPlugins()).hasSize(1); } - @Test(expected = RuntimeException.class) + @Test public void should_encapsulate_exception() { PluginRepository pluginRepository = mock(PluginRepository.class); when(pluginRepository.getPluginInfos()).thenThrow(new IllegalArgumentException()); InstalledPluginReferentialFactory factory = new InstalledPluginReferentialFactory(pluginRepository); - factory.start(); + assertThatThrownBy(factory::start) + .isInstanceOf(RuntimeException.class); } } diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/plugins/ServerExtensionInstallerTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/plugins/ServerExtensionInstallerTest.java index 1e3d2110cb5..137d99288b2 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/plugins/ServerExtensionInstallerTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/plugins/ServerExtensionInstallerTest.java @@ -22,9 +22,7 @@ package org.sonar.server.plugins; import java.util.Collection; import java.util.HashMap; import java.util.Map; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.Plugin; import org.sonar.api.SonarEdition; import org.sonar.api.SonarQubeSide; @@ -42,10 +40,6 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class ServerExtensionInstallerTest { - - @Rule - public ExpectedException expectedException = ExpectedException.none(); - private SonarRuntime sonarRuntime = SonarRuntimeImpl.forSonarQube(Version.parse("8.0"), SonarQubeSide.SERVER, SonarEdition.COMMUNITY); private TestPluginRepository pluginRepository = new TestPluginRepository(); diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/property/InternalPropertiesImplTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/property/InternalPropertiesImplTest.java index 265d882a4eb..58d1a61ffd1 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/property/InternalPropertiesImplTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/property/InternalPropertiesImplTest.java @@ -20,15 +20,15 @@ package org.sonar.server.property; import java.util.Optional; +import org.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.property.InternalPropertiesDao; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -38,9 +38,7 @@ public class InternalPropertiesImplTest { public static final String SOME_VALUE = "a value"; public static final String SOME_KEY = "some key"; - @Rule - public ExpectedException expectedException = ExpectedException.none(); - + private DbClient dbClient = mock(DbClient.class); private DbSession dbSession = mock(DbSession.class); private InternalPropertiesDao internalPropertiesDao = mock(InternalPropertiesDao.class); @@ -54,16 +52,12 @@ public class InternalPropertiesImplTest { @Test public void reads_throws_IAE_if_key_is_null() { - expectKeyNullOrEmptyIAE(); - - underTest.read(null); + expectKeyNullOrEmptyIAE(() -> underTest.read(null)); } @Test public void reads_throws_IAE_if_key_is_empty() { - expectKeyNullOrEmptyIAE(); - - underTest.read(EMPTY_STRING); + expectKeyNullOrEmptyIAE(() -> underTest.read(EMPTY_STRING)); } @Test @@ -77,16 +71,12 @@ public class InternalPropertiesImplTest { @Test public void write_throws_IAE_if_key_is_null() { - expectKeyNullOrEmptyIAE(); - - underTest.write(null, SOME_VALUE); + expectKeyNullOrEmptyIAE(() -> underTest.write(null, SOME_VALUE)); } @Test public void writes_throws_IAE_if_key_is_empty() { - expectKeyNullOrEmptyIAE(); - - underTest.write(EMPTY_STRING, SOME_VALUE); + expectKeyNullOrEmptyIAE(() -> underTest.write(EMPTY_STRING, SOME_VALUE)); } @Test @@ -113,8 +103,9 @@ public class InternalPropertiesImplTest { verify(dbSession).commit(); } - private void expectKeyNullOrEmptyIAE() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("key can't be null nor empty"); + private void expectKeyNullOrEmptyIAE(ThrowingCallable callback) { + assertThatThrownBy(callback) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("key can't be null nor empty"); } } diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/qualitygate/ConditionEvaluatorTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/qualitygate/ConditionEvaluatorTest.java index d377e9d658c..bd559418596 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/qualitygate/ConditionEvaluatorTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/qualitygate/ConditionEvaluatorTest.java @@ -24,13 +24,12 @@ import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.Optional; import javax.annotation.Nullable; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.api.measures.Metric; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.measures.Metric.ValueType.BOOL; import static org.sonar.api.measures.Metric.ValueType.DATA; import static org.sonar.api.measures.Metric.ValueType.DISTRIB; @@ -39,8 +38,6 @@ import static org.sonar.server.qualitygate.FakeMeasure.newMeasureOnLeak; @RunWith(DataProviderRunner.class) public class ConditionEvaluatorTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void GREATER_THAN_double() { @@ -80,11 +77,9 @@ public class ConditionEvaluatorTest { @Test public void evaluate_throws_IAE_if_fail_to_parse_threshold() { - - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Quality Gate: unable to parse threshold '9bar' to compare against foo"); - - test(new FakeMeasure(10), Condition.Operator.LESS_THAN, "9bar", EvaluatedCondition.EvaluationStatus.ERROR, "10da"); + assertThatThrownBy(() -> test(new FakeMeasure(10), Condition.Operator.LESS_THAN, "9bar", EvaluatedCondition.EvaluationStatus.ERROR, "10da")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Quality Gate: unable to parse threshold '9bar' to compare against foo"); } @Test @@ -97,10 +92,9 @@ public class ConditionEvaluatorTest { @Test @UseDataProvider("unsupportedMetricTypes") public void fail_when_condition_is_on_unsupported_metric(Metric.ValueType metricType) { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(String.format("Condition is not allowed for type %s", metricType)); - - test(new FakeMeasure(metricType), Condition.Operator.LESS_THAN, "9", EvaluatedCondition.EvaluationStatus.OK, "10"); + assertThatThrownBy(() -> test(new FakeMeasure(metricType), Condition.Operator.LESS_THAN, "9", EvaluatedCondition.EvaluationStatus.OK, "10")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage(String.format("Condition is not allowed for type %s", metricType)); } @DataProvider diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/qualitygate/ConditionTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/qualitygate/ConditionTest.java index a521d2af81d..1acf39a9985 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/qualitygate/ConditionTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/qualitygate/ConditionTest.java @@ -20,44 +20,38 @@ package org.sonar.server.qualitygate; import java.util.Arrays; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class ConditionTest { private static final String METRIC_KEY = "metric_key"; private static final Condition.Operator OPERATOR = Condition.Operator.GREATER_THAN; private static final String ERROR_THRESHOLD = "2"; - @Rule - public ExpectedException expectedException = ExpectedException.none(); private Condition underTest = new Condition(METRIC_KEY, OPERATOR, ERROR_THRESHOLD); @Test public void constructor_throws_NPE_if_metricKey_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("metricKey can't be null"); - - new Condition(null, OPERATOR, ERROR_THRESHOLD); + assertThatThrownBy(() -> new Condition(null, OPERATOR, ERROR_THRESHOLD)) + .isInstanceOf(NullPointerException.class) + .hasMessage("metricKey can't be null"); } @Test public void constructor_throws_NPE_if_operator_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("operator can't be null"); - - new Condition(METRIC_KEY, null, ERROR_THRESHOLD); + assertThatThrownBy(() -> new Condition(METRIC_KEY, null, ERROR_THRESHOLD)) + .isInstanceOf(NullPointerException.class) + .hasMessage("operator can't be null"); } @Test public void constructor_throws_NPE_if_errorThreshold_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("errorThreshold can't be null"); - - new Condition(METRIC_KEY, OPERATOR, null); + assertThatThrownBy(() -> new Condition(METRIC_KEY, OPERATOR, null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("errorThreshold can't be null"); } @Test diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/qualitygate/EvaluatedConditionTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/qualitygate/EvaluatedConditionTest.java index 4f8f12e45b9..641301e106a 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/qualitygate/EvaluatedConditionTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/qualitygate/EvaluatedConditionTest.java @@ -19,11 +19,10 @@ */ package org.sonar.server.qualitygate; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.server.qualitygate.Condition.Operator.GREATER_THAN; import static org.sonar.server.qualitygate.EvaluatedCondition.EvaluationStatus.ERROR; import static org.sonar.server.qualitygate.EvaluatedCondition.EvaluationStatus.OK; @@ -31,25 +30,21 @@ import static org.sonar.server.qualitygate.EvaluatedCondition.EvaluationStatus.O public class EvaluatedConditionTest { private static final Condition CONDITION_1 = new Condition("metricKey", GREATER_THAN, "2"); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private EvaluatedCondition underTest = new EvaluatedCondition(CONDITION_1, ERROR, "value"); @Test public void constructor_throws_NPE_if_condition_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("condition can't be null"); - - new EvaluatedCondition(null, ERROR, "value"); + assertThatThrownBy(() -> new EvaluatedCondition(null, ERROR, "value")) + .isInstanceOf(NullPointerException.class) + .hasMessage("condition can't be null"); } @Test public void constructor_throws_NPE_if_EvaluationStatus_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("status can't be null"); - - new EvaluatedCondition(CONDITION_1, null, "value"); + assertThatThrownBy(() -> new EvaluatedCondition(CONDITION_1, null, "value")) + .isInstanceOf(NullPointerException.class) + .hasMessage("status can't be null"); } @Test diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/qualitygate/EvaluatedQualityGateTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/qualitygate/EvaluatedQualityGateTest.java index 0f1d2c63638..7925687d756 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/qualitygate/EvaluatedQualityGateTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/qualitygate/EvaluatedQualityGateTest.java @@ -24,15 +24,14 @@ import java.util.Arrays; import java.util.HashSet; import java.util.Random; import org.apache.commons.lang.RandomStringUtils; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.measures.CoreMetrics; import org.sonar.api.measures.Metric.Level; import static java.util.Collections.emptySet; import static java.util.Collections.singleton; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.server.qualitygate.EvaluatedQualityGate.newBuilder; public class EvaluatedQualityGateTest { @@ -47,8 +46,6 @@ public class EvaluatedQualityGateTest { private static final QualityGate ALL_CONDITIONS_QUALITY_GATE = new QualityGate(QUALITY_GATE_ID, QUALITY_GATE_NAME, new HashSet<>(Arrays.asList(CONDITION_1, CONDITION_2, CONDITION_3))); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private final Random random = new Random(); private final Level randomStatus = Level.values()[random.nextInt(Level.values().length)]; @@ -62,26 +59,23 @@ public class EvaluatedQualityGateTest { public void build_fails_with_NPE_if_status_not_set() { builder.setQualityGate(NO_CONDITION_QUALITY_GATE); - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("status can't be null"); - - builder.build(); + assertThatThrownBy(() -> builder.build()) + .isInstanceOf(NullPointerException.class) + .hasMessage("status can't be null"); } @Test public void addCondition_fails_with_NPE_if_condition_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("condition can't be null"); - - builder.addEvaluatedCondition(null, EvaluatedCondition.EvaluationStatus.ERROR, "a_value"); + assertThatThrownBy(() -> builder.addEvaluatedCondition(null, EvaluatedCondition.EvaluationStatus.ERROR, "a_value")) + .isInstanceOf(NullPointerException.class) + .hasMessage("condition can't be null"); } @Test public void addCondition_fails_with_NPE_if_status_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("status can't be null"); - - builder.addEvaluatedCondition(new Condition("metric_key", Condition.Operator.LESS_THAN, "2"), null, "a_value"); + assertThatThrownBy(() -> builder.addEvaluatedCondition(new Condition("metric_key", Condition.Operator.LESS_THAN, "2"), null, "a_value")) + .isInstanceOf(NullPointerException.class) + .hasMessage("status can't be null"); } @Test @@ -103,10 +97,9 @@ public class EvaluatedQualityGateTest { .setStatus(randomStatus) .addEvaluatedCondition(CONDITION_1, randomEvaluationStatus, randomValue); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Evaluation provided for unknown conditions: [" + CONDITION_1 + "]"); - - builder.build(); + assertThatThrownBy(() -> builder.build()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Evaluation provided for unknown conditions: [" + CONDITION_1 + "]"); } @Test @@ -114,10 +107,9 @@ public class EvaluatedQualityGateTest { builder.setQualityGate(ONE_CONDITION_QUALITY_GATE) .setStatus(randomStatus); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Evaluation missing for the following conditions: [" + CONDITION_1 + "]"); - - builder.build(); + assertThatThrownBy(() -> builder.build()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Evaluation missing for the following conditions: [" + CONDITION_1 + "]"); } @Test diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/qualitygate/QualityGateTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/qualitygate/QualityGateTest.java index 88f67ed5277..d6c5bee2f62 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/qualitygate/QualityGateTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/qualitygate/QualityGateTest.java @@ -25,12 +25,11 @@ import java.util.Set; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static java.util.Collections.emptySet; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class QualityGateTest { private static final String QUALIGATE_ID = "qg_id"; @@ -38,53 +37,45 @@ public class QualityGateTest { private static final Condition CONDITION_1 = new Condition("m1", Condition.Operator.GREATER_THAN, "1"); private static final Condition CONDITION_2 = new Condition("m2", Condition.Operator.LESS_THAN, "2"); - @Rule - public ExpectedException expectedException = ExpectedException.none(); - private QualityGate underTest = new QualityGate(QUALIGATE_ID, QUALIGATE_NAME, ImmutableSet.of(CONDITION_1, CONDITION_2)); @Test public void constructor_fails_with_NPE_if_id_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("id can't be null"); - - new QualityGate(null, "name", emptySet()); + assertThatThrownBy(() -> new QualityGate(null, "name", emptySet())) + .isInstanceOf(NullPointerException.class) + .hasMessage("id can't be null"); } @Test public void constructor_fails_with_NPE_if_name_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("name can't be null"); - - new QualityGate("id", null, emptySet()); + assertThatThrownBy(() -> new QualityGate("id", null, emptySet())) + .isInstanceOf(NullPointerException.class) + .hasMessage("name can't be null"); } @Test public void constructor_fails_with_NPE_if_conditions_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("conditions can't be null"); - - new QualityGate("id", "name", null); + assertThatThrownBy(() ->new QualityGate("id", "name", null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("conditions can't be null"); } @Test public void constructor_fails_with_NPE_if_conditions_contains_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("condition can't be null"); Random random = new Random(); + Set conditions = Stream.of( - IntStream.range(0, random.nextInt(5)) - .mapToObj(i -> new Condition("m_before_" + i, Condition.Operator.GREATER_THAN, "10")), - Stream.of((Condition) null), - IntStream.range(0, random.nextInt(5)) - .mapToObj(i -> new Condition("m_after_" + i, Condition.Operator.GREATER_THAN, "10"))) + IntStream.range(0, random.nextInt(5)) + .mapToObj(i -> new Condition("m_before_" + i, Condition.Operator.GREATER_THAN, "10")), + Stream.of((Condition) null), + IntStream.range(0, random.nextInt(5)) + .mapToObj(i -> new Condition("m_after_" + i, Condition.Operator.GREATER_THAN, "10"))) .flatMap(s -> s) .collect(Collectors.toSet()); - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("condition can't be null"); - - new QualityGate("id", "name", conditions); + assertThatThrownBy(() -> new QualityGate("id", "name", conditions)) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("condition can't be null"); } @Test diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/qualityprofile/QualityProfileTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/qualityprofile/QualityProfileTest.java index ab7a0e20e27..d155a16800c 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/qualityprofile/QualityProfileTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/qualityprofile/QualityProfileTest.java @@ -24,6 +24,7 @@ import org.junit.Test; import org.sonar.api.utils.DateUtils; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class QualityProfileTest { @@ -33,24 +34,37 @@ public class QualityProfileTest { private static final Date SOME_DATE = DateUtils.parseDateTimeQuietly("2010-05-18T15:50:45+0100"); private static final QualityProfile QUALITY_PROFILE = new QualityProfile(SOME_QP_KEY, SOME_QP_NAME, SOME_LANGUAGE_KEY, SOME_DATE); - @Test(expected = NullPointerException.class) + @Test public void constructor_throws_NPE_if_qkKey_arg_is_null() { - new QualityProfile(null, SOME_QP_NAME, SOME_LANGUAGE_KEY, SOME_DATE); + assertThatThrownBy(() -> { + new QualityProfile(null, SOME_QP_NAME, SOME_LANGUAGE_KEY, SOME_DATE); + }) + .isInstanceOf(NullPointerException.class); } - @Test(expected = NullPointerException.class) + @Test public void constructor_throws_NPE_if_qpName_arg_is_null() { - new QualityProfile(SOME_QP_KEY, null, SOME_LANGUAGE_KEY, SOME_DATE); + + assertThatThrownBy(() -> { + new QualityProfile(SOME_QP_KEY, null, SOME_LANGUAGE_KEY, SOME_DATE); + }) + .isInstanceOf(NullPointerException.class); } - @Test(expected = NullPointerException.class) + @Test public void constructor_throws_NPE_if_languageKey_arg_is_null() { - new QualityProfile(SOME_QP_KEY, SOME_QP_NAME, null, SOME_DATE); + assertThatThrownBy(() -> { + new QualityProfile(SOME_QP_KEY, SOME_QP_NAME, null, SOME_DATE); + }) + .isInstanceOf(NullPointerException.class); } - @Test(expected = NullPointerException.class) + @Test public void constructor_throws_NPE_if_rulesUpdatedAt_arg_is_null() { - new QualityProfile(SOME_QP_KEY, SOME_QP_NAME, SOME_LANGUAGE_KEY, null); + assertThatThrownBy(() -> { + new QualityProfile(SOME_QP_KEY, SOME_QP_NAME, SOME_LANGUAGE_KEY, null); + }) + .isInstanceOf(NullPointerException.class); } @Test diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/rule/index/RuleIndexDefinitionTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/rule/index/RuleIndexDefinitionTest.java index de951814d2d..1dacc4c7f40 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/rule/index/RuleIndexDefinitionTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/rule/index/RuleIndexDefinitionTest.java @@ -24,7 +24,6 @@ import java.io.IOException; import java.util.List; import org.apache.commons.lang.StringUtils; import org.apache.lucene.search.TotalHits; -import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.indices.AnalyzeRequest; import org.elasticsearch.client.indices.AnalyzeResponse; diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/rule/index/RuleIndexTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/rule/index/RuleIndexTest.java index 2eef880893e..206eba38cb4 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/rule/index/RuleIndexTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/rule/index/RuleIndexTest.java @@ -27,7 +27,6 @@ import java.util.Map; import java.util.function.Consumer; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.impl.utils.AlwaysIncreasingSystem2; import org.sonar.api.rule.RuleKey; import org.sonar.api.rule.RuleStatus; @@ -49,6 +48,7 @@ import static java.util.Collections.emptySet; import static java.util.Collections.singletonList; import static java.util.stream.IntStream.rangeClosed; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.entry; import static org.junit.Assert.fail; import static org.sonar.api.rule.Severity.BLOCKER; @@ -94,8 +94,6 @@ public class RuleIndexTest { public EsTester es = EsTester.create(); @Rule public DbTester db = DbTester.create(system2); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private RuleIndexer ruleIndexer = new RuleIndexer(es.client(), db.getDbClient()); private ActiveRuleIndexer activeRuleIndexer = new ActiveRuleIndexer(db.getDbClient(), es.client()); @@ -738,10 +736,9 @@ public class RuleIndexTest { @Test public void fail_to_list_tags_when_size_greater_than_500() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Page size must be lower than or equals to 500"); - - underTest.listTags(null, 501); + assertThatThrownBy(() -> underTest.listTags(null, 501)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Page size must be lower than or equals to 500"); } @Test diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/setting/ChildSettingsTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/setting/ChildSettingsTest.java index 57052e7065c..1927a5f1f9e 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/setting/ChildSettingsTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/setting/ChildSettingsTest.java @@ -23,9 +23,7 @@ import java.util.Collections; import java.util.Date; import java.util.Optional; import java.util.Random; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.config.PropertyDefinition; import org.sonar.api.config.PropertyDefinitions; import org.sonar.api.config.internal.MapSettings; @@ -33,12 +31,11 @@ import org.sonar.api.utils.System2; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class ChildSettingsTest { private static final Random RANDOM = new Random(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private MapSettings parent = new MapSettings(); private ChildSettings underTest = new ChildSettings(parent); @@ -66,18 +63,16 @@ public class ChildSettingsTest { @Test public void set_will_throw_NPE_if_key_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("key can't be null"); - - underTest.set(null, ""); + assertThatThrownBy(() -> underTest.set(null, "")) + .isInstanceOf(NullPointerException.class) + .hasMessage("key can't be null"); } @Test public void set_will_throw_NPE_if_value_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("value can't be null"); - - underTest.set(randomAlphanumeric(10), null); + assertThatThrownBy(() -> underTest.set(randomAlphanumeric(10), null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("value can't be null"); } @Test diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/setting/DatabaseSettingsEnablerTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/setting/DatabaseSettingsEnablerTest.java index b18c7fbded6..6b41e63cb03 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/setting/DatabaseSettingsEnablerTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/setting/DatabaseSettingsEnablerTest.java @@ -20,17 +20,13 @@ package org.sonar.server.setting; import org.junit.After; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; public class DatabaseSettingsEnablerTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private ThreadLocalSettings settings = mock(ThreadLocalSettings.class); private DatabaseSettingLoader loader = mock(DatabaseSettingLoader.class); diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/setting/ThreadLocalSettingsTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/setting/ThreadLocalSettingsTest.java index adbba9c4e7f..284eb6e4d23 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/setting/ThreadLocalSettingsTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/setting/ThreadLocalSettingsTest.java @@ -31,7 +31,6 @@ import org.apache.ibatis.exceptions.PersistenceException; import org.junit.After; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.sonar.api.Property; import org.sonar.api.config.PropertyDefinitions; @@ -53,8 +52,6 @@ public class ThreadLocalSettingsTest { private static final String A_KEY = "a_key"; - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public TemporaryFolder temp = new TemporaryFolder(); diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/util/AbstractStoppableExecutorServiceTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/util/AbstractStoppableExecutorServiceTest.java index 499e7e62f8f..5877c2b07ac 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/util/AbstractStoppableExecutorServiceTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/util/AbstractStoppableExecutorServiceTest.java @@ -20,15 +20,14 @@ package org.sonar.server.util; import com.google.common.collect.ImmutableList; -import org.junit.Test; -import org.mockito.InOrder; -import org.mockito.Mockito; - import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; +import org.junit.Test; +import org.mockito.InOrder; +import org.mockito.Mockito; import static java.util.concurrent.TimeUnit.SECONDS; import static org.mockito.Mockito.mock; diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/webhook/AnalysisTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/webhook/AnalysisTest.java index 6d0ee86acab..9b4096d0266 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/webhook/AnalysisTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/webhook/AnalysisTest.java @@ -19,23 +19,19 @@ */ package org.sonar.server.webhook; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class AnalysisTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void constructor_throws_NPE_when_uuid_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("uuid must not be null"); - - new Analysis(null, 1_990L, "abcde"); + assertThatThrownBy(() -> new Analysis(null, 1_990L, "abcde")) + .isInstanceOf(NullPointerException.class) + .hasMessage("uuid must not be null"); } @Test diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/webhook/BranchTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/webhook/BranchTest.java index 8b693f69fda..bd373e6df3b 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/webhook/BranchTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/webhook/BranchTest.java @@ -20,24 +20,20 @@ package org.sonar.server.webhook; import java.util.Random; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class BranchTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private Branch underTest = new Branch(true, "b", Branch.Type.BRANCH); @Test public void constructor_throws_NPE_if_type_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("type can't be null"); - - new Branch(new Random().nextBoolean(), "s", null); + assertThatThrownBy(() -> new Branch(new Random().nextBoolean(), "s", null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("type can't be null"); } @Test diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/webhook/CeTaskTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/webhook/CeTaskTest.java index c877a408c80..a02e566f371 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/webhook/CeTaskTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/webhook/CeTaskTest.java @@ -19,32 +19,27 @@ */ package org.sonar.server.webhook; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class CeTaskTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private CeTask underTest = new CeTask("A", CeTask.Status.SUCCESS); @Test public void constructor_throws_NPE_if_id_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("id can't be null"); - - new CeTask(null, CeTask.Status.SUCCESS); + assertThatThrownBy(() -> new CeTask(null, CeTask.Status.SUCCESS)) + .isInstanceOf(NullPointerException.class) + .hasMessage("id can't be null"); } @Test public void constructor_throws_NPE_if_status_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("status can't be null"); - - new CeTask("B", null); + assertThatThrownBy(() -> new CeTask("B", null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("status can't be null"); } @Test diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/webhook/ProjectAnalysisTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/webhook/ProjectAnalysisTest.java index 56b7f3cc4ec..491965a80a7 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/webhook/ProjectAnalysisTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/webhook/ProjectAnalysisTest.java @@ -21,9 +21,7 @@ package org.sonar.server.webhook; import com.google.common.collect.ImmutableMap; import java.util.Map; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.measures.Metric; import org.sonar.server.qualitygate.EvaluatedQualityGate; import org.sonar.server.qualitygate.QualityGate; @@ -31,10 +29,9 @@ import org.sonar.server.qualitygate.QualityGate; import static java.util.Collections.emptyMap; import static java.util.Collections.emptySet; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class ProjectAnalysisTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private final CeTask ceTask = new CeTask("id", CeTask.Status.SUCCESS); private final Project project = new Project("uuid", "key", "name"); @@ -49,30 +46,32 @@ public class ProjectAnalysisTest { @Test public void constructor_throws_NPE_if_project_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("project can't be null"); - - new ProjectAnalysis(null, - ceTask, - analysis, - branch, - qualityGate, - 1L, - emptyMap()); + assertThatThrownBy(() -> { + new ProjectAnalysis(null, + ceTask, + analysis, + branch, + qualityGate, + 1L, + emptyMap()); + }) + .isInstanceOf(NullPointerException.class) + .hasMessage("project can't be null"); } @Test public void constructor_throws_NPE_if_properties_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("properties can't be null"); - - new ProjectAnalysis(project, - ceTask, - analysis, - branch, - qualityGate, - 1L, - null); + assertThatThrownBy(() -> { + new ProjectAnalysis(project, + ceTask, + analysis, + branch, + qualityGate, + 1L, + null); + }) + .isInstanceOf(NullPointerException.class) + .hasMessage("properties can't be null"); } @Test diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/webhook/TestWebhookCaller.java b/server/sonar-server-common/src/test/java/org/sonar/server/webhook/TestWebhookCaller.java index 562728c9a45..2981fff2747 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/webhook/TestWebhookCaller.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/webhook/TestWebhookCaller.java @@ -21,7 +21,6 @@ package org.sonar.server.webhook; import java.util.LinkedList; import java.util.Queue; -import java.util.concurrent.atomic.AtomicInteger; import javax.annotation.Nullable; import static java.util.Objects.requireNonNull; diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/webhook/WebhookModuleTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/webhook/WebhookModuleTest.java index ff885245925..9a98c13aaaf 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/webhook/WebhookModuleTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/webhook/WebhookModuleTest.java @@ -19,13 +19,10 @@ */ package org.sonar.server.webhook; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.core.platform.ComponentContainer; import static org.assertj.core.api.Assertions.assertThat; -import static org.sonar.core.platform.ComponentContainer.COMPONENTS_IN_EMPTY_COMPONENT_CONTAINER; public class WebhookModuleTest { diff --git a/server/sonar-webserver-api/src/test/java/org/sonar/server/app/ProcessCommandWrapperImplTest.java b/server/sonar-webserver-api/src/test/java/org/sonar/server/app/ProcessCommandWrapperImplTest.java index c9a74ee0272..9b582f7ad58 100644 --- a/server/sonar-webserver-api/src/test/java/org/sonar/server/app/ProcessCommandWrapperImplTest.java +++ b/server/sonar-webserver-api/src/test/java/org/sonar/server/app/ProcessCommandWrapperImplTest.java @@ -24,12 +24,12 @@ import java.io.IOException; import java.util.Random; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.sonar.api.config.internal.MapSettings; import org.sonar.process.sharedmemoryfile.DefaultProcessCommands; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.process.ProcessEntryPoint.PROPERTY_PROCESS_INDEX; import static org.sonar.process.ProcessEntryPoint.PROPERTY_SHARED_PATH; @@ -38,8 +38,6 @@ public class ProcessCommandWrapperImplTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private MapSettings settings = new MapSettings(); @@ -47,10 +45,9 @@ public class ProcessCommandWrapperImplTest { public void requestSQRestart_throws_IAE_if_process_index_property_not_set() { ProcessCommandWrapperImpl processCommandWrapper = new ProcessCommandWrapperImpl(settings.asConfig()); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Property process.index is not set"); - - processCommandWrapper.requestSQRestart(); + assertThatThrownBy(processCommandWrapper::requestSQRestart) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Property process.index is not set"); } @Test @@ -58,10 +55,9 @@ public class ProcessCommandWrapperImplTest { settings.setProperty(PROPERTY_PROCESS_INDEX, 1); ProcessCommandWrapperImpl processCommandWrapper = new ProcessCommandWrapperImpl(settings.asConfig()); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Property process.sharedDir is not set"); - - processCommandWrapper.requestSQRestart(); + assertThatThrownBy(processCommandWrapper::requestSQRestart) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Property process.sharedDir is not set"); } @Test @@ -83,10 +79,9 @@ public class ProcessCommandWrapperImplTest { settings.setProperty(PROPERTY_PROCESS_INDEX, 1); ProcessCommandWrapperImpl processCommandWrapper = new ProcessCommandWrapperImpl(settings.asConfig()); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Property process.sharedDir is not set"); - - processCommandWrapper.requestHardStop(); + assertThatThrownBy(processCommandWrapper::requestHardStop) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Property process.sharedDir is not set"); } @Test @@ -108,20 +103,18 @@ public class ProcessCommandWrapperImplTest { settings.setProperty(PROPERTY_PROCESS_INDEX, 1); ProcessCommandWrapperImpl processCommandWrapper = new ProcessCommandWrapperImpl(settings.asConfig()); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Property process.sharedDir is not set"); - - processCommandWrapper.notifyOperational(); + assertThatThrownBy(processCommandWrapper::notifyOperational) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Property process.sharedDir is not set"); } @Test public void notifyOperational_throws_IAE_if_process_index_property_not_set() { ProcessCommandWrapperImpl processCommandWrapper = new ProcessCommandWrapperImpl(settings.asConfig()); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Property process.index is not set"); - - processCommandWrapper.notifyOperational(); + assertThatThrownBy(processCommandWrapper::notifyOperational) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Property process.index is not set"); } @Test diff --git a/server/sonar-webserver-api/src/test/java/org/sonar/server/exceptions/BadRequestExceptionTest.java b/server/sonar-webserver-api/src/test/java/org/sonar/server/exceptions/BadRequestExceptionTest.java index b228271865a..ddc026e7b5a 100644 --- a/server/sonar-webserver-api/src/test/java/org/sonar/server/exceptions/BadRequestExceptionTest.java +++ b/server/sonar-webserver-api/src/test/java/org/sonar/server/exceptions/BadRequestExceptionTest.java @@ -20,18 +20,13 @@ package org.sonar.server.exceptions; import java.util.Collections; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class BadRequestExceptionTest { - - @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Test public void text_error() { BadRequestException exception = BadRequestException.create("error"); @@ -61,25 +56,22 @@ public class BadRequestExceptionTest { @Test public void fail_when_creating_exception_with_empty_list() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("At least one error message is required"); - - BadRequestException.create(Collections.emptyList()); + assertThatThrownBy(() -> BadRequestException.create(Collections.emptyList())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("At least one error message is required"); } @Test public void fail_when_creating_exception_with_one_empty_element() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Message cannot be empty"); - - BadRequestException.create(asList("error", "")); + assertThatThrownBy(() -> BadRequestException.create(asList("error", ""))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Message cannot be empty"); } @Test public void fail_when_creating_exception_with_one_null_element() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Message cannot be empty"); - - BadRequestException.create(asList("error", null)); + assertThatThrownBy(() -> BadRequestException.create(asList("error", null))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Message cannot be empty"); } } diff --git a/server/sonar-webserver-api/src/test/java/org/sonar/server/exceptions/MessageTest.java b/server/sonar-webserver-api/src/test/java/org/sonar/server/exceptions/MessageTest.java index 52deb2c6192..bf3e75dbc1e 100644 --- a/server/sonar-webserver-api/src/test/java/org/sonar/server/exceptions/MessageTest.java +++ b/server/sonar-webserver-api/src/test/java/org/sonar/server/exceptions/MessageTest.java @@ -19,17 +19,12 @@ */ package org.sonar.server.exceptions; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class MessageTest { - - @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Test public void create_message() { Message message = Message.of("key1 %s", "param1"); @@ -44,16 +39,14 @@ public class MessageTest { @Test public void fail_when_message_is_null() { - expectedException.expect(IllegalArgumentException.class); - - Message.of(null); + assertThatThrownBy(() -> Message.of(null)) + .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_when_message_is_empty() { - expectedException.expect(IllegalArgumentException.class); - - Message.of(""); + assertThatThrownBy(() -> Message.of("")) + .isInstanceOf(IllegalArgumentException.class); } @Test diff --git a/server/sonar-webserver-api/src/test/java/org/sonar/server/plugins/PluginDownloaderTest.java b/server/sonar-webserver-api/src/test/java/org/sonar/server/plugins/PluginDownloaderTest.java index c21aa93a676..d4d57ad60d0 100644 --- a/server/sonar-webserver-api/src/test/java/org/sonar/server/plugins/PluginDownloaderTest.java +++ b/server/sonar-webserver-api/src/test/java/org/sonar/server/plugins/PluginDownloaderTest.java @@ -26,7 +26,6 @@ import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.mockito.ArgumentMatcher; import org.mockito.invocation.InvocationOnMock; @@ -45,6 +44,7 @@ import static org.apache.commons.io.FileUtils.copyFileToDirectory; import static org.apache.commons.io.FileUtils.touch; import static org.apache.commons.io.FilenameUtils.separatorsToUnix; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; @@ -61,8 +61,6 @@ public class PluginDownloaderTest { @Rule public TemporaryFolder testFolder = new TemporaryFolder(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private File downloadDir; private UpdateCenterMatrixFactory updateCenterMatrixFactory; private UpdateCenter updateCenter; @@ -178,9 +176,8 @@ public class PluginDownloaderTest { @Test public void fail_if_no_compatible_plugin_found() { - expectedException.expect(BadRequestException.class); - - pluginDownloader.download("foo", create("1.0")); + assertThatThrownBy(() -> pluginDownloader.download("foo", create("1.0"))) + .isInstanceOf(BadRequestException.class); } @Test diff --git a/server/sonar-webserver-api/src/test/java/org/sonar/server/plugins/PluginJarLoaderTest.java b/server/sonar-webserver-api/src/test/java/org/sonar/server/plugins/PluginJarLoaderTest.java index 80686c8c23a..0c18988aa70 100644 --- a/server/sonar-webserver-api/src/test/java/org/sonar/server/plugins/PluginJarLoaderTest.java +++ b/server/sonar-webserver-api/src/test/java/org/sonar/server/plugins/PluginJarLoaderTest.java @@ -34,7 +34,6 @@ import org.apache.commons.io.FileUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.sonar.api.SonarRuntime; import org.sonar.api.utils.MessageException; @@ -45,12 +44,11 @@ import org.sonar.updatecenter.common.PluginManifest; import static java.util.jar.Attributes.Name.MANIFEST_VERSION; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class PluginJarLoaderTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public TemporaryFolder temp = new TemporaryFolder(); @Rule @@ -212,10 +210,11 @@ public class PluginJarLoaderTest { createJar(fs.getInstalledBundledPluginsDir(), "plugin1", "main", null); String dir = getDirName(fs.getInstalledExternalPluginsDir()); - expectedException.expectMessage("Found a plugin 'plugin1' in the directory '" + dir + "' with the same key [plugin1] as a built-in feature 'plugin1'. " - + "Please remove '" + new File(dir, jar.getName()) + "'"); - expectedException.expect(MessageException.class); - underTest.loadPlugins(); + + assertThatThrownBy(() -> underTest.loadPlugins()) + .isInstanceOf(MessageException.class) + .hasMessageContaining("Found a plugin 'plugin1' in the directory '" + dir + "' with the same key [plugin1] as a built-in feature 'plugin1'. " + + "Please remove '" + new File(dir, jar.getName()) + "'"); } @Test @@ -223,10 +222,11 @@ public class PluginJarLoaderTest { File downloaded = createJar(fs.getDownloadedPluginsDir(), "plugin1", "main", null); createJar(fs.getInstalledBundledPluginsDir(), "plugin1", "main", null); String dir = getDirName(fs.getDownloadedPluginsDir()); - expectedException.expectMessage("Fail to update plugin: plugin1. Built-in feature with same key already exists: plugin1. " - + "Move or delete plugin from " + dir + " directory"); - expectedException.expect(MessageException.class); - underTest.loadPlugins(); + + assertThatThrownBy(() -> underTest.loadPlugins()) + .isInstanceOf(MessageException.class) + .hasMessage("Fail to update plugin: plugin1. Built-in feature with same key already exists: plugin1. " + + "Move or delete plugin from " + dir + " directory"); } @Test @@ -235,11 +235,12 @@ public class PluginJarLoaderTest { File jar2 = createJar(fs.getInstalledExternalPluginsDir(), "plugin1", "main", null); String dir = getDirName(fs.getInstalledExternalPluginsDir()); - expectedException.expectMessage("Found two versions of the plugin 'plugin1' [plugin1] in the directory '" + dir + "'. Please remove "); - expectedException.expectMessage(jar2.getName()); - expectedException.expectMessage(jar1.getName()); - expectedException.expect(MessageException.class); - underTest.loadPlugins(); + + assertThatThrownBy(() -> underTest.loadPlugins()) + .isInstanceOf(MessageException.class) + .hasMessageContaining("Found two versions of the plugin 'plugin1' [plugin1] in the directory '" + dir + "'. Please remove ") + .hasMessageContaining(jar2.getName()) + .hasMessageContaining(jar1.getName()); } @Test @@ -247,20 +248,21 @@ public class PluginJarLoaderTest { File jar1 = createJar(fs.getInstalledBundledPluginsDir(), "plugin1", "main", null); File jar2 = createJar(fs.getInstalledBundledPluginsDir(), "plugin1", "main", null); String dir = getDirName(fs.getInstalledBundledPluginsDir()); - expectedException.expectMessage("Found two versions of the plugin plugin1 [plugin1] in the directory " + dir + ". Please remove one of "); - expectedException.expectMessage(jar1.getName()); - expectedException.expectMessage(jar2.getName()); - expectedException.expect(MessageException.class); - underTest.loadPlugins(); + + assertThatThrownBy(() -> underTest.loadPlugins()) + .isInstanceOf(MessageException.class) + .hasMessageContaining("Found two versions of the plugin plugin1 [plugin1] in the directory " + dir + ". Please remove one of ") + .hasMessageContaining(jar2.getName()) + .hasMessageContaining(jar1.getName()); } @Test public void fail_when_sqale_plugin_is_installed() throws Exception { copyTestPluginTo("fake-sqale-plugin", fs.getInstalledExternalPluginsDir()); - expectedException.expect(MessageException.class); - expectedException.expectMessage("The following plugin is no longer compatible with this version of SonarQube: 'sqale'"); - underTest.loadPlugins(); + assertThatThrownBy(() -> underTest.loadPlugins()) + .isInstanceOf(MessageException.class) + .hasMessage("The following plugin is no longer compatible with this version of SonarQube: 'sqale'"); } @Test @@ -269,27 +271,27 @@ public class PluginJarLoaderTest { createJar(fs.getInstalledExternalPluginsDir(), "scmgit", "main", null); createJar(fs.getInstalledExternalPluginsDir(), "scmsvn", "main", null); - expectedException.expect(MessageException.class); - expectedException.expectMessage("The following plugins are no longer compatible with this version of SonarQube: 'scmgit', 'scmsvn', 'sqale'"); - underTest.loadPlugins(); + assertThatThrownBy(() -> underTest.loadPlugins()) + .isInstanceOf(MessageException.class) + .hasMessage("The following plugins are no longer compatible with this version of SonarQube: 'scmgit', 'scmsvn', 'sqale'"); } @Test public void fail_when_report_is_installed() throws Exception { copyTestPluginTo("fake-report-plugin", fs.getInstalledExternalPluginsDir()); - expectedException.expect(MessageException.class); - expectedException.expectMessage("The following plugin is no longer compatible with this version of SonarQube: 'report'"); - underTest.loadPlugins(); + assertThatThrownBy(() -> underTest.loadPlugins()) + .isInstanceOf(MessageException.class) + .hasMessage("The following plugin is no longer compatible with this version of SonarQube: 'report'"); } @Test public void fail_when_views_is_installed() throws Exception { copyTestPluginTo("fake-views-plugin", fs.getInstalledExternalPluginsDir()); - expectedException.expect(MessageException.class); - expectedException.expectMessage("The following plugin is no longer compatible with this version of SonarQube: 'views'"); - underTest.loadPlugins(); + assertThatThrownBy(() -> underTest.loadPlugins()) + .isInstanceOf(MessageException.class) + .hasMessage("The following plugin is no longer compatible with this version of SonarQube: 'views'"); } @Test @@ -297,8 +299,8 @@ public class PluginJarLoaderTest { when(runtime.getApiVersion()).thenReturn(org.sonar.api.utils.Version.parse("1.0")); copyTestPluginTo("test-base-plugin", fs.getInstalledExternalPluginsDir()); - expectedException.expectMessage("Plugin Base Plugin [testbase] requires at least SonarQube 4.5.4"); - underTest.loadPlugins(); + assertThatThrownBy(() -> underTest.loadPlugins()) + .hasMessage("Plugin Base Plugin [testbase] requires at least SonarQube 4.5.4"); } private static File copyTestPluginTo(String testPluginName, File toDir) throws IOException { diff --git a/server/sonar-webserver-api/src/test/java/org/sonar/server/plugins/PluginUninstallerTest.java b/server/sonar-webserver-api/src/test/java/org/sonar/server/plugins/PluginUninstallerTest.java index 16e98ecdde8..7569e129509 100644 --- a/server/sonar-webserver-api/src/test/java/org/sonar/server/plugins/PluginUninstallerTest.java +++ b/server/sonar-webserver-api/src/test/java/org/sonar/server/plugins/PluginUninstallerTest.java @@ -28,7 +28,6 @@ import org.apache.commons.io.FileUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.sonar.api.Plugin; import org.sonar.api.utils.log.LogTester; @@ -47,8 +46,6 @@ public class PluginUninstallerTest { @Rule public TemporaryFolder testFolder = new TemporaryFolder(); @Rule - public ExpectedException exception = ExpectedException.none(); - @Rule public LogTester logs = new LogTester(); private File uninstallDir; diff --git a/server/sonar-webserver-api/src/test/java/org/sonar/server/plugins/ServerPluginRepositoryTest.java b/server/sonar-webserver-api/src/test/java/org/sonar/server/plugins/ServerPluginRepositoryTest.java index 2eebec65185..461c5d9f255 100644 --- a/server/sonar-webserver-api/src/test/java/org/sonar/server/plugins/ServerPluginRepositoryTest.java +++ b/server/sonar-webserver-api/src/test/java/org/sonar/server/plugins/ServerPluginRepositoryTest.java @@ -22,8 +22,6 @@ package org.sonar.server.plugins; import java.util.Arrays; import java.util.Collection; import java.util.Collections; -import java.util.stream.Collectors; - import org.junit.Assert; import org.junit.Test; import org.sonar.api.Plugin; diff --git a/server/sonar-webserver-api/src/test/java/org/sonar/server/plugins/TestProjectUtils.java b/server/sonar-webserver-api/src/test/java/org/sonar/server/plugins/TestProjectUtils.java index a9ace6379b0..8e1a7de9122 100644 --- a/server/sonar-webserver-api/src/test/java/org/sonar/server/plugins/TestProjectUtils.java +++ b/server/sonar-webserver-api/src/test/java/org/sonar/server/plugins/TestProjectUtils.java @@ -19,10 +19,9 @@ */ package org.sonar.server.plugins; -import org.apache.commons.io.FileUtils; - import java.io.File; import java.util.Collection; +import org.apache.commons.io.FileUtils; public class TestProjectUtils { diff --git a/server/sonar-webserver-api/src/test/java/org/sonar/server/plugins/UpdateCenterServlet.java b/server/sonar-webserver-api/src/test/java/org/sonar/server/plugins/UpdateCenterServlet.java index 9b831ac5a6d..5480fe0eff1 100644 --- a/server/sonar-webserver-api/src/test/java/org/sonar/server/plugins/UpdateCenterServlet.java +++ b/server/sonar-webserver-api/src/test/java/org/sonar/server/plugins/UpdateCenterServlet.java @@ -19,12 +19,12 @@ */ package org.sonar.server.plugins; +import java.io.IOException; +import java.util.Properties; import javax.servlet.GenericServlet; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; -import java.io.IOException; -import java.util.Properties; public class UpdateCenterServlet extends GenericServlet { diff --git a/server/sonar-webserver-api/src/test/java/org/sonar/server/plugins/edition/EditionBundledPluginsTest.java b/server/sonar-webserver-api/src/test/java/org/sonar/server/plugins/edition/EditionBundledPluginsTest.java index cc889cb76e7..1bb46ed6e30 100644 --- a/server/sonar-webserver-api/src/test/java/org/sonar/server/plugins/edition/EditionBundledPluginsTest.java +++ b/server/sonar-webserver-api/src/test/java/org/sonar/server/plugins/edition/EditionBundledPluginsTest.java @@ -20,26 +20,22 @@ package org.sonar.server.plugins.edition; import java.util.Random; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.core.platform.PluginInfo; import org.sonar.updatecenter.common.Plugin; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class EditionBundledPluginsTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private final Random random = new Random(); @Test public void isEditionBundled_on_Plugin_fails_with_NPE_if_arg_is_null() { - expectedException.expect(NullPointerException.class); - - EditionBundledPlugins.isEditionBundled((Plugin) null); + assertThatThrownBy(() -> EditionBundledPlugins.isEditionBundled((Plugin) null)) + .isInstanceOf(NullPointerException.class); } @Test @@ -79,9 +75,8 @@ public class EditionBundledPluginsTest { @Test public void isEditionBundled_on_PluginInfo_fails_with_NPE_if_arg_is_null() { - expectedException.expect(NullPointerException.class); - - EditionBundledPlugins.isEditionBundled((PluginInfo) null); + assertThatThrownBy(() -> EditionBundledPlugins.isEditionBundled((PluginInfo) null)) + .isInstanceOf(NullPointerException.class); } @Test diff --git a/server/sonar-webserver-api/src/test/java/org/sonar/server/project/ProjectLifeCycleListenersImplTest.java b/server/sonar-webserver-api/src/test/java/org/sonar/server/project/ProjectLifeCycleListenersImplTest.java index d2bf33214c6..74007de52ff 100644 --- a/server/sonar-webserver-api/src/test/java/org/sonar/server/project/ProjectLifeCycleListenersImplTest.java +++ b/server/sonar-webserver-api/src/test/java/org/sonar/server/project/ProjectLifeCycleListenersImplTest.java @@ -26,9 +26,7 @@ import java.util.Collections; import java.util.Random; import java.util.Set; import java.util.stream.IntStream; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.InOrder; import org.mockito.Mockito; @@ -41,11 +39,10 @@ import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyNoInteractions; import static org.sonar.db.component.ComponentTesting.newPrivateProjectDto; +import static org.assertj.core.api.Assertions.assertThatThrownBy; @RunWith(DataProviderRunner.class) public class ProjectLifeCycleListenersImplTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private final ProjectLifeCycleListener listener1 = mock(ProjectLifeCycleListener.class); private final ProjectLifeCycleListener listener2 = mock(ProjectLifeCycleListener.class); @@ -56,18 +53,16 @@ public class ProjectLifeCycleListenersImplTest { @Test public void onProjectsDeleted_throws_NPE_if_set_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("projects can't be null"); - - underTestWithListeners.onProjectsDeleted(null); + assertThatThrownBy(() -> underTestWithListeners.onProjectsDeleted(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("projects can't be null"); } @Test public void onProjectsDeleted_throws_NPE_if_set_is_null_even_if_no_listeners() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("projects can't be null"); - - underTestNoListeners.onProjectsDeleted(null); + assertThatThrownBy(() -> underTestNoListeners.onProjectsDeleted(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("projects can't be null"); } @Test @@ -131,18 +126,16 @@ public class ProjectLifeCycleListenersImplTest { @Test public void onProjectBranchesDeleted_throws_NPE_if_set_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("projects can't be null"); - - underTestWithListeners.onProjectBranchesDeleted(null); + assertThatThrownBy(() -> underTestWithListeners.onProjectBranchesDeleted(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("projects can't be null"); } @Test public void onProjectBranchesDeleted_throws_NPE_if_set_is_null_even_if_no_listeners() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("projects can't be null"); - - underTestNoListeners.onProjectBranchesDeleted(null); + assertThatThrownBy(() -> underTestNoListeners.onProjectBranchesDeleted(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("projects can't be null"); } @Test @@ -215,18 +208,16 @@ public class ProjectLifeCycleListenersImplTest { @Test public void onProjectsRekeyed_throws_NPE_if_set_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("rekeyedProjects can't be null"); - - underTestWithListeners.onProjectsRekeyed(null); + assertThatThrownBy(() -> underTestWithListeners.onProjectsRekeyed(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("rekeyedProjects can't be null"); } @Test public void onProjectsRekeyed_throws_NPE_if_set_is_null_even_if_no_listeners() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("rekeyedProjects can't be null"); - - underTestNoListeners.onProjectsRekeyed(null); + assertThatThrownBy(() -> underTestNoListeners.onProjectsRekeyed(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("rekeyedProjects can't be null"); } @Test diff --git a/server/sonar-webserver-api/src/test/java/org/sonar/server/project/RekeyedProjectTest.java b/server/sonar-webserver-api/src/test/java/org/sonar/server/project/RekeyedProjectTest.java index 46578707c4a..e743cfc5ec6 100644 --- a/server/sonar-webserver-api/src/test/java/org/sonar/server/project/RekeyedProjectTest.java +++ b/server/sonar-webserver-api/src/test/java/org/sonar/server/project/RekeyedProjectTest.java @@ -19,33 +19,28 @@ */ package org.sonar.server.project; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static java.util.Collections.emptyList; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.db.component.ComponentTesting.newPrivateProjectDto; public class RekeyedProjectTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void constructor_throws_NPE_if_project_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("project can't be null"); - - new RekeyedProject(null, randomAlphanumeric(3)); + assertThatThrownBy(() -> new RekeyedProject(null, randomAlphanumeric(3))) + .isInstanceOf(NullPointerException.class) + .hasMessage("project can't be null"); } @Test public void constructor_throws_NPE_if_previousKey_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("previousKey can't be null"); - - new RekeyedProject(newRandomProject(), null); + assertThatThrownBy(() -> new RekeyedProject(newRandomProject(), null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("previousKey can't be null"); } @Test diff --git a/server/sonar-webserver-api/src/test/java/org/sonar/server/qualitygate/changeevent/QGChangeEventTest.java b/server/sonar-webserver-api/src/test/java/org/sonar/server/qualitygate/changeevent/QGChangeEventTest.java index 754f7f0e5e9..289352be624 100644 --- a/server/sonar-webserver-api/src/test/java/org/sonar/server/qualitygate/changeevent/QGChangeEventTest.java +++ b/server/sonar-webserver-api/src/test/java/org/sonar/server/qualitygate/changeevent/QGChangeEventTest.java @@ -22,9 +22,7 @@ package org.sonar.server.qualitygate.changeevent; import java.util.Optional; import java.util.Random; import java.util.function.Supplier; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.Mockito; import org.sonar.api.config.Configuration; import org.sonar.api.measures.Metric; @@ -35,10 +33,9 @@ import org.sonar.db.project.ProjectDto; import org.sonar.server.qualitygate.EvaluatedQualityGate; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class QGChangeEventTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private ProjectDto project = new ProjectDto() .setKey("foo") @@ -57,34 +54,30 @@ public class QGChangeEventTest { @Test public void constructor_fails_with_NPE_if_project_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("project can't be null"); - - new QGChangeEvent(null, branch, analysis, configuration, previousStatus, supplier); + assertThatThrownBy(() -> new QGChangeEvent(null, branch, analysis, configuration, previousStatus, supplier)) + .isInstanceOf(NullPointerException.class) + .hasMessage("project can't be null"); } @Test public void constructor_fails_with_NPE_if_branch_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("branch can't be null"); - - new QGChangeEvent(project, null, analysis, configuration, previousStatus, supplier); + assertThatThrownBy(() -> new QGChangeEvent(project, null, analysis, configuration, previousStatus, supplier)) + .isInstanceOf(NullPointerException.class) + .hasMessage("branch can't be null"); } @Test public void constructor_fails_with_NPE_if_analysis_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("analysis can't be null"); - - new QGChangeEvent(project, branch, null, configuration, previousStatus, supplier); + assertThatThrownBy(() -> new QGChangeEvent(project, branch, null, configuration, previousStatus, supplier)) + .isInstanceOf(NullPointerException.class) + .hasMessage("analysis can't be null"); } @Test public void constructor_fails_with_NPE_if_configuration_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("projectConfiguration can't be null"); - - new QGChangeEvent(project, branch, analysis, null, previousStatus, supplier); + assertThatThrownBy(() -> new QGChangeEvent(project, branch, analysis, null, previousStatus, supplier)) + .isInstanceOf(NullPointerException.class) + .hasMessage("projectConfiguration can't be null"); } @Test @@ -94,10 +87,9 @@ public class QGChangeEventTest { @Test public void constructor_fails_with_NPE_if_supplier_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("qualityGateSupplier can't be null"); - - new QGChangeEvent(project, branch, analysis, configuration, previousStatus, null); + assertThatThrownBy(() -> new QGChangeEvent(project, branch, analysis, configuration, previousStatus, null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("qualityGateSupplier can't be null"); } @Test diff --git a/server/sonar-webserver-api/src/test/java/org/sonar/server/util/BooleanTypeValidationTest.java b/server/sonar-webserver-api/src/test/java/org/sonar/server/util/BooleanTypeValidationTest.java index 5a679dd8ed0..e2d7a340ece 100644 --- a/server/sonar-webserver-api/src/test/java/org/sonar/server/util/BooleanTypeValidationTest.java +++ b/server/sonar-webserver-api/src/test/java/org/sonar/server/util/BooleanTypeValidationTest.java @@ -19,18 +19,13 @@ */ package org.sonar.server.util; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.server.exceptions.BadRequestException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class BooleanTypeValidationTest { - - @Rule - public ExpectedException expectedException = ExpectedException.none(); - private BooleanTypeValidation underTest = new BooleanTypeValidation(); @Test @@ -48,10 +43,9 @@ public class BooleanTypeValidationTest { @Test public void fail_on_invalid_boolean() { - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Value 'abc' must be one of \"true\" or \"false\"."); - - underTest.validate("abc", null); + assertThatThrownBy(() -> underTest.validate("abc", null)) + .isInstanceOf(BadRequestException.class) + .hasMessage("Value 'abc' must be one of \"true\" or \"false\"."); } } diff --git a/server/sonar-webserver-api/src/test/java/org/sonar/server/util/FloatTypeValidationTest.java b/server/sonar-webserver-api/src/test/java/org/sonar/server/util/FloatTypeValidationTest.java index e82a86d1479..cc3b8c54d45 100644 --- a/server/sonar-webserver-api/src/test/java/org/sonar/server/util/FloatTypeValidationTest.java +++ b/server/sonar-webserver-api/src/test/java/org/sonar/server/util/FloatTypeValidationTest.java @@ -19,18 +19,13 @@ */ package org.sonar.server.util; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.server.exceptions.BadRequestException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class FloatTypeValidationTest { - - @Rule - public ExpectedException expectedException = ExpectedException.none(); - private FloatTypeValidation validation = new FloatTypeValidation(); @Test @@ -47,10 +42,9 @@ public class FloatTypeValidationTest { @Test public void fail_on_invalid_float() { - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Value 'abc' must be an floating point number."); - - validation.validate("abc", null); + assertThatThrownBy(() -> validation.validate("abc", null)) + .isInstanceOf(BadRequestException.class) + .hasMessage("Value 'abc' must be an floating point number."); } } diff --git a/server/sonar-webserver-api/src/test/java/org/sonar/server/util/GlobalLockManagerImplTest.java b/server/sonar-webserver-api/src/test/java/org/sonar/server/util/GlobalLockManagerImplTest.java index 5312e2c0ba0..03b6e779c45 100644 --- a/server/sonar-webserver-api/src/test/java/org/sonar/server/util/GlobalLockManagerImplTest.java +++ b/server/sonar-webserver-api/src/test/java/org/sonar/server/util/GlobalLockManagerImplTest.java @@ -24,10 +24,9 @@ import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.Random; import org.apache.commons.lang.RandomStringUtils; +import org.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.db.DbClient; import org.sonar.db.DbSession; @@ -35,6 +34,7 @@ import org.sonar.db.property.InternalPropertiesDao; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; @@ -45,10 +45,6 @@ import static org.sonar.server.util.GlobalLockManager.DEFAULT_LOCK_DURATION_SECO public class GlobalLockManagerImplTest { private static final int LOCK_NAME_MAX_LENGTH = 15; - - @Rule - public ExpectedException expectedException = ExpectedException.none(); - private final DbClient dbClient = mock(DbClient.class); private final InternalPropertiesDao internalPropertiesDao = mock(InternalPropertiesDao.class); private final DbSession dbSession = mock(DbSession.class); @@ -64,18 +60,14 @@ public class GlobalLockManagerImplTest { public void tryLock_fails_with_IAE_if_name_is_empty() { String badLockName = ""; - expectBadLockNameIAE(badLockName); - - underTest.tryLock(badLockName); + expectBadLockNameIAE(() -> underTest.tryLock(badLockName), badLockName); } @Test public void tryLock_fails_with_IAE_if_name_length_is_16_or_more() { String badLockName = RandomStringUtils.random(LOCK_NAME_MAX_LENGTH + 1 + new Random().nextInt(96)); - expectBadLockNameIAE(badLockName); - - underTest.tryLock(badLockName); + expectBadLockNameIAE(() -> underTest.tryLock(badLockName), badLockName); } @Test @@ -105,9 +97,7 @@ public class GlobalLockManagerImplTest { public void tryLock_with_duration_fails_with_IAE_if_name_is_empty(int randomValidDuration) { String badLockName = ""; - expectBadLockNameIAE(badLockName); - - underTest.tryLock(badLockName, randomValidDuration); + expectBadLockNameIAE(() -> underTest.tryLock(badLockName, randomValidDuration), badLockName); } @Test @@ -123,17 +113,13 @@ public class GlobalLockManagerImplTest { public void tryLock_with_duration_fails_with_IAE_if_name_length_is_16_or_more(int randomValidDuration) { String badLockName = RandomStringUtils.random(LOCK_NAME_MAX_LENGTH + 1 + new Random().nextInt(65)); - expectBadLockNameIAE(badLockName); - - underTest.tryLock(badLockName, randomValidDuration); + expectBadLockNameIAE(() -> underTest.tryLock(badLockName, randomValidDuration), badLockName); } @Test @UseDataProvider("randomValidLockName") public void tryLock_with_duration_fails_with_IAE_if_duration_is_0(String randomValidLockName) { - expectBadDuration(0); - - underTest.tryLock(randomValidLockName, 0); + expectBadDuration(() -> underTest.tryLock(randomValidLockName, 0),0); } @Test @@ -141,9 +127,7 @@ public class GlobalLockManagerImplTest { public void tryLock_with_duration_fails_with_IAE_if_duration_is_less_than_0(String randomValidLockName) { int negativeDuration = -1 - new Random().nextInt(100); - expectBadDuration(negativeDuration); - - underTest.tryLock(randomValidLockName, negativeDuration); + expectBadDuration(() -> underTest.tryLock(randomValidLockName, negativeDuration), negativeDuration); } @Test @@ -176,14 +160,16 @@ public class GlobalLockManagerImplTest { }; } - private void expectBadLockNameIAE(String badLockName) { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("name's length must be > 0 and <= " + LOCK_NAME_MAX_LENGTH + ": '" + badLockName + "'"); + private void expectBadLockNameIAE(ThrowingCallable callback, String badLockName) { + assertThatThrownBy(callback) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("name's length must be > 0 and <= " + LOCK_NAME_MAX_LENGTH + ": '" + badLockName + "'"); } - private void expectBadDuration(int badDuration) { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("duration must be > 0: " + badDuration); + private void expectBadDuration(ThrowingCallable callback, int badDuration) { + assertThatThrownBy(callback) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("duration must be > 0: " + badDuration); } } diff --git a/server/sonar-webserver-api/src/test/java/org/sonar/server/util/IntegerTypeValidationTest.java b/server/sonar-webserver-api/src/test/java/org/sonar/server/util/IntegerTypeValidationTest.java index 773f33f4c55..1044ea2288c 100644 --- a/server/sonar-webserver-api/src/test/java/org/sonar/server/util/IntegerTypeValidationTest.java +++ b/server/sonar-webserver-api/src/test/java/org/sonar/server/util/IntegerTypeValidationTest.java @@ -19,18 +19,13 @@ */ package org.sonar.server.util; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.server.exceptions.BadRequestException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class IntegerTypeValidationTest { - - @Rule - public ExpectedException expectedException = ExpectedException.none(); - private IntegerTypeValidation validation = new IntegerTypeValidation(); @Test @@ -46,18 +41,17 @@ public class IntegerTypeValidationTest { @Test public void fail_on_string() { - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Value 'abc' must be an integer."); - - validation.validate("abc", null); + assertThatThrownBy(() -> validation.validate("abc", null)) + .isInstanceOf(BadRequestException.class) + .hasMessage("Value 'abc' must be an integer."); } @Test public void fail_on_float() { - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Value '10.1' must be an integer."); - validation.validate("10.1", null); + assertThatThrownBy(() -> validation.validate("10.1", null)) + .isInstanceOf(BadRequestException.class) + .hasMessage("Value '10.1' must be an integer."); } } diff --git a/server/sonar-webserver-api/src/test/java/org/sonar/server/util/LongTypeValidationTest.java b/server/sonar-webserver-api/src/test/java/org/sonar/server/util/LongTypeValidationTest.java index d06a7918f7f..8c142509a78 100644 --- a/server/sonar-webserver-api/src/test/java/org/sonar/server/util/LongTypeValidationTest.java +++ b/server/sonar-webserver-api/src/test/java/org/sonar/server/util/LongTypeValidationTest.java @@ -19,19 +19,16 @@ */ package org.sonar.server.util; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.PropertyType; import org.sonar.server.exceptions.BadRequestException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class LongTypeValidationTest { LongTypeValidation underTest = new LongTypeValidation(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void key_is_long_type_name() { @@ -46,17 +43,15 @@ public class LongTypeValidationTest { @Test public void fail_when_float() { - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Value '3.14' must be a long."); - - underTest.validate("3.14", null); + assertThatThrownBy(() -> underTest.validate("3.14", null)) + .isInstanceOf(BadRequestException.class) + .hasMessage("Value '3.14' must be a long."); } @Test public void fail_when_string() { - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Value 'original string' must be a long."); - - underTest.validate("original string", null); + assertThatThrownBy(() -> underTest.validate("original string", null)) + .isInstanceOf(BadRequestException.class) + .hasMessage("Value 'original string' must be a long."); } } diff --git a/server/sonar-webserver-api/src/test/java/org/sonar/server/util/StringListTypeValidationTest.java b/server/sonar-webserver-api/src/test/java/org/sonar/server/util/StringListTypeValidationTest.java index 91f1fbd998f..cf98f9d4dca 100644 --- a/server/sonar-webserver-api/src/test/java/org/sonar/server/util/StringListTypeValidationTest.java +++ b/server/sonar-webserver-api/src/test/java/org/sonar/server/util/StringListTypeValidationTest.java @@ -19,19 +19,14 @@ */ package org.sonar.server.util; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.server.exceptions.BadRequestException; import static com.google.common.collect.Lists.newArrayList; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class StringListTypeValidationTest { - - @Rule - public ExpectedException expectedException = ExpectedException.none(); - private StringListTypeValidation validation = new StringListTypeValidation(); @Test @@ -47,10 +42,9 @@ public class StringListTypeValidationTest { @Test public void fail_on_invalid_option() { - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Value 'abc' must be one of : a, b, c."); - - validation.validate("abc", newArrayList("a", "b", "c")); + assertThatThrownBy(() -> validation.validate("abc", newArrayList("a", "b", "c"))) + .isInstanceOf(BadRequestException.class) + .hasMessage("Value 'abc' must be one of : a, b, c."); } } diff --git a/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/BasicAuthenticationTest.java b/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/BasicAuthenticationTest.java index 6a7542314ed..d5c8d769c96 100644 --- a/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/BasicAuthenticationTest.java +++ b/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/BasicAuthenticationTest.java @@ -24,28 +24,26 @@ import java.util.Optional; import javax.servlet.http.HttpServletRequest; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.utils.System2; import org.sonar.db.DbClient; import org.sonar.db.DbTester; import org.sonar.db.user.UserDto; import org.sonar.db.user.UserTesting; import org.sonar.server.authentication.event.AuthenticationEvent; +import org.sonar.server.authentication.event.AuthenticationException; import org.sonar.server.usertoken.UserTokenAuthentication; import static java.nio.charset.StandardCharsets.UTF_8; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.rules.ExpectedException.none; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; -import static org.sonar.server.authentication.event.AuthenticationEvent.Method; import static org.sonar.server.authentication.event.AuthenticationEvent.Method.BASIC; import static org.sonar.server.authentication.event.AuthenticationEvent.Method.BASIC_TOKEN; import static org.sonar.server.authentication.event.AuthenticationEvent.Source; -import static org.sonar.server.authentication.event.AuthenticationExceptionMatcher.authenticationException; public class BasicAuthenticationTest { @@ -57,8 +55,6 @@ public class BasicAuthenticationTest { private static final UserDto USER = UserTesting.newUserDto().setLogin(A_LOGIN); - @Rule - public ExpectedException expectedException = none(); @Rule public DbTester db = DbTester.create(System2.INSTANCE); @@ -118,21 +114,21 @@ public class BasicAuthenticationTest { public void fail_to_authenticate_when_no_login() { when(request.getHeader("Authorization")).thenReturn("Basic " + toBase64(":" + A_PASSWORD)); - expectedException.expect(authenticationException().from(Source.local(BASIC)).withoutLogin().andNoPublicMessage()); - try { - underTest.authenticate(request); - } finally { - verifyZeroInteractions(authenticationEvent); - } + assertThatThrownBy(() -> underTest.authenticate(request)) + .isInstanceOf(AuthenticationException.class) + .hasFieldOrPropertyWithValue("source", Source.local(BASIC)); + + verifyZeroInteractions(authenticationEvent); } @Test public void fail_to_authenticate_when_invalid_header() { when(request.getHeader("Authorization")).thenReturn("Basic Invàlid"); - expectedException.expect(authenticationException().from(Source.local(BASIC)).withoutLogin().andNoPublicMessage()); - expectedException.expectMessage("Invalid basic header"); - underTest.authenticate(request); + assertThatThrownBy(() -> underTest.authenticate(request)) + .hasMessage("Invalid basic header") + .isInstanceOf(AuthenticationException.class) + .hasFieldOrPropertyWithValue("source", Source.local(BASIC)); } @Test @@ -153,12 +149,12 @@ public class BasicAuthenticationTest { when(userTokenAuthentication.authenticate("token")).thenReturn(Optional.empty()); when(request.getHeader("Authorization")).thenReturn("Basic " + toBase64("token:")); - expectedException.expect(authenticationException().from(Source.local(BASIC_TOKEN)).withoutLogin().andNoPublicMessage()); - try { - underTest.authenticate(request); - } finally { - verifyZeroInteractions(authenticationEvent); - } + assertThatThrownBy(() -> underTest.authenticate(request)) + .hasMessage("Token doesn't exist") + .isInstanceOf(AuthenticationException.class) + .hasFieldOrPropertyWithValue("source", Source.local(BASIC_TOKEN)); + + verifyZeroInteractions(authenticationEvent); } @Test @@ -166,12 +162,12 @@ public class BasicAuthenticationTest { when(userTokenAuthentication.authenticate("token")).thenReturn(Optional.of("Unknown user")); when(request.getHeader("Authorization")).thenReturn("Basic " + toBase64("token:")); - expectedException.expect(authenticationException().from(Source.local(Method.BASIC_TOKEN)).withoutLogin().andNoPublicMessage()); - try { - underTest.authenticate(request); - } finally { - verifyZeroInteractions(authenticationEvent); - } + assertThatThrownBy(() -> underTest.authenticate(request)) + .hasMessageContaining("User doesn't exist") + .isInstanceOf(AuthenticationException.class) + .hasFieldOrPropertyWithValue("source", Source.local(BASIC_TOKEN)); + + verifyZeroInteractions(authenticationEvent); } @Test @@ -180,12 +176,12 @@ public class BasicAuthenticationTest { when(userTokenAuthentication.authenticate("token")).thenReturn(Optional.of(user.getUuid())); when(request.getHeader("Authorization")).thenReturn("Basic " + toBase64("token:")); - expectedException.expect(authenticationException().from(Source.local(Method.BASIC_TOKEN)).withoutLogin().andNoPublicMessage()); - try { - underTest.authenticate(request); - } finally { - verifyZeroInteractions(authenticationEvent); - } + assertThatThrownBy(() -> underTest.authenticate(request)) + .hasMessageContaining("User doesn't exist") + .isInstanceOf(AuthenticationException.class) + .hasFieldOrPropertyWithValue("source", Source.local(BASIC_TOKEN)); + + verifyZeroInteractions(authenticationEvent); } private static String toBase64(String text) { diff --git a/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/CookiesTest.java b/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/CookiesTest.java index bb1be0f0062..7b3df93b3df 100644 --- a/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/CookiesTest.java +++ b/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/CookiesTest.java @@ -21,11 +21,10 @@ package org.sonar.server.authentication; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.server.authentication.Cookies.findCookie; @@ -35,8 +34,6 @@ public class CookiesTest { private static final String HTTPS_HEADER = "X-Forwarded-Proto"; - @Rule - public ExpectedException expectedException = ExpectedException.none(); private HttpServletRequest request = mock(HttpServletRequest.class); @@ -108,14 +105,14 @@ public class CookiesTest { @Test public void fail_with_NPE_when_cookie_name_is_null() { - expectedException.expect(NullPointerException.class); - newCookieBuilder(request).setName(null); + assertThatThrownBy(() -> newCookieBuilder(request).setName(null)) + .isInstanceOf(NullPointerException.class); } @Test public void fail_with_NPE_when_cookie_has_no_name() { - expectedException.expect(NullPointerException.class); - newCookieBuilder(request).setName(null); + assertThatThrownBy(() -> newCookieBuilder(request).setName(null)) + .isInstanceOf(NullPointerException.class); } } diff --git a/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/CredentialsAuthenticationTest.java b/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/CredentialsAuthenticationTest.java index 7ad9affa9f0..d5e75a2ece3 100644 --- a/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/CredentialsAuthenticationTest.java +++ b/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/CredentialsAuthenticationTest.java @@ -23,7 +23,6 @@ import java.util.Optional; import javax.servlet.http.HttpServletRequest; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.utils.System2; import org.sonar.db.DbClient; @@ -31,9 +30,10 @@ import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.user.UserDto; import org.sonar.server.authentication.event.AuthenticationEvent; +import org.sonar.server.authentication.event.AuthenticationException; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.rules.ExpectedException.none; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; @@ -42,7 +42,6 @@ import static org.sonar.db.user.UserTesting.newUserDto; import static org.sonar.server.authentication.event.AuthenticationEvent.Method.BASIC; import static org.sonar.server.authentication.event.AuthenticationEvent.Method.BASIC_TOKEN; import static org.sonar.server.authentication.event.AuthenticationEvent.Source; -import static org.sonar.server.authentication.event.AuthenticationExceptionMatcher.authenticationException; public class CredentialsAuthenticationTest { @@ -51,8 +50,6 @@ public class CredentialsAuthenticationTest { private static final String SALT = "0242b0b4c0a93ddfe09dd886de50bc25ba000b51"; private static final String ENCRYPTED_PASSWORD = "540e4fc4be4e047db995bc76d18374a5b5db08cc"; - @Rule - public ExpectedException expectedException = none(); @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); private DbClient dbClient = dbTester.getDbClient(); @@ -87,13 +84,14 @@ public class CredentialsAuthenticationTest { .setHashMethod(CredentialsLocalAuthentication.HashMethod.SHA1.name()) .setLocal(true)); - expectedException.expect(authenticationException().from(Source.local(BASIC)).withLogin(LOGIN).andNoPublicMessage()); - expectedException.expectMessage("wrong password"); - try { - executeAuthenticate(BASIC); - } finally { - verifyZeroInteractions(authenticationEvent); - } + assertThatThrownBy(() -> executeAuthenticate(BASIC)) + .hasMessage("wrong password") + .isInstanceOf(AuthenticationException.class) + .hasFieldOrPropertyWithValue("source", Source.local(BASIC)) + .hasFieldOrPropertyWithValue("login", LOGIN); + + verifyZeroInteractions(authenticationEvent); + } @Test @@ -116,13 +114,13 @@ public class CredentialsAuthenticationTest { .setLogin(LOGIN) .setLocal(false)); - expectedException.expect(authenticationException().from(Source.local(BASIC_TOKEN)).withLogin(LOGIN).andNoPublicMessage()); - expectedException.expectMessage("User is not local"); - try { - executeAuthenticate(BASIC_TOKEN); - } finally { - verifyZeroInteractions(authenticationEvent); - } + assertThatThrownBy(() -> executeAuthenticate(BASIC_TOKEN)) + .hasMessage("User is not local") + .isInstanceOf(AuthenticationException.class) + .hasFieldOrPropertyWithValue("source", Source.local(BASIC_TOKEN)) + .hasFieldOrPropertyWithValue("login", LOGIN); + + verifyZeroInteractions(authenticationEvent); } @Test @@ -134,13 +132,13 @@ public class CredentialsAuthenticationTest { .setHashMethod(CredentialsLocalAuthentication.HashMethod.SHA1.name()) .setLocal(true)); - expectedException.expect(authenticationException().from(Source.local(BASIC)).withLogin(LOGIN).andNoPublicMessage()); - expectedException.expectMessage("null password in DB"); - try { - executeAuthenticate(BASIC); - } finally { - verifyZeroInteractions(authenticationEvent); - } + assertThatThrownBy(() -> executeAuthenticate(BASIC)) + .hasMessage("null password in DB") + .isInstanceOf(AuthenticationException.class) + .hasFieldOrPropertyWithValue("source", Source.local(BASIC)) + .hasFieldOrPropertyWithValue("login", LOGIN); + + verifyZeroInteractions(authenticationEvent); } @Test @@ -152,13 +150,14 @@ public class CredentialsAuthenticationTest { .setHashMethod(CredentialsLocalAuthentication.HashMethod.SHA1.name()) .setLocal(true)); - expectedException.expect(authenticationException().from(Source.local(BASIC_TOKEN)).withLogin(LOGIN).andNoPublicMessage()); - expectedException.expectMessage("null salt"); - try { - executeAuthenticate(BASIC_TOKEN); - } finally { - verifyZeroInteractions(authenticationEvent); - } + assertThatThrownBy(() -> executeAuthenticate(BASIC_TOKEN)) + .hasMessage("null salt") + .isInstanceOf(AuthenticationException.class) + .hasFieldOrPropertyWithValue("source", Source.local(BASIC_TOKEN)) + .hasFieldOrPropertyWithValue("login", LOGIN); + + verifyZeroInteractions(authenticationEvent); + } private UserDto executeAuthenticate(AuthenticationEvent.Method method) { diff --git a/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/CredentialsExternalAuthenticationTest.java b/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/CredentialsExternalAuthenticationTest.java index 61074bea768..53361950e8b 100644 --- a/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/CredentialsExternalAuthenticationTest.java +++ b/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/CredentialsExternalAuthenticationTest.java @@ -21,9 +21,7 @@ package org.sonar.server.authentication; import javax.servlet.http.HttpServletRequest; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.security.Authenticator; import org.sonar.api.security.ExternalGroupsProvider; @@ -32,11 +30,12 @@ import org.sonar.api.security.SecurityRealm; import org.sonar.api.security.UserDetails; import org.sonar.server.authentication.event.AuthenticationEvent; import org.sonar.server.authentication.event.AuthenticationEvent.Source; +import org.sonar.server.authentication.event.AuthenticationException; import org.sonar.server.user.SecurityRealmFactory; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.rules.ExpectedException.none; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; @@ -46,7 +45,6 @@ import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; import static org.sonar.server.authentication.event.AuthenticationEvent.Method.BASIC; import static org.sonar.server.authentication.event.AuthenticationEvent.Method.BASIC_TOKEN; -import static org.sonar.server.authentication.event.AuthenticationExceptionMatcher.authenticationException; public class CredentialsExternalAuthenticationTest { @@ -55,9 +53,6 @@ public class CredentialsExternalAuthenticationTest { private static final String REALM_NAME = "realm name"; - @Rule - public ExpectedException expectedException = none(); - private MapSettings settings = new MapSettings(); private SecurityRealmFactory securityRealmFactory = mock(SecurityRealmFactory.class); @@ -189,13 +184,13 @@ public class CredentialsExternalAuthenticationTest { when(externalUsersProvider.doGetUserDetails(any(ExternalUsersProvider.Context.class))).thenReturn(null); - expectedException.expect(authenticationException().from(Source.realm(BASIC, REALM_NAME)).withLogin(LOGIN).andNoPublicMessage()); - expectedException.expectMessage("No user details"); - try { - underTest.authenticate(new Credentials(LOGIN, PASSWORD), request, BASIC); - } finally { - verifyZeroInteractions(authenticationEvent); - } + assertThatThrownBy(() -> underTest.authenticate(new Credentials(LOGIN, PASSWORD), request, BASIC)) + .hasMessage("No user details") + .isInstanceOf(AuthenticationException.class) + .hasFieldOrPropertyWithValue("source", Source.realm(BASIC, REALM_NAME)) + .hasFieldOrPropertyWithValue("login", LOGIN); + + verifyZeroInteractions(authenticationEvent); } @Test @@ -205,13 +200,14 @@ public class CredentialsExternalAuthenticationTest { when(authenticator.doAuthenticate(any(Authenticator.Context.class))).thenReturn(false); - expectedException.expect(authenticationException().from(Source.realm(BASIC, REALM_NAME)).withLogin(LOGIN).andNoPublicMessage()); - expectedException.expectMessage("Realm returned authenticate=false"); - try { - underTest.authenticate(new Credentials(LOGIN, PASSWORD), request, BASIC); - } finally { - verifyZeroInteractions(authenticationEvent); - } + assertThatThrownBy(() -> underTest.authenticate(new Credentials(LOGIN, PASSWORD), request, BASIC)) + .hasMessage("Realm returned authenticate=false") + .isInstanceOf(AuthenticationException.class) + .hasFieldOrPropertyWithValue("source", Source.realm(BASIC, REALM_NAME)) + .hasFieldOrPropertyWithValue("login", LOGIN); + + verifyZeroInteractions(authenticationEvent); + } @Test @@ -222,13 +218,13 @@ public class CredentialsExternalAuthenticationTest { when(externalUsersProvider.doGetUserDetails(any(ExternalUsersProvider.Context.class))).thenReturn(new UserDetails()); - expectedException.expect(authenticationException().from(Source.realm(BASIC_TOKEN, REALM_NAME)).withLogin(LOGIN).andNoPublicMessage()); - expectedException.expectMessage(expectedMessage); - try { - underTest.authenticate(new Credentials(LOGIN, PASSWORD), request, BASIC_TOKEN); - } finally { - verifyZeroInteractions(authenticationEvent); - } + assertThatThrownBy(() -> underTest.authenticate(new Credentials(LOGIN, PASSWORD), request, BASIC_TOKEN)) + .hasMessage(expectedMessage) + .isInstanceOf(AuthenticationException.class) + .hasFieldOrPropertyWithValue("source", Source.realm(BASIC_TOKEN, REALM_NAME)) + .hasFieldOrPropertyWithValue("login", LOGIN); + + verifyZeroInteractions(authenticationEvent); } @Test @@ -242,9 +238,9 @@ public class CredentialsExternalAuthenticationTest { when(realm.doGetAuthenticator()).thenReturn(null); when(securityRealmFactory.getRealm()).thenReturn(realm); - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("No authenticator available"); - underTest.start(); + assertThatThrownBy(() -> underTest.start()) + .isInstanceOf(NullPointerException.class) + .hasMessage("No authenticator available"); } @Test @@ -253,9 +249,9 @@ public class CredentialsExternalAuthenticationTest { when(realm.getUsersProvider()).thenReturn(null); when(securityRealmFactory.getRealm()).thenReturn(realm); - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("No users provider available"); - underTest.start(); + assertThatThrownBy(() -> underTest.start()) + .isInstanceOf(NullPointerException.class) + .hasMessage("No users provider available"); } private void executeStartWithoutGroupSync() { diff --git a/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/DefaultAdminCredentialsVerifierImplTest.java b/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/DefaultAdminCredentialsVerifierImplTest.java index 5b80f1f6428..a36e86126a2 100644 --- a/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/DefaultAdminCredentialsVerifierImplTest.java +++ b/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/DefaultAdminCredentialsVerifierImplTest.java @@ -19,7 +19,6 @@ */ package org.sonar.server.authentication; -import org.junit.After; import org.junit.Rule; import org.junit.Test; import org.sonar.api.config.internal.MapSettings; diff --git a/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/HttpHeadersAuthenticationTest.java b/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/HttpHeadersAuthenticationTest.java index 85966c3c136..393c83114ee 100644 --- a/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/HttpHeadersAuthenticationTest.java +++ b/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/HttpHeadersAuthenticationTest.java @@ -30,7 +30,6 @@ import javax.servlet.http.HttpServletResponse; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.impl.utils.AlwaysIncreasingSystem2; import org.sonar.api.utils.System2; @@ -40,6 +39,7 @@ import org.sonar.db.user.GroupDto; import org.sonar.db.user.UserDto; import org.sonar.server.authentication.event.AuthenticationEvent; import org.sonar.server.authentication.event.AuthenticationEvent.Source; +import org.sonar.server.authentication.event.AuthenticationException; import org.sonar.server.es.EsTester; import org.sonar.server.user.NewUserNotifier; import org.sonar.server.user.UserUpdater; @@ -48,7 +48,7 @@ import org.sonar.server.usergroups.DefaultGroupFinder; import static java.util.Arrays.stream; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.rules.ExpectedException.none; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyMap; import static org.mockito.ArgumentMatchers.eq; @@ -58,14 +58,11 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; import static org.sonar.db.user.UserTesting.newUserDto; -import static org.sonar.server.authentication.event.AuthenticationExceptionMatcher.authenticationException; public class HttpHeadersAuthenticationTest { private final MapSettings settings = new MapSettings().setProperty("sonar.internal.pbkdf2.iterations", "1"); - @Rule - public ExpectedException expectedException = none(); @Rule public DbTester db = DbTester.create(new AlwaysIncreasingSystem2()); @Rule @@ -346,13 +343,12 @@ public class HttpHeadersAuthenticationTest { startWithSso(); setNotUserInToken(); - expectedException.expect(authenticationException().from(Source.sso()).withoutLogin().andNoPublicMessage()); - expectedException.expectMessage("Use only letters, numbers, and .-_@ please."); - try { - underTest.authenticate(createRequest("invalid login", DEFAULT_NAME, DEFAULT_EMAIL, GROUPS), response); - } finally { - verifyZeroInteractions(authenticationEvent); - } + assertThatThrownBy(() -> underTest.authenticate(createRequest("invalid login", DEFAULT_NAME, DEFAULT_EMAIL, GROUPS), response)) + .hasMessage("Use only letters, numbers, and .-_@ please.") + .isInstanceOf(AuthenticationException.class) + .hasFieldOrPropertyWithValue("source", Source.sso()); + + verifyZeroInteractions(authenticationEvent); } private void startWithSso() { diff --git a/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/IdentityProviderRepositoryTest.java b/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/IdentityProviderRepositoryTest.java index e738aeeb322..334c0a5bd63 100644 --- a/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/IdentityProviderRepositoryTest.java +++ b/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/IdentityProviderRepositoryTest.java @@ -20,18 +20,15 @@ package org.sonar.server.authentication; import java.util.List; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.authentication.IdentityProvider; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class IdentityProviderRepositoryTest { - @Rule - public ExpectedException thrown = ExpectedException.none(); static IdentityProvider GITHUB = new TestIdentityProvider() .setKey("github") @@ -60,9 +57,9 @@ public class IdentityProviderRepositoryTest { public void fail_on_disabled_provider() { IdentityProviderRepository underTest = new IdentityProviderRepository(asList(GITHUB, BITBUCKET, DISABLED)); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Identity provider disabled does not exist or is not enabled"); - underTest.getEnabledByKey(DISABLED.getKey()); + assertThatThrownBy(() -> underTest.getEnabledByKey(DISABLED.getKey())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Identity provider disabled does not exist or is not enabled"); } @Test diff --git a/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/InitFilterTest.java b/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/InitFilterTest.java index cba0e20cb44..12905ccf96a 100644 --- a/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/InitFilterTest.java +++ b/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/InitFilterTest.java @@ -26,7 +26,6 @@ import javax.servlet.http.HttpServletResponse; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; import org.sonar.api.server.authentication.BaseIdentityProvider; import org.sonar.api.server.authentication.Display; @@ -54,8 +53,6 @@ public class InitFilterTest { @Rule public LogTester logTester = new LogTester(); - @Rule - public ExpectedException thrown = ExpectedException.none(); @Rule public IdentityProviderRepositoryRule identityProviderRepository = new IdentityProviderRepositoryRule(); diff --git a/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/JwtCsrfVerifierTest.java b/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/JwtCsrfVerifierTest.java index b5200741ed3..0021ae96c4d 100644 --- a/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/JwtCsrfVerifierTest.java +++ b/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/JwtCsrfVerifierTest.java @@ -23,24 +23,20 @@ import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; +import org.sonar.server.authentication.event.AuthenticationEvent.Source; +import org.sonar.server.authentication.event.AuthenticationException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.sonar.server.authentication.event.AuthenticationEvent.Method; -import static org.sonar.server.authentication.event.AuthenticationEvent.Source; -import static org.sonar.server.authentication.event.AuthenticationExceptionMatcher.authenticationException; public class JwtCsrfVerifierTest { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private static final int TIMEOUT = 30; private static final String CSRF_STATE = "STATE"; private static final String JAVA_WS_URL = "/api/projects/create"; @@ -80,9 +76,11 @@ public class JwtCsrfVerifierTest { mockRequestCsrf("other value"); mockPostJavaWsRequest(); - thrown.expect(authenticationException().from(Source.local(Method.JWT)).withLogin(LOGIN).andNoPublicMessage()); - thrown.expectMessage("Wrong CSFR in request"); - underTest.verifyState(request, CSRF_STATE, LOGIN); + assertThatThrownBy(() -> underTest.verifyState(request, CSRF_STATE, LOGIN)) + .isInstanceOf(AuthenticationException.class) + .hasMessage("Wrong CSFR in request") + .hasFieldOrPropertyWithValue("login", LOGIN) + .hasFieldOrPropertyWithValue("source", Source.local(Method.JWT)); } @Test @@ -90,9 +88,11 @@ public class JwtCsrfVerifierTest { mockRequestCsrf(CSRF_STATE); mockPostJavaWsRequest(); - thrown.expect(authenticationException().from(Source.local(Method.JWT)).withLogin(LOGIN).andNoPublicMessage()); - thrown.expectMessage("Missing reference CSRF value"); - underTest.verifyState(request, null, LOGIN); + assertThatThrownBy(() -> underTest.verifyState(request, null, LOGIN)) + .hasMessage("Missing reference CSRF value") + .isInstanceOf(AuthenticationException.class) + .hasFieldOrPropertyWithValue("login", LOGIN) + .hasFieldOrPropertyWithValue("source", Source.local(Method.JWT)); } @Test @@ -100,9 +100,11 @@ public class JwtCsrfVerifierTest { mockRequestCsrf(CSRF_STATE); mockPostJavaWsRequest(); - thrown.expect(authenticationException().from(Source.local(Method.JWT)).withLogin(LOGIN).andNoPublicMessage()); - thrown.expectMessage("Missing reference CSRF value"); - underTest.verifyState(request, "", LOGIN); + assertThatThrownBy(() -> underTest.verifyState(request, "", LOGIN)) + .hasMessage("Missing reference CSRF value") + .isInstanceOf(AuthenticationException.class) + .hasFieldOrPropertyWithValue("login", LOGIN) + .hasFieldOrPropertyWithValue("source", Source.local(Method.JWT)); } @Test @@ -111,9 +113,11 @@ public class JwtCsrfVerifierTest { when(request.getRequestURI()).thenReturn(JAVA_WS_URL); when(request.getMethod()).thenReturn("POST"); - thrown.expect(authenticationException().from(Source.local(Method.JWT)).withLogin(LOGIN).andNoPublicMessage()); - thrown.expectMessage("Wrong CSFR in request"); - underTest.verifyState(request, CSRF_STATE, LOGIN); + assertThatThrownBy(() -> underTest.verifyState(request, CSRF_STATE, LOGIN)) + .hasMessage("Wrong CSFR in request") + .isInstanceOf(AuthenticationException.class) + .hasFieldOrPropertyWithValue("login", LOGIN) + .hasFieldOrPropertyWithValue("source", Source.local(Method.JWT)); } @Test @@ -122,9 +126,11 @@ public class JwtCsrfVerifierTest { when(request.getRequestURI()).thenReturn(JAVA_WS_URL); when(request.getMethod()).thenReturn("PUT"); - thrown.expect(authenticationException().from(Source.local(Method.JWT)).withLogin(LOGIN).andNoPublicMessage()); - thrown.expectMessage("Wrong CSFR in request"); - underTest.verifyState(request, CSRF_STATE, LOGIN); + assertThatThrownBy(() -> underTest.verifyState(request, CSRF_STATE, LOGIN)) + .hasMessage("Wrong CSFR in request") + .isInstanceOf(AuthenticationException.class) + .hasFieldOrPropertyWithValue("login", LOGIN) + .hasFieldOrPropertyWithValue("source", Source.local(Method.JWT)); } @Test @@ -133,9 +139,11 @@ public class JwtCsrfVerifierTest { when(request.getRequestURI()).thenReturn(JAVA_WS_URL); when(request.getMethod()).thenReturn("DELETE"); - thrown.expect(authenticationException().from(Source.local(Method.JWT)).withLogin(LOGIN).andNoPublicMessage()); - thrown.expectMessage("Wrong CSFR in request"); - underTest.verifyState(request, CSRF_STATE, LOGIN); + assertThatThrownBy(() -> underTest.verifyState(request, CSRF_STATE, LOGIN)) + .hasMessage("Wrong CSFR in request") + .isInstanceOf(AuthenticationException.class) + .hasFieldOrPropertyWithValue("login", LOGIN) + .hasFieldOrPropertyWithValue("source", Source.local(Method.JWT)); } @Test diff --git a/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/JwtHttpHandlerTest.java b/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/JwtHttpHandlerTest.java index ba25da81862..3e6a0bb4a73 100644 --- a/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/JwtHttpHandlerTest.java +++ b/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/JwtHttpHandlerTest.java @@ -32,7 +32,6 @@ import javax.servlet.http.HttpSession; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.utils.System2; @@ -43,6 +42,7 @@ import org.sonar.db.user.SessionTokenDto; import org.sonar.db.user.UserDto; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.entry; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; @@ -69,8 +69,6 @@ public class JwtHttpHandlerTest { private static final long IN_FIVE_MINUTES = NOW + 5 * 60 * 1000L; - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester db = DbTester.create(); @@ -156,40 +154,36 @@ public class JwtHttpHandlerTest { public void session_timeout_property_cannot_be_zero() { settings.setProperty("sonar.web.sessionTimeoutInMinutes", 0); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Property sonar.web.sessionTimeoutInMinutes must be higher than 5 minutes and must not be greater than 3 months. Got 0"); - - new JwtHttpHandler(system2, dbClient, settings.asConfig(), jwtSerializer, jwtCsrfVerifier); + assertThatThrownBy(() -> new JwtHttpHandler(system2, dbClient, settings.asConfig(), jwtSerializer, jwtCsrfVerifier)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Property sonar.web.sessionTimeoutInMinutes must be higher than 5 minutes and must not be greater than 3 months. Got 0 minutes"); } @Test public void session_timeout_property_cannot_be_negative() { settings.setProperty("sonar.web.sessionTimeoutInMinutes", -10); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Property sonar.web.sessionTimeoutInMinutes must be higher than 5 minutes and must not be greater than 3 months. Got -10"); - - new JwtHttpHandler(system2, dbClient, settings.asConfig(), jwtSerializer, jwtCsrfVerifier); + assertThatThrownBy(() -> new JwtHttpHandler(system2, dbClient, settings.asConfig(), jwtSerializer, jwtCsrfVerifier)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Property sonar.web.sessionTimeoutInMinutes must be higher than 5 minutes and must not be greater than 3 months. Got -10 minutes"); } @Test public void session_timeout_property_cannot_be_set_to_five_minutes() { settings.setProperty("sonar.web.sessionTimeoutInMinutes", 5); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Property sonar.web.sessionTimeoutInMinutes must be higher than 5 minutes and must not be greater than 3 months. Got 5 minutes"); - - new JwtHttpHandler(system2, dbClient, settings.asConfig(), jwtSerializer, jwtCsrfVerifier); + assertThatThrownBy(() -> new JwtHttpHandler(system2, dbClient, settings.asConfig(), jwtSerializer, jwtCsrfVerifier)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Property sonar.web.sessionTimeoutInMinutes must be higher than 5 minutes and must not be greater than 3 months. Got 5 minutes"); } @Test public void session_timeout_property_cannot_be_greater_than_three_months() { settings.setProperty("sonar.web.sessionTimeoutInMinutes", 4 * 30 * 24 * 60); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Property sonar.web.sessionTimeoutInMinutes must be higher than 5 minutes and must not be greater than 3 months. Got 172800 minutes"); - - new JwtHttpHandler(system2, dbClient, settings.asConfig(), jwtSerializer, jwtCsrfVerifier); + assertThatThrownBy(() -> new JwtHttpHandler(system2, dbClient, settings.asConfig(), jwtSerializer, jwtCsrfVerifier)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Property sonar.web.sessionTimeoutInMinutes must be higher than 5 minutes and must not be greater than 3 months. Got 172800 minutes"); } @Test diff --git a/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/JwtSerializerTest.java b/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/JwtSerializerTest.java index 18c7bdea99f..6c60d8a9355 100644 --- a/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/JwtSerializerTest.java +++ b/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/JwtSerializerTest.java @@ -28,20 +28,19 @@ import java.util.Date; import java.util.Optional; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.utils.DateUtils; import org.sonar.api.utils.System2; import org.sonar.server.authentication.JwtSerializer.JwtSession; -import org.sonar.server.authentication.event.AuthenticationEvent.Source; +import org.sonar.server.authentication.event.AuthenticationException; import static io.jsonwebtoken.SignatureAlgorithm.HS256; import static org.apache.commons.lang.time.DateUtils.addMinutes; import static org.apache.commons.lang.time.DateUtils.addYears; import static org.assertj.core.api.Assertions.assertThat; -import static org.sonar.server.authentication.event.AuthenticationExceptionMatcher.authenticationException; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.sonar.server.authentication.event.AuthenticationEvent.Source; public class JwtSerializerTest { @@ -49,8 +48,6 @@ public class JwtSerializerTest { private static final String USER_LOGIN = "john"; private static final String SESSION_TOKEN_UUID = "ABCD"; - @Rule - public ExpectedException expectedException = ExpectedException.none(); private MapSettings settings = new MapSettings(); private System2 system2 = System2.INSTANCE; @@ -181,9 +178,11 @@ public class JwtSerializerTest { .signWith(decodeSecretKey(A_SECRET_KEY), HS256) .compact(); - expectedException.expect(authenticationException().from(Source.jwt()).withLogin(USER_LOGIN).andNoPublicMessage()); - expectedException.expectMessage("Token id hasn't been found"); - underTest.decode(token); + assertThatThrownBy(() -> underTest.decode(token)) + .hasMessage("Token id hasn't been found") + .isInstanceOf(AuthenticationException.class) + .hasFieldOrPropertyWithValue("source", Source.jwt()) + .hasFieldOrPropertyWithValue("login", USER_LOGIN); } @Test @@ -199,9 +198,10 @@ public class JwtSerializerTest { .signWith(HS256, decodeSecretKey(A_SECRET_KEY)) .compact(); - expectedException.expect(authenticationException().from(Source.jwt()).withoutLogin().andNoPublicMessage()); - expectedException.expectMessage("Token subject hasn't been found"); - underTest.decode(token); + assertThatThrownBy(() -> underTest.decode(token)) + .hasMessage("Token subject hasn't been found") + .isInstanceOf(AuthenticationException.class) + .hasFieldOrPropertyWithValue("source", Source.jwt()); } @Test @@ -217,9 +217,11 @@ public class JwtSerializerTest { .signWith(decodeSecretKey(A_SECRET_KEY), HS256) .compact(); - expectedException.expect(authenticationException().from(Source.jwt()).withLogin(USER_LOGIN).andNoPublicMessage()); - expectedException.expectMessage("Token expiration date hasn't been found"); - underTest.decode(token); + assertThatThrownBy(() -> underTest.decode(token)) + .hasMessage("Token expiration date hasn't been found") + .isInstanceOf(AuthenticationException.class) + .hasFieldOrPropertyWithValue("source", Source.jwt()) + .hasFieldOrPropertyWithValue("login", USER_LOGIN); } @Test @@ -234,9 +236,11 @@ public class JwtSerializerTest { .signWith(decodeSecretKey(A_SECRET_KEY), HS256) .compact(); - expectedException.expect(authenticationException().from(Source.jwt()).withLogin(USER_LOGIN).andNoPublicMessage()); - expectedException.expectMessage("Token creation date hasn't been found"); - underTest.decode(token); + assertThatThrownBy(() -> underTest.decode(token)) + .hasMessage("Token creation date hasn't been found") + .isInstanceOf(AuthenticationException.class) + .hasFieldOrPropertyWithValue("source", Source.jwt()) + .hasFieldOrPropertyWithValue("login", USER_LOGIN); } @Test @@ -306,26 +310,23 @@ public class JwtSerializerTest { @Test public void encode_fail_when_not_started() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("org.sonar.server.authentication.JwtSerializer not started"); - - underTest.encode(new JwtSession(USER_LOGIN, SESSION_TOKEN_UUID, addMinutes(new Date(), 10).getTime())); + assertThatThrownBy(() -> underTest.encode(new JwtSession(USER_LOGIN, SESSION_TOKEN_UUID, addMinutes(new Date(), 10).getTime()))) + .isInstanceOf(NullPointerException.class) + .hasMessage("org.sonar.server.authentication.JwtSerializer not started"); } @Test public void decode_fail_when_not_started() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("org.sonar.server.authentication.JwtSerializer not started"); - - underTest.decode("token"); + assertThatThrownBy(() -> underTest.decode("token")) + .isInstanceOf(NullPointerException.class) + .hasMessage("org.sonar.server.authentication.JwtSerializer not started"); } @Test public void refresh_fail_when_not_started() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("org.sonar.server.authentication.JwtSerializer not started"); - - underTest.refresh(new DefaultClaims(), addMinutes(new Date(), 10).getTime()); + assertThatThrownBy(() -> underTest.refresh(new DefaultClaims(), addMinutes(new Date(), 10).getTime())) + .isInstanceOf(NullPointerException.class) + .hasMessage("org.sonar.server.authentication.JwtSerializer not started"); } private SecretKey decodeSecretKey(String encodedKey) { diff --git a/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/LogOAuthWarningTest.java b/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/LogOAuthWarningTest.java index 4199f0e7ac3..67d2b1ebab8 100644 --- a/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/LogOAuthWarningTest.java +++ b/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/LogOAuthWarningTest.java @@ -21,7 +21,6 @@ package org.sonar.server.authentication; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.platform.Server; import org.sonar.api.server.authentication.OAuth2IdentityProvider; import org.sonar.api.utils.log.LogTester; @@ -34,8 +33,6 @@ import static org.mockito.Mockito.when; public class LogOAuthWarningTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public LogTester logTester = new LogTester(); diff --git a/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/OAuth2CallbackFilterTest.java b/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/OAuth2CallbackFilterTest.java index 503b8be6149..8d7baa730de 100644 --- a/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/OAuth2CallbackFilterTest.java +++ b/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/OAuth2CallbackFilterTest.java @@ -26,7 +26,6 @@ import javax.servlet.http.HttpServletResponse; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; import org.sonar.api.server.authentication.OAuth2IdentityProvider; import org.sonar.api.server.authentication.UnauthorizedException; @@ -53,8 +52,6 @@ public class OAuth2CallbackFilterTest { @Rule public LogTester logTester = new LogTester(); @Rule - public ExpectedException thrown = ExpectedException.none(); - @Rule public IdentityProviderRepositoryRule identityProviderRepository = new IdentityProviderRepositoryRule(); private OAuth2ContextFactory oAuth2ContextFactory = mock(OAuth2ContextFactory.class); diff --git a/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/OAuth2ContextFactoryTest.java b/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/OAuth2ContextFactoryTest.java index ea5ebad1ccb..01c22951c6e 100644 --- a/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/OAuth2ContextFactoryTest.java +++ b/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/OAuth2ContextFactoryTest.java @@ -26,9 +26,7 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; import org.sonar.api.platform.Server; import org.sonar.api.server.authentication.OAuth2IdentityProvider; @@ -58,8 +56,6 @@ public class OAuth2ContextFactoryTest { .setEmail("john@email.com") .build(); - @Rule - public ExpectedException thrown = ExpectedException.none(); private ThreadLocalUserSession threadLocalUserSession = mock(ThreadLocalUserSession.class); private TestUserRegistrar userIdentityAuthenticator = new TestUserRegistrar(); diff --git a/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/OAuthCsrfVerifierTest.java b/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/OAuthCsrfVerifierTest.java index d7e0f12449b..a238cb6fc27 100644 --- a/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/OAuthCsrfVerifierTest.java +++ b/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/OAuthCsrfVerifierTest.java @@ -23,28 +23,24 @@ import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; import org.sonar.api.platform.Server; import org.sonar.api.server.authentication.OAuth2IdentityProvider; import org.sonar.server.authentication.event.AuthenticationEvent; +import org.sonar.server.authentication.event.AuthenticationException; import static org.apache.commons.codec.digest.DigestUtils.sha1Hex; import static org.apache.commons.codec.digest.DigestUtils.sha256Hex; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import static org.sonar.server.authentication.event.AuthenticationExceptionMatcher.authenticationException; public class OAuthCsrfVerifierTest { private static final String PROVIDER_NAME = "provider name"; - @Rule - public ExpectedException thrown = ExpectedException.none(); - private ArgumentCaptor cookieArgumentCaptor = ArgumentCaptor.forClass(Cookie.class); private OAuth2IdentityProvider identityProvider = mock(OAuth2IdentityProvider.class); @@ -73,7 +69,7 @@ public class OAuthCsrfVerifierTest { @Test public void verify_state() { String state = "state"; - when(request.getCookies()).thenReturn(new Cookie[] {new Cookie("OAUTHSTATE", sha256Hex(state))}); + when(request.getCookies()).thenReturn(new Cookie[]{new Cookie("OAUTHSTATE", sha256Hex(state))}); when(request.getParameter("aStateParameter")).thenReturn(state); underTest.verifyState(request, response, identityProvider, "aStateParameter"); @@ -89,7 +85,7 @@ public class OAuthCsrfVerifierTest { @Test public void verify_state_using_default_state_parameter() { String state = "state"; - when(request.getCookies()).thenReturn(new Cookie[] {new Cookie("OAUTHSTATE", sha256Hex(state))}); + when(request.getCookies()).thenReturn(new Cookie[]{new Cookie("OAUTHSTATE", sha256Hex(state))}); when(request.getParameter("state")).thenReturn(state); underTest.verifyState(request, response, identityProvider); @@ -104,41 +100,45 @@ public class OAuthCsrfVerifierTest { @Test public void fail_with_AuthenticationException_when_state_cookie_is_not_the_same_as_state_parameter() { - when(request.getCookies()).thenReturn(new Cookie[] {new Cookie("OAUTHSTATE", sha1Hex("state"))}); + when(request.getCookies()).thenReturn(new Cookie[]{new Cookie("OAUTHSTATE", sha1Hex("state"))}); when(request.getParameter("state")).thenReturn("other value"); - thrown.expect(authenticationException().from(AuthenticationEvent.Source.oauth2(identityProvider)).withoutLogin().andNoPublicMessage()); - thrown.expectMessage("CSRF state value is invalid"); - underTest.verifyState(request, response, identityProvider); + assertThatThrownBy(() -> underTest.verifyState(request, response, identityProvider)) + .hasMessage("CSRF state value is invalid") + .isInstanceOf(AuthenticationException.class) + .hasFieldOrPropertyWithValue("source", AuthenticationEvent.Source.oauth2(identityProvider)); } @Test public void fail_with_AuthenticationException_when_state_cookie_is_null() { - when(request.getCookies()).thenReturn(new Cookie[] {new Cookie("OAUTHSTATE", null)}); + when(request.getCookies()).thenReturn(new Cookie[]{new Cookie("OAUTHSTATE", null)}); when(request.getParameter("state")).thenReturn("state"); - thrown.expect(authenticationException().from(AuthenticationEvent.Source.oauth2(identityProvider)).withoutLogin().andNoPublicMessage()); - thrown.expectMessage("CSRF state value is invalid"); - underTest.verifyState(request, response, identityProvider); + assertThatThrownBy(() -> underTest.verifyState(request, response, identityProvider)) + .hasMessage("CSRF state value is invalid") + .isInstanceOf(AuthenticationException.class) + .hasFieldOrPropertyWithValue("source", AuthenticationEvent.Source.oauth2(identityProvider)); } @Test public void fail_with_AuthenticationException_when_state_parameter_is_empty() { - when(request.getCookies()).thenReturn(new Cookie[] {new Cookie("OAUTHSTATE", sha1Hex("state"))}); + when(request.getCookies()).thenReturn(new Cookie[]{new Cookie("OAUTHSTATE", sha1Hex("state"))}); when(request.getParameter("state")).thenReturn(""); - thrown.expect(authenticationException().from(AuthenticationEvent.Source.oauth2(identityProvider)).withoutLogin().andNoPublicMessage()); - thrown.expectMessage("CSRF state value is invalid"); - underTest.verifyState(request, response, identityProvider); + assertThatThrownBy(() -> underTest.verifyState(request, response, identityProvider)) + .hasMessage("CSRF state value is invalid") + .isInstanceOf(AuthenticationException.class) + .hasFieldOrPropertyWithValue("source", AuthenticationEvent.Source.oauth2(identityProvider)); } @Test public void fail_with_AuthenticationException_when_cookie_is_missing() { - when(request.getCookies()).thenReturn(new Cookie[] {}); + when(request.getCookies()).thenReturn(new Cookie[]{}); - thrown.expect(authenticationException().from(AuthenticationEvent.Source.oauth2(identityProvider)).withoutLogin().andNoPublicMessage()); - thrown.expectMessage("Cookie 'OAUTHSTATE' is missing"); - underTest.verifyState(request, response, identityProvider); + assertThatThrownBy(() -> underTest.verifyState(request, response, identityProvider)) + .hasMessage("Cookie 'OAUTHSTATE' is missing") + .isInstanceOf(AuthenticationException.class) + .hasFieldOrPropertyWithValue("source", AuthenticationEvent.Source.oauth2(identityProvider)); } private void verifyCookie(Cookie cookie) { diff --git a/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/ResetPasswordFilterTest.java b/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/ResetPasswordFilterTest.java index 319b9a27bf4..a638365b39c 100644 --- a/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/ResetPasswordFilterTest.java +++ b/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/ResetPasswordFilterTest.java @@ -32,7 +32,6 @@ import org.junit.runner.RunWith; import org.sonar.server.user.ThreadLocalUserSession; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; diff --git a/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/UserRegistrarImplTest.java b/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/UserRegistrarImplTest.java index f0be0dc151a..4fef0b19761 100644 --- a/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/UserRegistrarImplTest.java +++ b/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/UserRegistrarImplTest.java @@ -26,7 +26,6 @@ import javax.annotation.Nullable; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.impl.utils.AlwaysIncreasingSystem2; import org.sonar.api.server.authentication.UserIdentity; @@ -54,7 +53,6 @@ import static org.mockito.Mockito.verify; import static org.sonar.db.user.UserTesting.newUserDto; import static org.sonar.process.ProcessProperties.Property.ONBOARDING_TUTORIAL_SHOW_TO_NEW_USERS; import static org.sonar.server.authentication.event.AuthenticationEvent.Method.BASIC; -import static org.sonar.server.authentication.event.AuthenticationExceptionMatcher.authenticationException; public class UserRegistrarImplTest { private static final String USER_LOGIN = "johndoo"; @@ -74,8 +72,6 @@ public class UserRegistrarImplTest { private final MapSettings settings = new MapSettings().setProperty("sonar.internal.pbkdf2.iterations", "1"); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester db = DbTester.create(new AlwaysIncreasingSystem2()); @Rule @@ -227,14 +223,14 @@ public class UserRegistrarImplTest { db.users().insertUser(u -> u.setEmail("john@email.com")); Source source = Source.local(BASIC); - expectedException.expect(authenticationException().from(source) - .withLogin(USER_IDENTITY.getProviderLogin()) - .andPublicMessage("This account is already associated with another authentication method." + assertThatThrownBy(() -> underTest.register(newUserRegistration())) + .isInstanceOf(AuthenticationException.class) + .hasMessage("Email 'john@email.com' is already used") + .hasFieldOrPropertyWithValue("source", source) + .hasFieldOrPropertyWithValue("login", USER_IDENTITY.getProviderLogin()) + .hasFieldOrPropertyWithValue("publicMessage", "This account is already associated with another authentication method." + " Sign in using the current authentication method," - + " or contact your administrator to transfer your account to a different authentication method.")); - expectedException.expectMessage("Email 'john@email.com' is already used"); - - underTest.register(newUserRegistration()); + + " or contact your administrator to transfer your account to a different authentication method."); } @Test @@ -243,14 +239,14 @@ public class UserRegistrarImplTest { db.users().insertUser(u -> u.setEmail("john@email.com")); Source source = Source.realm(AuthenticationEvent.Method.FORM, GH_IDENTITY_PROVIDER.getName()); - expectedException.expect(authenticationException().from(source) - .withLogin(USER_IDENTITY.getProviderLogin()) - .andPublicMessage("This account is already associated with another authentication method." - + " Sign in using the current authentication method," - + " or contact your administrator to transfer your account to a different authentication method.")); - expectedException.expectMessage("Email 'john@email.com' is already used"); - - underTest.register(newUserRegistration(source)); + assertThatThrownBy(() -> underTest.register(newUserRegistration(source))) + .isInstanceOf(AuthenticationException.class) + .hasMessage("Email 'john@email.com' is already used") + .hasFieldOrPropertyWithValue("source", source) + .hasFieldOrPropertyWithValue("login", USER_IDENTITY.getProviderLogin()) + .hasFieldOrPropertyWithValue("publicMessage", "This account is already associated with another authentication method." + + " Sign in using the current authentication method," + + " or contact your administrator to transfer your account to a different authentication method."); } @Test @@ -262,14 +258,18 @@ public class UserRegistrarImplTest { .setAllowsUsersToSignUp(false); Source source = Source.realm(AuthenticationEvent.Method.FORM, identityProvider.getName()); - expectedException.expect(authenticationException().from(source).withLogin(USER_IDENTITY.getProviderLogin()).andPublicMessage("'github' users are not allowed to sign up")); - expectedException.expectMessage("User signup disabled for provider 'github'"); - - underTest.register(UserRegistration.builder() - .setUserIdentity(USER_IDENTITY) - .setProvider(identityProvider) - .setSource(source) - .build()); + assertThatThrownBy(() -> { + underTest.register(UserRegistration.builder() + .setUserIdentity(USER_IDENTITY) + .setProvider(identityProvider) + .setSource(source) + .build()); + }) + .isInstanceOf(AuthenticationException.class) + .hasMessage("User signup disabled for provider 'github'") + .hasFieldOrPropertyWithValue("source", source) + .hasFieldOrPropertyWithValue("login", USER_IDENTITY.getProviderLogin()) + .hasFieldOrPropertyWithValue("publicMessage", "'github' users are not allowed to sign up"); } @Test @@ -512,14 +512,15 @@ public class UserRegistrarImplTest { .build(); Source source = Source.realm(AuthenticationEvent.Method.FORM, GH_IDENTITY_PROVIDER.getName()); - expectedException.expect(authenticationException().from(source) - .withLogin(userIdentity.getProviderLogin()) - .andPublicMessage("This account is already associated with another authentication method." - + " Sign in using the current authentication method," - + " or contact your administrator to transfer your account to a different authentication method.")); - expectedException.expectMessage("Email 'john@email.com' is already used"); - underTest.register(newUserRegistration(userIdentity, source)); + assertThatThrownBy(() -> underTest.register(newUserRegistration(userIdentity, source))) + .isInstanceOf(AuthenticationException.class) + .hasMessage("Email 'john@email.com' is already used") + .hasFieldOrPropertyWithValue("source", source) + .hasFieldOrPropertyWithValue("login", USER_IDENTITY.getProviderLogin()) + .hasFieldOrPropertyWithValue("publicMessage", "This account is already associated with another authentication method." + + " Sign in using the current authentication method," + + " or contact your administrator to transfer your account to a different authentication method."); } @Test @@ -619,7 +620,7 @@ public class UserRegistrarImplTest { } private void checkGroupMembership(UserDto user, GroupDto... expectedGroups) { - assertThat(db.users().selectGroupUuidsOfUser(user)).containsOnly(stream(expectedGroups).map(GroupDto::getUuid).collect(Collectors.toList()).toArray(new String[] {})); + assertThat(db.users().selectGroupUuidsOfUser(user)).containsOnly(stream(expectedGroups).map(GroupDto::getUuid).collect(Collectors.toList()).toArray(new String[]{})); } private GroupDto insertDefaultGroup() { diff --git a/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/event/AuthenticationEventImplTest.java b/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/event/AuthenticationEventImplTest.java index d64a747ee74..7e0f6bf2e9f 100644 --- a/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/event/AuthenticationEventImplTest.java +++ b/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/event/AuthenticationEventImplTest.java @@ -28,12 +28,12 @@ import javax.servlet.http.HttpServletRequest; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.utils.log.LogTester; import org.sonar.api.utils.log.LoggerLevel; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; @@ -47,8 +47,6 @@ public class AuthenticationEventImplTest { @Rule public LogTester logTester = new LogTester(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private AuthenticationEventImpl underTest = new AuthenticationEventImpl(); @@ -60,19 +58,19 @@ public class AuthenticationEventImplTest { @Test public void login_success_fails_with_NPE_if_request_is_null() { logTester.setLevel(LoggerLevel.INFO); - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("request can't be null"); - underTest.loginSuccess(null, "login", Source.sso()); + assertThatThrownBy(() -> underTest.loginSuccess(null, "login", Source.sso())) + .isInstanceOf(NullPointerException.class) + .hasMessage("request can't be null"); } @Test public void login_success_fails_with_NPE_if_source_is_null() { logTester.setLevel(LoggerLevel.INFO); - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("source can't be null"); - underTest.loginSuccess(mock(HttpServletRequest.class), "login", null); + assertThatThrownBy(() -> underTest.loginSuccess(mock(HttpServletRequest.class), "login", null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("source can't be null"); } @Test @@ -133,19 +131,19 @@ public class AuthenticationEventImplTest { @Test public void login_failure_fails_with_NPE_if_request_is_null() { logTester.setLevel(LoggerLevel.INFO); - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("request can't be null"); - underTest.loginFailure(null, newBuilder().setSource(Source.sso()).build()); + assertThatThrownBy(() -> underTest.loginFailure(null, newBuilder().setSource(Source.sso()).build())) + .isInstanceOf(NullPointerException.class) + .hasMessage("request can't be null"); } @Test public void login_failure_fails_with_NPE_if_AuthenticationException_is_null() { logTester.setLevel(LoggerLevel.INFO); - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("AuthenticationException can't be null"); - underTest.loginFailure(mock(HttpServletRequest.class), null); + assertThatThrownBy(() -> underTest.loginFailure(mock(HttpServletRequest.class), null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("AuthenticationException can't be null"); } @Test @@ -241,10 +239,10 @@ public class AuthenticationEventImplTest { @Test public void logout_success_fails_with_NPE_if_request_is_null() { logTester.setLevel(LoggerLevel.INFO); - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("request can't be null"); - underTest.logoutSuccess(null, "foo"); + assertThatThrownBy(() -> underTest.logoutSuccess(null, "foo")) + .isInstanceOf(NullPointerException.class) + .hasMessage("request can't be null"); } @Test @@ -297,19 +295,19 @@ public class AuthenticationEventImplTest { @Test public void logout_failure_with_NPE_if_request_is_null() { logTester.setLevel(LoggerLevel.INFO); - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("request can't be null"); - underTest.logoutFailure(null, "bad csrf"); + assertThatThrownBy(() -> underTest.logoutFailure(null, "bad csrf")) + .isInstanceOf(NullPointerException.class) + .hasMessage("request can't be null"); } @Test public void login_fails_with_NPE_if_error_message_is_null() { logTester.setLevel(LoggerLevel.INFO); - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("error message can't be null"); - underTest.logoutFailure(mock(HttpServletRequest.class), null); + assertThatThrownBy(() -> underTest.logoutFailure(mock(HttpServletRequest.class), null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("error message can't be null"); } @Test diff --git a/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/event/AuthenticationEventSourceTest.java b/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/event/AuthenticationEventSourceTest.java index c33904b6ef9..72e2d4d9cf8 100644 --- a/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/event/AuthenticationEventSourceTest.java +++ b/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/event/AuthenticationEventSourceTest.java @@ -20,12 +20,11 @@ package org.sonar.server.authentication.event; import java.io.Serializable; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.authentication.BaseIdentityProvider; import org.sonar.api.server.authentication.OAuth2IdentityProvider; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -34,15 +33,12 @@ import static org.sonar.server.authentication.event.AuthenticationEvent.Provider import static org.sonar.server.authentication.event.AuthenticationEvent.Source; public class AuthenticationEventSourceTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void local_fails_with_NPE_if_method_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("method can't be null"); - - Source.local(null); + assertThatThrownBy(() -> Source.local(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("method can't be null"); } @Test @@ -56,26 +52,23 @@ public class AuthenticationEventSourceTest { @Test public void oauth2_fails_with_NPE_if_provider_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("identityProvider can't be null"); - - Source.oauth2(null); + assertThatThrownBy(() -> Source.oauth2(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("identityProvider can't be null"); } @Test public void oauth2_fails_with_NPE_if_providerName_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("provider name can't be null"); - - Source.oauth2(newOauth2IdentityProvider(null)); + assertThatThrownBy(() -> Source.oauth2(newOauth2IdentityProvider(null))) + .isInstanceOf(NullPointerException.class) + .hasMessage("provider name can't be null"); } @Test public void oauth2_fails_with_IAE_if_providerName_is_empty() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("provider name can't be empty"); - - Source.oauth2(newOauth2IdentityProvider("")); + assertThatThrownBy(() -> Source.oauth2(newOauth2IdentityProvider(""))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("provider name can't be empty"); } @Test @@ -89,26 +82,23 @@ public class AuthenticationEventSourceTest { @Test public void realm_fails_with_NPE_if_method_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("method can't be null"); - - Source.realm(null, "name"); + assertThatThrownBy(() -> Source.realm(null, "name")) + .isInstanceOf(NullPointerException.class) + .hasMessage("method can't be null"); } @Test public void realm_fails_with_NPE_if_providerName_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("provider name can't be null"); - - Source.realm(Method.BASIC, null); + assertThatThrownBy(() -> Source.realm(Method.BASIC, null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("provider name can't be null"); } @Test public void realm_fails_with_IAE_if_providerName_is_empty() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("provider name can't be empty"); - - Source.realm(Method.BASIC, ""); + assertThatThrownBy(() -> Source.realm(Method.BASIC, "")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("provider name can't be empty"); } @Test @@ -144,26 +134,23 @@ public class AuthenticationEventSourceTest { @Test public void external_fails_with_NPE_if_provider_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("identityProvider can't be null"); - - Source.external(null); + assertThatThrownBy(() -> Source.external(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("identityProvider can't be null"); } @Test public void external_fails_with_NPE_if_providerName_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("provider name can't be null"); - - Source.external(newBasicIdentityProvider(null)); + assertThatThrownBy(() -> Source.external(newBasicIdentityProvider(null))) + .isInstanceOf(NullPointerException.class) + .hasMessage("provider name can't be null"); } @Test public void external_fails_with_IAE_if_providerName_is_empty() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("provider name can't be empty"); - - Source.external(newBasicIdentityProvider("")); + assertThatThrownBy(() -> Source.external(newBasicIdentityProvider(""))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("provider name can't be empty"); } @Test diff --git a/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/event/AuthenticationExceptionTest.java b/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/event/AuthenticationExceptionTest.java index dfeca243b11..3aa04aedf59 100644 --- a/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/event/AuthenticationExceptionTest.java +++ b/server/sonar-webserver-auth/src/test/java/org/sonar/server/authentication/event/AuthenticationExceptionTest.java @@ -19,16 +19,13 @@ */ package org.sonar.server.authentication.event; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.server.authentication.event.AuthenticationEvent.Source; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class AuthenticationExceptionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void build_fails_with_NPE_if_source_is_null() { @@ -36,10 +33,9 @@ public class AuthenticationExceptionTest { .setLogin("login") .setMessage("message"); - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("source can't be null"); - - builder.build(); + assertThatThrownBy(builder::build) + .isInstanceOf(NullPointerException.class) + .hasMessage("source can't be null"); } @Test diff --git a/server/sonar-webserver-auth/src/test/java/org/sonar/server/permission/GroupUuidOrAnyoneTest.java b/server/sonar-webserver-auth/src/test/java/org/sonar/server/permission/GroupUuidOrAnyoneTest.java index ea8395f9ab0..093eb896aa7 100644 --- a/server/sonar-webserver-auth/src/test/java/org/sonar/server/permission/GroupUuidOrAnyoneTest.java +++ b/server/sonar-webserver-auth/src/test/java/org/sonar/server/permission/GroupUuidOrAnyoneTest.java @@ -19,17 +19,13 @@ */ package org.sonar.server.permission; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.db.user.GroupDto; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.assertj.core.api.Assertions.assertThat; public class GroupUuidOrAnyoneTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void for_returns_isAnyone_if_id_is_null() { diff --git a/server/sonar-webserver-auth/src/test/java/org/sonar/server/qualityprofile/BuiltInQPChangeNotificationTest.java b/server/sonar-webserver-auth/src/test/java/org/sonar/server/qualityprofile/BuiltInQPChangeNotificationTest.java index ea309092f70..dc9cf05f31c 100644 --- a/server/sonar-webserver-auth/src/test/java/org/sonar/server/qualityprofile/BuiltInQPChangeNotificationTest.java +++ b/server/sonar-webserver-auth/src/test/java/org/sonar/server/qualityprofile/BuiltInQPChangeNotificationTest.java @@ -20,22 +20,19 @@ package org.sonar.server.qualityprofile; import java.util.Random; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.notifications.Notification; import org.sonar.server.qualityprofile.BuiltInQPChangeNotificationBuilder.Profile; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; public class BuiltInQPChangeNotificationTest { private static final Random RANDOM = new Random(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void serialize_and_parse_no_profile() { @@ -137,9 +134,8 @@ public class BuiltInQPChangeNotificationTest { @Test public void fail_with_ISE_when_parsing_empty_notification() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Could not read the built-in quality profile notification"); - - BuiltInQPChangeNotificationBuilder.parse(new Notification(BuiltInQPChangeNotification.TYPE)); + assertThatThrownBy(() -> BuiltInQPChangeNotificationBuilder.parse(new Notification(BuiltInQPChangeNotification.TYPE))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Could not read the built-in quality profile notification"); } } diff --git a/server/sonar-webserver-auth/src/test/java/org/sonar/server/qualityprofile/BuiltInQProfileInsertImplTest.java b/server/sonar-webserver-auth/src/test/java/org/sonar/server/qualityprofile/BuiltInQProfileInsertImplTest.java index b1452cb2c61..0b14896fc1b 100644 --- a/server/sonar-webserver-auth/src/test/java/org/sonar/server/qualityprofile/BuiltInQProfileInsertImplTest.java +++ b/server/sonar-webserver-auth/src/test/java/org/sonar/server/qualityprofile/BuiltInQProfileInsertImplTest.java @@ -24,7 +24,6 @@ import java.util.List; import org.junit.After; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.PropertyType; import org.sonar.api.impl.utils.AlwaysIncreasingSystem2; import org.sonar.api.rule.Severity; @@ -59,8 +58,6 @@ public class BuiltInQProfileInsertImplTest { public BuiltInQProfileRepositoryRule builtInQProfileRepository = new BuiltInQProfileRepositoryRule(); @Rule public DbTester db = DbTester.create(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private final System2 system2 = new AlwaysIncreasingSystem2(); private final UuidFactory uuidFactory = new SequenceUuidFactory(); diff --git a/server/sonar-webserver-auth/src/test/java/org/sonar/server/qualityprofile/BuiltInQProfileRepositoryImplTest.java b/server/sonar-webserver-auth/src/test/java/org/sonar/server/qualityprofile/BuiltInQProfileRepositoryImplTest.java index e5c1b02dc4b..42cef84c2b9 100644 --- a/server/sonar-webserver-auth/src/test/java/org/sonar/server/qualityprofile/BuiltInQProfileRepositoryImplTest.java +++ b/server/sonar-webserver-auth/src/test/java/org/sonar/server/qualityprofile/BuiltInQProfileRepositoryImplTest.java @@ -22,7 +22,6 @@ package org.sonar.server.qualityprofile; import java.util.List; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.resources.Language; import org.sonar.api.resources.Languages; import org.sonar.api.rule.RuleKey; @@ -38,6 +37,7 @@ import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.groups.Tuple.tuple; import static org.mockito.Mockito.mock; import static org.sonar.db.rule.RuleTesting.EXTERNAL_XOO; @@ -47,8 +47,6 @@ public class BuiltInQProfileRepositoryImplTest { private static final Language FOO_LANGUAGE = LanguageTesting.newLanguage("foo", "foo", "foo"); private static final String SONAR_WAY_QP_NAME = "Sonar way"; - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester db = DbTester.create(); @@ -196,30 +194,26 @@ public class BuiltInQProfileRepositoryImplTest { DummyProfileDefinition[] definitions = new DummyProfileDefinition[] {new DummyProfileDefinition("foo", "foo", false, singletonList(EXTERNAL_XOO))}; BuiltInQProfileRepository underTest = new BuiltInQProfileRepositoryImpl(dbClient, ruleFinder, new Languages(FOO_LANGUAGE), definitions); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage(String.format("Rule with key '%s' not found", EXTERNAL_XOO.toString())); - underTest.initialize(); } @Test public void fail_with_ISE_when_two_profiles_with_different_name_are_default_for_the_same_language() { BuiltInQProfileRepository underTest = new BuiltInQProfileRepositoryImpl(dbClient, ruleFinder, new Languages(FOO_LANGUAGE), new DummyProfileDefinition("foo", "foo1", true), new DummyProfileDefinition("foo", "foo2", true)); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Several Quality profiles are flagged as default for the language foo: [foo1, foo2]"); - underTest.initialize(); + assertThatThrownBy(underTest::initialize) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Several Quality profiles are flagged as default for the language foo: [foo1, foo2]"); } @Test public void get_throws_ISE_if_called_before_initialize() { BuiltInQProfileRepositoryImpl underTest = new BuiltInQProfileRepositoryImpl(mock(DbClient.class), ruleFinder, new Languages()); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("initialize must be called first"); - - underTest.get(); + assertThatThrownBy(underTest::get) + .isInstanceOf(IllegalStateException.class) + .hasMessage("initialize must be called first"); } @Test @@ -227,20 +221,18 @@ public class BuiltInQProfileRepositoryImplTest { BuiltInQProfileRepositoryImpl underTest = new BuiltInQProfileRepositoryImpl(mock(DbClient.class), ruleFinder, new Languages()); underTest.initialize(); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("initialize must be called only once"); - - underTest.initialize(); + assertThatThrownBy(underTest::initialize) + .isInstanceOf(IllegalStateException.class) + .hasMessage("initialize must be called only once"); } @Test public void initialize_throws_ISE_if_language_has_no_builtin_qp() { BuiltInQProfileRepository underTest = new BuiltInQProfileRepositoryImpl(mock(DbClient.class), ruleFinder, new Languages(FOO_LANGUAGE)); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("The following languages have no built-in quality profiles: foo"); - - underTest.initialize(); + assertThatThrownBy(underTest::initialize) + .isInstanceOf(IllegalStateException.class) + .hasMessage("The following languages have no built-in quality profiles: foo"); } private static final class DummyProfileDefinition implements BuiltInQualityProfilesDefinition { diff --git a/server/sonar-webserver-auth/src/test/java/org/sonar/server/qualityprofile/BuiltInQProfileUpdateImplTest.java b/server/sonar-webserver-auth/src/test/java/org/sonar/server/qualityprofile/BuiltInQProfileUpdateImplTest.java index dde53fb8f1b..b2f25dd6163 100644 --- a/server/sonar-webserver-auth/src/test/java/org/sonar/server/qualityprofile/BuiltInQProfileUpdateImplTest.java +++ b/server/sonar-webserver-auth/src/test/java/org/sonar/server/qualityprofile/BuiltInQProfileUpdateImplTest.java @@ -63,7 +63,6 @@ import static org.sonar.api.rules.RulePriority.MAJOR; import static org.sonar.api.rules.RulePriority.MINOR; import static org.sonar.db.qualityprofile.QualityProfileTesting.newRuleProfileDto; import static org.sonar.server.qualityprofile.ActiveRuleInheritance.INHERITED; -import static org.sonar.server.qualityprofile.ActiveRuleInheritance.OVERRIDES; public class BuiltInQProfileUpdateImplTest { diff --git a/server/sonar-webserver-auth/src/test/java/org/sonar/server/user/DoPrivilegedTest.java b/server/sonar-webserver-auth/src/test/java/org/sonar/server/user/DoPrivilegedTest.java index b57a1e2e6d3..3ce36ea935e 100644 --- a/server/sonar-webserver-auth/src/test/java/org/sonar/server/user/DoPrivilegedTest.java +++ b/server/sonar-webserver-auth/src/test/java/org/sonar/server/user/DoPrivilegedTest.java @@ -26,7 +26,6 @@ import org.sonar.db.component.ComponentDto; import org.sonar.server.tester.MockUserSession; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; public class DoPrivilegedTest { diff --git a/server/sonar-webserver-auth/src/test/java/org/sonar/server/user/ExternalIdentityTest.java b/server/sonar-webserver-auth/src/test/java/org/sonar/server/user/ExternalIdentityTest.java index 430e05cbe83..6a6714ee6a4 100644 --- a/server/sonar-webserver-auth/src/test/java/org/sonar/server/user/ExternalIdentityTest.java +++ b/server/sonar-webserver-auth/src/test/java/org/sonar/server/user/ExternalIdentityTest.java @@ -19,16 +19,13 @@ */ package org.sonar.server.user; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class ExternalIdentityTest { - @Rule - public ExpectedException thrown = ExpectedException.none(); @Test public void create_external_identity() { @@ -48,18 +45,16 @@ public class ExternalIdentityTest { @Test public void fail_with_NPE_when_identity_provider_is_null() { - thrown.expect(NullPointerException.class); - thrown.expectMessage("Identity provider cannot be null"); - - new ExternalIdentity(null, "login", "ABCD"); + assertThatThrownBy(() -> new ExternalIdentity(null, "login", "ABCD")) + .isInstanceOf(NullPointerException.class) + .hasMessage("Identity provider cannot be null"); } @Test public void fail_with_NPE_when_identity_login_is_null() { - thrown.expect(NullPointerException.class); - thrown.expectMessage("Identity login cannot be null"); - - new ExternalIdentity("github", null, "ABCD"); + assertThatThrownBy(() -> new ExternalIdentity("github", null, "ABCD")) + .isInstanceOf(NullPointerException.class) + .hasMessage("Identity login cannot be null"); } } diff --git a/server/sonar-webserver-auth/src/test/java/org/sonar/server/user/NewUserTest.java b/server/sonar-webserver-auth/src/test/java/org/sonar/server/user/NewUserTest.java index e36c63b9566..1377e6d6727 100644 --- a/server/sonar-webserver-auth/src/test/java/org/sonar/server/user/NewUserTest.java +++ b/server/sonar-webserver-auth/src/test/java/org/sonar/server/user/NewUserTest.java @@ -19,17 +19,14 @@ */ package org.sonar.server.user; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class NewUserTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void create_new_user() { @@ -76,15 +73,16 @@ public class NewUserTest { @Test public void fail_to_set_password_when_external_identity_is_set() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Password should not be set with an external identity"); - - NewUser.builder() - .setLogin("login") - .setName("name") - .setEmail("email") - .setPassword("password") - .setExternalIdentity(new ExternalIdentity("github", "github_login", "ABCD")) - .build(); + assertThatThrownBy(() -> { + NewUser.builder() + .setLogin("login") + .setName("name") + .setEmail("email") + .setPassword("password") + .setExternalIdentity(new ExternalIdentity("github", "github_login", "ABCD")) + .build(); + }) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Password should not be set with an external identity"); } } diff --git a/server/sonar-webserver-auth/src/test/java/org/sonar/server/user/UserUpdaterCreateTest.java b/server/sonar-webserver-auth/src/test/java/org/sonar/server/user/UserUpdaterCreateTest.java index a0f2702509f..7d71b6976a5 100644 --- a/server/sonar-webserver-auth/src/test/java/org/sonar/server/user/UserUpdaterCreateTest.java +++ b/server/sonar-webserver-auth/src/test/java/org/sonar/server/user/UserUpdaterCreateTest.java @@ -26,7 +26,6 @@ import java.util.List; import org.elasticsearch.search.SearchHit; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.impl.utils.AlwaysIncreasingSystem2; @@ -35,7 +34,6 @@ import org.sonar.api.utils.System2; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.DbTester; -import org.sonar.db.audit.AuditPersister; import org.sonar.db.user.GroupDto; import org.sonar.db.user.UserDto; import org.sonar.server.authentication.CredentialsLocalAuthentication; @@ -49,6 +47,7 @@ import org.sonar.server.usergroups.DefaultGroupFinder; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.data.MapEntry.entry; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; @@ -63,8 +62,6 @@ public class UserUpdaterCreateTest { private final System2 system2 = new AlwaysIncreasingSystem2(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public EsTester es = EsTester.create(); @Rule @@ -327,100 +324,107 @@ public class UserUpdaterCreateTest { @Test public void fail_to_create_user_with_invalid_login() { - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Use only letters, numbers, and .-_@ please."); - - underTest.createAndCommit(db.getSession(), NewUser.builder() - .setLogin("/marius/") - .setName("Marius") - .setEmail("marius@mail.com") - .setPassword("password") - .build(), u -> { + assertThatThrownBy(() -> { + underTest.createAndCommit(db.getSession(), NewUser.builder() + .setLogin("/marius/") + .setName("Marius") + .setEmail("marius@mail.com") + .setPassword("password") + .build(), u -> { }); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Use only letters, numbers, and .-_@ please."); } @Test public void fail_to_create_user_with_space_in_login() { - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Use only letters, numbers, and .-_@ please."); - - underTest.createAndCommit(db.getSession(), NewUser.builder() - .setLogin("mari us") - .setName("Marius") - .setEmail("marius@mail.com") - .setPassword("password") - .build(), u -> { + assertThatThrownBy(() -> { + underTest.createAndCommit(db.getSession(), NewUser.builder() + .setLogin("mari us") + .setName("Marius") + .setEmail("marius@mail.com") + .setPassword("password") + .build(), u -> { }); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Use only letters, numbers, and .-_@ please."); } @Test public void fail_to_create_user_with_too_short_login() { - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Login is too short (minimum is 2 characters)"); - - underTest.createAndCommit(db.getSession(), NewUser.builder() - .setLogin("m") - .setName("Marius") - .setEmail("marius@mail.com") - .setPassword("password") - .build(), u -> { + assertThatThrownBy(() -> { + underTest.createAndCommit(db.getSession(), NewUser.builder() + .setLogin("m") + .setName("Marius") + .setEmail("marius@mail.com") + .setPassword("password") + .build(), u -> { }); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Login is too short (minimum is 2 characters)"); } @Test public void fail_to_create_user_with_too_long_login() { - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Login is too long (maximum is 255 characters)"); - - underTest.createAndCommit(db.getSession(), NewUser.builder() - .setLogin(Strings.repeat("m", 256)) - .setName("Marius") - .setEmail("marius@mail.com") - .setPassword("password") - .build(), u -> { + assertThatThrownBy(() -> { + underTest.createAndCommit(db.getSession(), NewUser.builder() + .setLogin(Strings.repeat("m", 256)) + .setName("Marius") + .setEmail("marius@mail.com") + .setPassword("password") + .build(), u -> { }); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Login is too long (maximum is 255 characters)"); } @Test public void fail_to_create_user_with_missing_name() { - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Name can't be empty"); - - underTest.createAndCommit(db.getSession(), NewUser.builder() - .setLogin(DEFAULT_LOGIN) - .setName(null) - .setEmail("marius@mail.com") - .setPassword("password") - .build(), u -> { + assertThatThrownBy(() -> { + underTest.createAndCommit(db.getSession(), NewUser.builder() + .setLogin(DEFAULT_LOGIN) + .setName(null) + .setEmail("marius@mail.com") + .setPassword("password") + .build(), u -> { }); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Name can't be empty"); } @Test public void fail_to_create_user_with_too_long_name() { - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Name is too long (maximum is 200 characters)"); - - underTest.createAndCommit(db.getSession(), NewUser.builder() - .setLogin(DEFAULT_LOGIN) - .setName(Strings.repeat("m", 201)) - .setEmail("marius@mail.com") - .setPassword("password") - .build(), u -> { + assertThatThrownBy(() -> { + underTest.createAndCommit(db.getSession(), NewUser.builder() + .setLogin(DEFAULT_LOGIN) + .setName(Strings.repeat("m", 201)) + .setEmail("marius@mail.com") + .setPassword("password") + .build(), u -> { }); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Name is too long (maximum is 200 characters)"); } @Test public void fail_to_create_user_with_too_long_email() { - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Email is too long (maximum is 100 characters)"); - - underTest.createAndCommit(db.getSession(), NewUser.builder() - .setLogin(DEFAULT_LOGIN) - .setName("Marius") - .setEmail(Strings.repeat("m", 101)) - .setPassword("password") - .build(), u -> { + assertThatThrownBy(() -> { + underTest.createAndCommit(db.getSession(), NewUser.builder() + .setLogin(DEFAULT_LOGIN) + .setName("Marius") + .setEmail(Strings.repeat("m", 101)) + .setPassword("password") + .build(), u -> { }); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Email is too long (maximum is 100 characters)"); } @Test @@ -443,17 +447,18 @@ public class UserUpdaterCreateTest { public void fail_to_create_user_when_scm_account_is_already_used() { db.users().insertUser(newLocalUser("john", "John", null).setScmAccounts(singletonList("jo"))); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("The scm account 'jo' is already used by user(s) : 'John (john)'"); - - underTest.createAndCommit(db.getSession(), NewUser.builder() - .setLogin(DEFAULT_LOGIN) - .setName("Marius") - .setEmail("marius@mail.com") - .setPassword("password") - .setScmAccounts(singletonList("jo")) - .build(), u -> { + assertThatThrownBy(() -> { + underTest.createAndCommit(db.getSession(), NewUser.builder() + .setLogin(DEFAULT_LOGIN) + .setName("Marius") + .setEmail("marius@mail.com") + .setPassword("password") + .setScmAccounts(singletonList("jo")) + .build(), u -> { }); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("The scm account 'jo' is already used by user(s) : 'John (john)'"); } @Test @@ -461,47 +466,50 @@ public class UserUpdaterCreateTest { db.users().insertUser(newLocalUser("john", "John", null).setScmAccounts(singletonList("john@email.com"))); db.users().insertUser(newLocalUser("technical-account", "Technical account", null).setScmAccounts(singletonList("john@email.com"))); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("The scm account 'john@email.com' is already used by user(s) : 'John (john), Technical account (technical-account)'"); - - underTest.createAndCommit(db.getSession(), NewUser.builder() - .setLogin(DEFAULT_LOGIN) - .setName("Marius") - .setEmail("marius@mail.com") - .setPassword("password") - .setScmAccounts(asList("john@email.com")) - .build(), u -> { + assertThatThrownBy(() -> { + underTest.createAndCommit(db.getSession(), NewUser.builder() + .setLogin(DEFAULT_LOGIN) + .setName("Marius") + .setEmail("marius@mail.com") + .setPassword("password") + .setScmAccounts(asList("john@email.com")) + .build(), u -> { }); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("The scm account 'john@email.com' is already used by user(s) : 'John (john), Technical account (technical-account)'"); } @Test public void fail_to_create_user_when_scm_account_is_user_login() { - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Login and email are automatically considered as SCM accounts"); - - underTest.createAndCommit(db.getSession(), NewUser.builder() - .setLogin(DEFAULT_LOGIN) - .setName("Marius2") - .setEmail("marius2@mail.com") - .setPassword("password2") - .setScmAccounts(singletonList(DEFAULT_LOGIN)) - .build(), u -> { + assertThatThrownBy(() -> { + underTest.createAndCommit(db.getSession(), NewUser.builder() + .setLogin(DEFAULT_LOGIN) + .setName("Marius2") + .setEmail("marius2@mail.com") + .setPassword("password2") + .setScmAccounts(singletonList(DEFAULT_LOGIN)) + .build(), u -> { }); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Login and email are automatically considered as SCM accounts"); } @Test public void fail_to_create_user_when_scm_account_is_user_email() { - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Login and email are automatically considered as SCM accounts"); - - underTest.createAndCommit(db.getSession(), NewUser.builder() - .setLogin(DEFAULT_LOGIN) - .setName("Marius2") - .setEmail("marius2@mail.com") - .setPassword("password2") - .setScmAccounts(singletonList("marius2@mail.com")) - .build(), u -> { + assertThatThrownBy(() -> { + underTest.createAndCommit(db.getSession(), NewUser.builder() + .setLogin(DEFAULT_LOGIN) + .setName("Marius2") + .setEmail("marius2@mail.com") + .setPassword("password2") + .setScmAccounts(singletonList("marius2@mail.com")) + .build(), u -> { }); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Login and email are automatically considered as SCM accounts"); } @Test @@ -509,15 +517,16 @@ public class UserUpdaterCreateTest { createDefaultGroup(); UserDto existingUser = db.users().insertUser(u -> u.setLogin("existing_login")); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("A user with login 'existing_login' already exists"); - - underTest.createAndCommit(db.getSession(), NewUser.builder() - .setLogin(existingUser.getLogin()) - .setName("User") - .setPassword("PASSWORD") - .build(), u -> { + assertThatThrownBy(() -> { + underTest.createAndCommit(db.getSession(), NewUser.builder() + .setLogin(existingUser.getLogin()) + .setName("User") + .setPassword("PASSWORD") + .build(), u -> { }); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("A user with login 'existing_login' already exists"); } @Test @@ -525,15 +534,16 @@ public class UserUpdaterCreateTest { createDefaultGroup(); UserDto existingUser = db.users().insertUser(u -> u.setExternalId("existing_external_id").setExternalIdentityProvider("existing_external_provider")); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("A user with provider id 'existing_external_id' and identity provider 'existing_external_provider' already exists"); - - underTest.createAndCommit(db.getSession(), NewUser.builder() - .setLogin("new_login") - .setName("User") - .setExternalIdentity(new ExternalIdentity(existingUser.getExternalIdentityProvider(), existingUser.getExternalLogin(), existingUser.getExternalId())) - .build(), u -> { + assertThatThrownBy(() -> { + underTest.createAndCommit(db.getSession(), NewUser.builder() + .setLogin("new_login") + .setName("User") + .setExternalIdentity(new ExternalIdentity(existingUser.getExternalIdentityProvider(), existingUser.getExternalLogin(), existingUser.getExternalId())) + .build(), u -> { }); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("A user with provider id 'existing_external_id' and identity provider 'existing_external_provider' already exists"); } @Test @@ -573,17 +583,18 @@ public class UserUpdaterCreateTest { @Test public void fail_to_associate_default_group_when_default_group_does_not_exist() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Default group cannot be found"); - - underTest.createAndCommit(db.getSession(), NewUser.builder() - .setLogin("user") - .setName("User") - .setEmail("user@mail.com") - .setPassword("password") - .setScmAccounts(asList("u1", "u_1")) - .build(), u -> { + assertThatThrownBy(() -> { + underTest.createAndCommit(db.getSession(), NewUser.builder() + .setLogin("user") + .setName("User") + .setEmail("user@mail.com") + .setPassword("password") + .setScmAccounts(asList("u1", "u_1")) + .build(), u -> { }); + }) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Default group cannot be found"); } private GroupDto createDefaultGroup() { diff --git a/server/sonar-webserver-auth/src/test/java/org/sonar/server/user/UserUpdaterReactivateTest.java b/server/sonar-webserver-auth/src/test/java/org/sonar/server/user/UserUpdaterReactivateTest.java index 1ad7b464ba0..1678d0abb11 100644 --- a/server/sonar-webserver-auth/src/test/java/org/sonar/server/user/UserUpdaterReactivateTest.java +++ b/server/sonar-webserver-auth/src/test/java/org/sonar/server/user/UserUpdaterReactivateTest.java @@ -22,7 +22,6 @@ package org.sonar.server.user; import com.google.common.collect.Multimap; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.impl.utils.AlwaysIncreasingSystem2; import org.sonar.api.utils.System2; @@ -42,6 +41,7 @@ import org.sonar.server.usergroups.DefaultGroupFinder; import static java.lang.String.format; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -53,8 +53,6 @@ public class UserUpdaterReactivateTest { private final System2 system2 = new AlwaysIncreasingSystem2(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public EsTester es = EsTester.create(); @Rule @@ -210,14 +208,15 @@ public class UserUpdaterReactivateTest { UserDto user = db.users().insertUser(); createDefaultGroup(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(format("An active user with login '%s' already exists", user.getLogin())); - - underTest.reactivateAndCommit(db.getSession(), user, NewUser.builder() - .setLogin(user.getLogin()) - .setName(user.getName()) - .build(), u -> { + assertThatThrownBy(() -> { + underTest.reactivateAndCommit(db.getSession(), user, NewUser.builder() + .setLogin(user.getLogin()) + .setName(user.getName()) + .build(), u -> { }); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage(format("An active user with login '%s' already exists", user.getLogin())); } @Test @@ -288,16 +287,17 @@ public class UserUpdaterReactivateTest { UserDto user = db.users().insertUser(u -> u.setActive(false)); UserDto existingUser = db.users().insertUser(u -> u.setLogin("existing_login")); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("A user with login 'existing_login' already exists"); - - underTest.reactivateAndCommit(db.getSession(), user, NewUser.builder() - .setLogin(existingUser.getLogin()) - .setName("Marius2") - .setPassword("password2") - .build(), - u -> { - }); + assertThatThrownBy(() -> { + underTest.reactivateAndCommit(db.getSession(), user, NewUser.builder() + .setLogin(existingUser.getLogin()) + .setName("Marius2") + .setPassword("password2") + .build(), + u -> { + }); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("A user with login 'existing_login' already exists"); } @Test @@ -306,16 +306,17 @@ public class UserUpdaterReactivateTest { UserDto user = db.users().insertUser(u -> u.setActive(false)); UserDto existingUser = db.users().insertUser(u -> u.setExternalId("existing_external_id").setExternalIdentityProvider("existing_external_provider")); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("A user with provider id 'existing_external_id' and identity provider 'existing_external_provider' already exists"); - - underTest.reactivateAndCommit(db.getSession(), user, NewUser.builder() - .setLogin(user.getLogin()) - .setName("Marius2") - .setExternalIdentity(new ExternalIdentity(existingUser.getExternalIdentityProvider(), existingUser.getExternalLogin(), existingUser.getExternalId())) - .build(), - u -> { - }); + assertThatThrownBy(() -> { + underTest.reactivateAndCommit(db.getSession(), user, NewUser.builder() + .setLogin(user.getLogin()) + .setName("Marius2") + .setExternalIdentity(new ExternalIdentity(existingUser.getExternalIdentityProvider(), existingUser.getExternalLogin(), existingUser.getExternalId())) + .build(), + u -> { + }); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("A user with provider id 'existing_external_id' and identity provider 'existing_external_provider' already exists"); } private GroupDto createDefaultGroup() { diff --git a/server/sonar-webserver-auth/src/test/java/org/sonar/server/usertoken/UserTokenAuthenticationTest.java b/server/sonar-webserver-auth/src/test/java/org/sonar/server/usertoken/UserTokenAuthenticationTest.java index b1919b83d59..19badd1d687 100644 --- a/server/sonar-webserver-auth/src/test/java/org/sonar/server/usertoken/UserTokenAuthenticationTest.java +++ b/server/sonar-webserver-auth/src/test/java/org/sonar/server/usertoken/UserTokenAuthenticationTest.java @@ -22,7 +22,6 @@ package org.sonar.server.usertoken; import java.util.Optional; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.utils.System2; import org.sonar.db.DbTester; import org.sonar.db.user.UserDto; @@ -38,8 +37,6 @@ import static org.mockito.Mockito.when; public class UserTokenAuthenticationTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester db = DbTester.create(System2.INSTANCE); diff --git a/server/sonar-webserver-core/src/test/java/org/sonar/server/app/WebServerProcessLoggingTest.java b/server/sonar-webserver-core/src/test/java/org/sonar/server/app/WebServerProcessLoggingTest.java index 52f87a55e75..b3c0cb48a27 100644 --- a/server/sonar-webserver-core/src/test/java/org/sonar/server/app/WebServerProcessLoggingTest.java +++ b/server/sonar-webserver-core/src/test/java/org/sonar/server/app/WebServerProcessLoggingTest.java @@ -42,7 +42,6 @@ import org.junit.AfterClass; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.sonar.process.Props; import org.sonar.process.logging.LogbackHelper; @@ -50,6 +49,7 @@ import org.sonar.process.logging.LogbackJsonLayout; import org.sonar.process.logging.PatternLayoutEncoder; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.slf4j.Logger.ROOT_LOGGER_NAME; import static org.sonar.process.ProcessProperties.Property.PATH_LOGS; @@ -57,8 +57,6 @@ public class WebServerProcessLoggingTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private File logDir; private Props props = new Props(new Properties()); @@ -401,50 +399,45 @@ public class WebServerProcessLoggingTest { public void fail_with_IAE_if_global_property_unsupported_level() { props.set("sonar.log.level", "ERROR"); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("log level ERROR in property sonar.log.level is not a supported value (allowed levels are [TRACE, DEBUG, INFO])"); - - underTest.configure(props); + assertThatThrownBy(() -> underTest.configure(props)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("log level ERROR in property sonar.log.level is not a supported value (allowed levels are [TRACE, DEBUG, INFO])"); } @Test public void fail_with_IAE_if_web_property_unsupported_level() { props.set("sonar.log.level.web", "ERROR"); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("log level ERROR in property sonar.log.level.web is not a supported value (allowed levels are [TRACE, DEBUG, INFO])"); - - underTest.configure(props); + assertThatThrownBy(() -> underTest.configure(props)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("log level ERROR in property sonar.log.level.web is not a supported value (allowed levels are [TRACE, DEBUG, INFO])"); } @Test public void fail_with_IAE_if_web_sql_property_unsupported_level() { props.set("sonar.log.level.web.sql", "ERROR"); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("log level ERROR in property sonar.log.level.web.sql is not a supported value (allowed levels are [TRACE, DEBUG, INFO])"); - - underTest.configure(props); + assertThatThrownBy(() -> underTest.configure(props)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("log level ERROR in property sonar.log.level.web.sql is not a supported value (allowed levels are [TRACE, DEBUG, INFO])"); } @Test public void fail_with_IAE_if_web_es_property_unsupported_level() { props.set("sonar.log.level.web.es", "ERROR"); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("log level ERROR in property sonar.log.level.web.es is not a supported value (allowed levels are [TRACE, DEBUG, INFO])"); - - underTest.configure(props); + assertThatThrownBy(() -> underTest.configure(props)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("log level ERROR in property sonar.log.level.web.es is not a supported value (allowed levels are [TRACE, DEBUG, INFO])"); } @Test public void fail_with_IAE_if_web_jmx_property_unsupported_level() { props.set("sonar.log.level.web.jmx", "ERROR"); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("log level ERROR in property sonar.log.level.web.jmx is not a supported value (allowed levels are [TRACE, DEBUG, INFO])"); - - underTest.configure(props); + assertThatThrownBy(() -> underTest.configure(props)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("log level ERROR in property sonar.log.level.web.jmx is not a supported value (allowed levels are [TRACE, DEBUG, INFO])"); } @Test diff --git a/server/sonar-webserver-core/src/test/java/org/sonar/server/ce/http/CeHttpClientImplTest.java b/server/sonar-webserver-core/src/test/java/org/sonar/server/ce/http/CeHttpClientImplTest.java index 0e64f365f2f..9c4bfcac841 100644 --- a/server/sonar-webserver-core/src/test/java/org/sonar/server/ce/http/CeHttpClientImplTest.java +++ b/server/sonar-webserver-core/src/test/java/org/sonar/server/ce/http/CeHttpClientImplTest.java @@ -28,25 +28,22 @@ import okio.Buffer; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.utils.log.LoggerLevel; -import org.sonar.process.sharedmemoryfile.DefaultProcessCommands; import org.sonar.process.ProcessEntryPoint; import org.sonar.process.ProcessId; +import org.sonar.process.sharedmemoryfile.DefaultProcessCommands; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; -import static org.sonar.test.ExceptionCauseMatcher.hasType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class CeHttpClientImplTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Rule public MockWebServer server = new MockWebServer(); private File ipcSharedDir; @@ -87,19 +84,18 @@ public class CeHttpClientImplTest { // initialize registration of process setUpWithHttpUrl(ProcessId.COMPUTE_ENGINE); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Failed to call HTTP server of process " + ProcessId.COMPUTE_ENGINE); - expectedException.expectCause(hasType(IOException.class) - .andMessage(format("Server returned HTTP response code: 500 for URL: http://%s:%d/systemInfo", server.getHostName(), server.getPort()))); - underTest.retrieveSystemInfo(); + assertThatThrownBy(() -> underTest.retrieveSystemInfo()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Failed to call HTTP server of process " + ProcessId.COMPUTE_ENGINE) + .hasRootCauseInstanceOf(IOException.class) + .hasRootCauseMessage(format("Server returned HTTP response code: 500 for URL: http://%s:%d/systemInfo", server.getHostName(), server.getPort())); } @Test public void changeLogLevel_throws_NPE_if_level_argument_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("level can't be null"); - - underTest.changeLogLevel(null); + assertThatThrownBy(() -> underTest.changeLogLevel(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("level can't be null"); } @Test @@ -110,13 +106,12 @@ public class CeHttpClientImplTest { // initialize registration of process setUpWithHttpUrl(ProcessId.COMPUTE_ENGINE); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Failed to call HTTP server of process " + ProcessId.COMPUTE_ENGINE); - expectedException.expectCause(hasType(IOException.class) - .andMessage(format("Failed to change log level in Compute Engine. Code was '500' and response was 'blah' for url " + - "'http://%s:%s/changeLogLevel'", server.getHostName(), server.getPort()))); - - underTest.changeLogLevel(LoggerLevel.DEBUG); + assertThatThrownBy(() -> underTest.changeLogLevel(LoggerLevel.DEBUG)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Failed to call HTTP server of process " + ProcessId.COMPUTE_ENGINE) + .hasRootCauseInstanceOf(IOException.class) + .hasRootCauseMessage(format("Failed to change log level in Compute Engine. Code was '500' and response was 'blah' for url " + + "'http://%s:%s/changeLogLevel'", server.getHostName(), server.getPort())); } @Test diff --git a/server/sonar-webserver-core/src/test/java/org/sonar/server/notification/email/EmailNotificationChannelTest.java b/server/sonar-webserver-core/src/test/java/org/sonar/server/notification/email/EmailNotificationChannelTest.java index 81f711abb37..2d7f20d524f 100644 --- a/server/sonar-webserver-core/src/test/java/org/sonar/server/notification/email/EmailNotificationChannelTest.java +++ b/server/sonar-webserver-core/src/test/java/org/sonar/server/notification/email/EmailNotificationChannelTest.java @@ -35,9 +35,7 @@ import javax.mail.internet.MimeMessage; import org.apache.commons.mail.EmailException; import org.junit.After; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.api.config.EmailSettings; import org.sonar.api.notifications.Notification; @@ -63,8 +61,6 @@ public class EmailNotificationChannelTest { private static final String SUBJECT_PREFIX = "[SONARQUBE]"; - @Rule - public ExpectedException thrown = ExpectedException.none(); private Wiser smtpServer; private EmailSettings configuration; diff --git a/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/ClusterVerificationTest.java b/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/ClusterVerificationTest.java index dfa227169f7..ed7a6ab5e5e 100644 --- a/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/ClusterVerificationTest.java +++ b/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/ClusterVerificationTest.java @@ -19,11 +19,10 @@ */ package org.sonar.server.platform; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.utils.MessageException; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -31,8 +30,6 @@ public class ClusterVerificationTest { private static final String ERROR_MESSAGE = "Cluster mode can't be enabled. Please install the Data Center Edition. More details at https://redirect.sonarsource.com/editions/datacenter.html."; - @Rule - public ExpectedException expectedException = ExpectedException.none(); private WebServer webServer = mock(WebServer.class); private ClusterFeature feature = mock(ClusterFeature.class); @@ -43,9 +40,9 @@ public class ClusterVerificationTest { ClusterVerification underTest = new ClusterVerification(webServer); - expectedException.expect(MessageException.class); - expectedException.expectMessage(ERROR_MESSAGE); - underTest.start(); + assertThatThrownBy(underTest::start) + .isInstanceOf(MessageException.class) + .hasMessage(ERROR_MESSAGE); } @Test @@ -54,9 +51,9 @@ public class ClusterVerificationTest { when(feature.isEnabled()).thenReturn(false); ClusterVerification underTest = new ClusterVerification(webServer, feature); - expectedException.expect(MessageException.class); - expectedException.expectMessage(ERROR_MESSAGE); - underTest.start(); + assertThatThrownBy(underTest::start) + .isInstanceOf(MessageException.class) + .hasMessage(ERROR_MESSAGE); } @Test diff --git a/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/DatabaseServerCompatibilityTest.java b/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/DatabaseServerCompatibilityTest.java index acf32f945f8..a9d33f44aa4 100644 --- a/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/DatabaseServerCompatibilityTest.java +++ b/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/DatabaseServerCompatibilityTest.java @@ -22,7 +22,6 @@ package org.sonar.server.platform; import java.util.Optional; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.utils.MessageException; import org.sonar.api.utils.log.LogTester; @@ -38,8 +37,6 @@ public class DatabaseServerCompatibilityTest { @Rule public LogTester logTester = new LogTester(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private MapSettings settings = new MapSettings(); @Test diff --git a/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/PersistentSettingsTest.java b/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/PersistentSettingsTest.java index a73583572ea..7db8acf6d4d 100644 --- a/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/PersistentSettingsTest.java +++ b/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/PersistentSettingsTest.java @@ -21,8 +21,8 @@ package org.sonar.server.platform; import org.junit.Rule; import org.junit.Test; -import org.sonar.api.config.internal.Settings; import org.sonar.api.config.internal.MapSettings; +import org.sonar.api.config.internal.Settings; import org.sonar.api.utils.System2; import org.sonar.db.DbTester; import org.sonar.server.setting.SettingsChangeNotifier; diff --git a/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/StandaloneSystemInfoWriterTest.java b/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/StandaloneSystemInfoWriterTest.java index bd893c90327..ca44516f9ab 100644 --- a/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/StandaloneSystemInfoWriterTest.java +++ b/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/StandaloneSystemInfoWriterTest.java @@ -23,7 +23,6 @@ import java.io.StringWriter; import java.util.Optional; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.Mockito; import org.sonar.api.utils.text.JsonWriter; import org.sonar.process.systeminfo.SystemInfoSection; @@ -45,8 +44,6 @@ public class StandaloneSystemInfoWriterTest { public UserSessionRule userSessionRule = UserSessionRule.standalone() .logIn("login") .setName("name"); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private final SystemInfoSection section1 = mock(SystemInfoSection.class); private final SystemInfoSection section2 = mock(SystemInfoSection.class); diff --git a/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/StartupMetadataPersisterTest.java b/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/StartupMetadataPersisterTest.java index 7e476ffa0f2..9da584ecdd9 100644 --- a/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/StartupMetadataPersisterTest.java +++ b/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/StartupMetadataPersisterTest.java @@ -21,7 +21,6 @@ package org.sonar.server.platform; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.CoreProperties; import org.sonar.api.utils.DateUtils; import org.sonar.api.utils.System2; @@ -32,8 +31,6 @@ import static org.assertj.core.api.Assertions.assertThat; public class StartupMetadataPersisterTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); diff --git a/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/db/EmbeddedDatabaseTest.java b/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/db/EmbeddedDatabaseTest.java index 764d8cc34c4..4c244a6a7ed 100644 --- a/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/db/EmbeddedDatabaseTest.java +++ b/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/db/EmbeddedDatabaseTest.java @@ -27,7 +27,6 @@ import org.junit.After; import org.junit.Rule; import org.junit.Test; import org.junit.rules.DisableOnDebug; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.junit.rules.TestRule; import org.junit.rules.Timeout; @@ -37,6 +36,7 @@ import org.sonar.api.utils.log.LogTester; import org.sonar.process.NetworkUtilsImpl; import static junit.framework.Assert.fail; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.sonar.process.ProcessProperties.Property.JDBC_EMBEDDED_PORT; @@ -49,8 +49,6 @@ public class EmbeddedDatabaseTest { private static final String LOOPBACK_ADDRESS = InetAddress.getLoopbackAddress().getHostAddress(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public LogTester logTester = new LogTester(); @Rule @@ -71,30 +69,27 @@ public class EmbeddedDatabaseTest { @Test public void start_fails_with_IAE_if_property_Data_Path_is_not_set() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Missing property " + PATH_DATA.getKey()); - - underTest.start(); + assertThatThrownBy(() -> underTest.start()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Missing property " + PATH_DATA.getKey()); } @Test public void start_fails_with_IAE_if_property_Data_Path_is_empty() { settings.setProperty(PATH_DATA.getKey(), ""); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Missing property " + PATH_DATA.getKey()); - - underTest.start(); + assertThatThrownBy(() -> underTest.start()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Missing property " + PATH_DATA.getKey()); } @Test public void start_fails_with_IAE_if_JDBC_URL_settings_is_not_set() throws IOException { settings.setProperty(PATH_DATA.getKey(), temporaryFolder.newFolder().getAbsolutePath()); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Missing property " + JDBC_URL.getKey()); - - underTest.start(); + assertThatThrownBy(() -> underTest.start()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Missing property " + JDBC_URL.getKey()); } @Test @@ -103,10 +98,9 @@ public class EmbeddedDatabaseTest { .setProperty(PATH_DATA.getKey(), temporaryFolder.newFolder().getAbsolutePath()) .setProperty(JDBC_URL.getKey(), "jdbc url"); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Missing property " + JDBC_EMBEDDED_PORT.getKey()); - - underTest.start(); + assertThatThrownBy(() -> underTest.start()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Missing property " + JDBC_EMBEDDED_PORT.getKey()); } @Test diff --git a/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/db/migration/AutoDbMigrationTest.java b/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/db/migration/AutoDbMigrationTest.java index 4c4c6cb8b0b..dfc1d90d9c6 100644 --- a/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/db/migration/AutoDbMigrationTest.java +++ b/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/db/migration/AutoDbMigrationTest.java @@ -21,7 +21,6 @@ package org.sonar.server.platform.db.migration; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.Mockito; import org.sonar.api.utils.log.LogTester; import org.sonar.api.utils.log.LoggerLevel; @@ -41,8 +40,6 @@ import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; public class AutoDbMigrationTest { - @Rule - public ExpectedException thrown = ExpectedException.none(); @Rule public LogTester logTester = new LogTester(); diff --git a/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/monitoring/BundledSectionTest.java b/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/monitoring/BundledSectionTest.java index 3d7926a9695..99f324ac830 100644 --- a/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/monitoring/BundledSectionTest.java +++ b/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/monitoring/BundledSectionTest.java @@ -19,6 +19,7 @@ */ package org.sonar.server.platform.monitoring; +import java.util.Arrays; import org.junit.Test; import org.sonar.core.platform.PluginInfo; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; @@ -30,7 +31,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.server.platform.monitoring.SystemInfoTesting.assertThatAttributeIs; -import java.util.Arrays; public class BundledSectionTest { diff --git a/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/monitoring/EsIndexesSectionTest.java b/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/monitoring/EsIndexesSectionTest.java index 161fbbfcbb8..248f8e4b93b 100644 --- a/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/monitoring/EsIndexesSectionTest.java +++ b/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/monitoring/EsIndexesSectionTest.java @@ -27,7 +27,6 @@ import org.sonar.server.es.EsClient; import org.sonar.server.es.EsTester; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.process.systeminfo.SystemInfoUtils.attribute; diff --git a/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/monitoring/PluginsSectionTest.java b/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/monitoring/PluginsSectionTest.java index 8fbf32462d8..7dc9e328500 100644 --- a/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/monitoring/PluginsSectionTest.java +++ b/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/monitoring/PluginsSectionTest.java @@ -22,14 +22,12 @@ package org.sonar.server.platform.monitoring; import java.util.Arrays; import org.junit.Test; import org.sonar.core.platform.PluginInfo; -import org.sonar.core.platform.PluginRepository; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; import org.sonar.server.plugins.PluginType; import org.sonar.server.plugins.ServerPluginRepository; import org.sonar.updatecenter.common.Version; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.server.platform.monitoring.SystemInfoTesting.assertThatAttributeIs; diff --git a/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/monitoring/cluster/AppNodesInfoLoaderImplTest.java b/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/monitoring/cluster/AppNodesInfoLoaderImplTest.java index d36ce91ee3a..778bde943f8 100644 --- a/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/monitoring/cluster/AppNodesInfoLoaderImplTest.java +++ b/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/monitoring/cluster/AppNodesInfoLoaderImplTest.java @@ -25,9 +25,7 @@ import com.hazelcast.cluster.MemberSelector; import java.io.IOException; import java.net.InetAddress; import java.util.Collection; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.Mockito; import org.sonar.process.cluster.hz.DistributedAnswer; import org.sonar.process.cluster.hz.DistributedCall; @@ -45,8 +43,6 @@ public class AppNodesInfoLoaderImplTest { private static final InetAddress AN_ADDRESS = InetAddress.getLoopbackAddress(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private final HazelcastMember hzMember = mock(HazelcastMember.class); private final AppNodesInfoLoaderImpl underTest = new AppNodesInfoLoaderImpl(hzMember); diff --git a/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/monitoring/cluster/NodeSystemSectionTest.java b/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/monitoring/cluster/NodeSystemSectionTest.java index ca07b038742..66d6c18f60a 100644 --- a/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/monitoring/cluster/NodeSystemSectionTest.java +++ b/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/monitoring/cluster/NodeSystemSectionTest.java @@ -19,9 +19,7 @@ */ package org.sonar.server.platform.monitoring.cluster; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.platform.Server; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; @@ -41,8 +39,6 @@ import static org.sonar.server.platform.monitoring.SystemInfoTesting.assertThatA public class NodeSystemSectionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private MapSettings settings = new MapSettings(); private Server server = mock(Server.class, RETURNS_DEEP_STUBS); diff --git a/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/serverid/ServerIdFactoryImplTest.java b/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/serverid/ServerIdFactoryImplTest.java index 363c363b187..ba3a3630116 100644 --- a/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/serverid/ServerIdFactoryImplTest.java +++ b/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/serverid/ServerIdFactoryImplTest.java @@ -24,9 +24,8 @@ import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.text.SimpleDateFormat; import java.util.Date; -import org.junit.Rule; +import org.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.api.config.Configuration; import org.sonar.api.config.internal.MapSettings; @@ -36,6 +35,7 @@ import org.sonar.core.util.Uuids; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.core.platform.ServerId.DATABASE_ID_LENGTH; @@ -48,8 +48,6 @@ import static org.sonar.server.platform.serverid.ServerIdFactoryImpl.crc32Hex; public class ServerIdFactoryImplTest { private static final ServerId A_SERVERID = ServerId.of(randomAlphabetic(DATABASE_ID_LENGTH), randomAlphabetic(UUID_DATASET_ID_LENGTH)); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private MapSettings settings = new MapSettings(); private Configuration config = settings.asConfig(); @@ -59,9 +57,7 @@ public class ServerIdFactoryImplTest { @Test public void create_from_scratch_fails_with_ISE_if_JDBC_property_not_set() { - expectMissingJdbcUrlISE(); - - underTest.create(); + expectMissingJdbcUrlISE(() -> underTest.create()); } @Test @@ -81,9 +77,7 @@ public class ServerIdFactoryImplTest { @Test public void create_from_ServerId_fails_with_ISE_if_JDBC_property_not_set() { - expectMissingJdbcUrlISE(); - - underTest.create(A_SERVERID); + expectMissingJdbcUrlISE(() -> underTest.create(A_SERVERID)); } @Test @@ -112,8 +106,9 @@ public class ServerIdFactoryImplTest { }; } - private void expectMissingJdbcUrlISE() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Missing JDBC URL"); + private void expectMissingJdbcUrlISE(ThrowingCallable callback) { + assertThatThrownBy(callback) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Missing JDBC URL"); } } diff --git a/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/serverid/ServerIdManagerTest.java b/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/serverid/ServerIdManagerTest.java index 8505afc474b..c92489f6287 100644 --- a/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/serverid/ServerIdManagerTest.java +++ b/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/serverid/ServerIdManagerTest.java @@ -22,13 +22,13 @@ package org.sonar.server.platform.serverid; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; -import org.sonar.api.SonarEdition; +import org.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.junit.After; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.api.CoreProperties; +import org.sonar.api.SonarEdition; import org.sonar.api.SonarQubeSide; import org.sonar.api.internal.SonarRuntimeImpl; import org.sonar.api.utils.System2; @@ -43,6 +43,7 @@ import org.sonar.server.property.InternalProperties; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; @@ -65,8 +66,6 @@ public class ServerIdManagerTest { @Rule public final DbTester dbTester = DbTester.create(System2.INSTANCE); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private ServerIdChecksum serverIdChecksum = mock(ServerIdChecksum.class); private ServerIdFactory serverIdFactory = mock(ServerIdFactory.class); @@ -209,9 +208,7 @@ public class ServerIdManagerTest { public void web_follower_fails_if_server_id_is_missing() { when(webServer.isStartupLeader()).thenReturn(false); - expectMissingServerIdException(); - - test(SERVER); + expectMissingServerIdException(() -> test(SERVER)); } @Test @@ -219,9 +216,7 @@ public class ServerIdManagerTest { insertServerId(""); when(webServer.isStartupLeader()).thenReturn(false); - expectEmptyServerIdException(); - - test(SERVER); + expectEmptyServerIdException(() -> test(SERVER)); } @Test @@ -258,18 +253,14 @@ public class ServerIdManagerTest { @Test public void compute_engine_fails_if_server_id_is_missing() { - expectMissingServerIdException(); - - test(COMPUTE_ENGINE); + expectMissingServerIdException(() -> test(COMPUTE_ENGINE)); } @Test public void compute_engine_fails_if_server_id_is_empty() { insertServerId(""); - expectEmptyServerIdException(); - - test(COMPUTE_ENGINE); + expectEmptyServerIdException(() -> test(COMPUTE_ENGINE)); } @Test @@ -299,14 +290,16 @@ public class ServerIdManagerTest { }; } - private void expectEmptyServerIdException() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Property sonar.core.id is empty in database"); + private void expectEmptyServerIdException(ThrowingCallable callback) { + assertThatThrownBy(callback) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Property sonar.core.id is empty in database"); } - private void expectMissingServerIdException() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Property sonar.core.id is missing in database"); + private void expectMissingServerIdException(ThrowingCallable callback) { + assertThatThrownBy(callback) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Property sonar.core.id is missing in database"); } private void verifyDb(ServerId expectedServerId, String expectedChecksum) { diff --git a/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/web/requestid/RequestIdGeneratorImplTest.java b/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/web/requestid/RequestIdGeneratorImplTest.java index 0efaef7ffbe..79cd7e63d77 100644 --- a/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/web/requestid/RequestIdGeneratorImplTest.java +++ b/server/sonar-webserver-core/src/test/java/org/sonar/server/platform/web/requestid/RequestIdGeneratorImplTest.java @@ -19,18 +19,15 @@ */ package org.sonar.server.platform.web.requestid; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.core.util.UuidGenerator; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class RequestIdGeneratorImplTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private UuidGenerator.WithFixedBase generator1 = increment -> new byte[] {124, 22, 66, 96, 55, 88, 2, 9}; private UuidGenerator.WithFixedBase generator2 = increment -> new byte[] {0, 5, 88, 81, 8, 6, 44, 19}; @@ -55,10 +52,11 @@ public class RequestIdGeneratorImplTest { assertThat(underTest.generate()).isEqualTo("fgkjTAIBAg=="); // renewing generator and using generator3 assertThat(underTest.generate()).isEqualTo("fgkjTAIBAg=="); // using generator3 - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage(expected.getMessage()); - - underTest.generate(); // renewing generator and failing + assertThatThrownBy(() -> { + underTest.generate(); // renewing generator and failing + }) + .isInstanceOf(IllegalStateException.class) + .hasMessage(expected.getMessage()); } @Test @@ -81,9 +79,10 @@ public class RequestIdGeneratorImplTest { assertThat(underTest.generate()).isEqualTo("fgkjTAIBAg=="); // using generator3 assertThat(underTest.generate()).isEqualTo("fgkjTAIBAg=="); // using generator3 - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage(expected.getMessage()); - - underTest.generate(); // renewing generator and failing + assertThatThrownBy(() -> { + underTest.generate(); // renewing generator and failing + }) + .isInstanceOf(IllegalStateException.class) + .hasMessage(expected.getMessage()); } } diff --git a/server/sonar-webserver-core/src/test/java/org/sonar/server/plugins/PluginsRiskConsentFilterTest.java b/server/sonar-webserver-core/src/test/java/org/sonar/server/plugins/PluginsRiskConsentFilterTest.java index 523f65ce9fb..20c59b0370b 100644 --- a/server/sonar-webserver-core/src/test/java/org/sonar/server/plugins/PluginsRiskConsentFilterTest.java +++ b/server/sonar-webserver-core/src/test/java/org/sonar/server/plugins/PluginsRiskConsentFilterTest.java @@ -20,13 +20,17 @@ package org.sonar.server.plugins; +import java.util.Optional; +import javax.servlet.FilterChain; +import javax.servlet.ServletRequest; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import org.sonar.api.config.Configuration; import org.sonar.api.web.ServletFilter; import org.sonar.core.extension.PluginRiskConsent; -import org.sonar.server.plugins.PluginsRiskConsentFilter; import org.sonar.server.user.ThreadLocalUserSession; import static org.assertj.core.api.Assertions.assertThat; @@ -35,11 +39,6 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.sonar.core.config.CorePropertyDefinitions.PLUGINS_RISK_CONSENT; -import javax.servlet.FilterChain; -import javax.servlet.ServletRequest; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.util.Optional; public class PluginsRiskConsentFilterTest { diff --git a/server/sonar-webserver-core/src/test/java/org/sonar/server/qualitygate/ProjectsInWarningDaemonTest.java b/server/sonar-webserver-core/src/test/java/org/sonar/server/qualitygate/ProjectsInWarningDaemonTest.java index ab6d6073236..78c49687110 100644 --- a/server/sonar-webserver-core/src/test/java/org/sonar/server/qualitygate/ProjectsInWarningDaemonTest.java +++ b/server/sonar-webserver-core/src/test/java/org/sonar/server/qualitygate/ProjectsInWarningDaemonTest.java @@ -23,7 +23,6 @@ import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.measures.CoreMetrics; import org.sonar.api.measures.Metric; @@ -52,8 +51,6 @@ import static org.sonar.server.qualitygate.ProjectsInWarningDaemon.PROJECTS_IN_W public class ProjectsInWarningDaemonTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester db = DbTester.create(); @Rule diff --git a/server/sonar-webserver-core/src/test/java/org/sonar/server/rule/RegisterRulesTest.java b/server/sonar-webserver-core/src/test/java/org/sonar/server/rule/RegisterRulesTest.java index 572e4706274..5eb8a2d39c9 100644 --- a/server/sonar-webserver-core/src/test/java/org/sonar/server/rule/RegisterRulesTest.java +++ b/server/sonar-webserver-core/src/test/java/org/sonar/server/rule/RegisterRulesTest.java @@ -30,7 +30,6 @@ import java.util.function.Consumer; import java.util.stream.IntStream; import org.junit.Before; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.api.impl.utils.TestSystem2; import org.sonar.api.resources.Language; @@ -72,6 +71,7 @@ import static java.util.Collections.emptySet; import static java.util.Collections.singletonList; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; @@ -104,8 +104,6 @@ public class RegisterRulesTest { private final TestSystem2 system = new TestSystem2().setNow(DATE1.getTime()); - @org.junit.Rule - public ExpectedException expectedException = ExpectedException.none(); @org.junit.Rule public DbTester db = DbTester.create(system); @org.junit.Rule @@ -903,31 +901,33 @@ public class RegisterRulesTest { @Test public void declaring_two_rules_with_same_deprecated_RuleKey_should_throw_ISE() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("The following deprecated rule keys are declared at least twice [fake:old]"); - - execute(context -> { - NewRepository repo = context.createRepository("fake", "java"); - createRule(repo, "newKey1") - .addDeprecatedRuleKey("fake", "old"); - createRule(repo, "newKey2") - .addDeprecatedRuleKey("fake", "old"); - repo.done(); - }); + assertThatThrownBy(() -> { + execute(context -> { + NewRepository repo = context.createRepository("fake", "java"); + createRule(repo, "newKey1") + .addDeprecatedRuleKey("fake", "old"); + createRule(repo, "newKey2") + .addDeprecatedRuleKey("fake", "old"); + repo.done(); + }); + }) + .isInstanceOf(IllegalStateException.class) + .hasMessage("The following deprecated rule keys are declared at least twice [fake:old]"); } @Test public void declaring_a_rule_with_a_deprecated_RuleKey_still_used_should_throw_ISE() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("The following rule keys are declared both as deprecated and used key [fake:newKey1]"); - - execute(context -> { - NewRepository repo = context.createRepository("fake", "java"); - createRule(repo, "newKey1"); - createRule(repo, "newKey2") - .addDeprecatedRuleKey("fake", "newKey1"); - repo.done(); - }); + assertThatThrownBy(() -> { + execute(context -> { + NewRepository repo = context.createRepository("fake", "java"); + createRule(repo, "newKey1"); + createRule(repo, "newKey2") + .addDeprecatedRuleKey("fake", "newKey1"); + repo.done(); + }); + }) + .isInstanceOf(IllegalStateException.class) + .hasMessage("The following rule keys are declared both as deprecated and used key [fake:newKey1]"); } @Test @@ -936,13 +936,14 @@ public class RegisterRulesTest { execute(context -> createRule(context, "javascript", "javascript", "s103", r -> r.addDeprecatedRuleKey("javascript", "linelength"))); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("An incorrect state of deprecated rule keys has been detected.\n " + - "The deprecated rule key [javascript:linelength] was previously deprecated by [javascript:s103]. [javascript:s103] should be a deprecated key of [sonarjs:s103],"); - - // This rule should have been moved to another repository - execute(context -> createRule(context, "javascript", "sonarjs", "s103", - r -> r.addDeprecatedRuleKey("javascript", "linelength"))); + assertThatThrownBy(() -> { + // This rule should have been moved to another repository + execute(context -> createRule(context, "javascript", "sonarjs", "s103", + r -> r.addDeprecatedRuleKey("javascript", "linelength"))); + }) + .isInstanceOf(IllegalStateException.class) + .hasMessage("An incorrect state of deprecated rule keys has been detected.\n " + + "The deprecated rule key [javascript:linelength] was previously deprecated by [javascript:s103]. [javascript:s103] should be a deprecated key of [sonarjs:s103],"); } @Test @@ -959,15 +960,16 @@ public class RegisterRulesTest { @Test public void declaring_a_rule_with_an_existing_RuleKey_still_used_should_throw_IAE() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The rule 'newKey1' of repository 'fake' is declared several times"); - - execute(context -> { - NewRepository repo = context.createRepository("fake", "java"); - createRule(repo, "newKey1"); - createRule(repo, "newKey1"); - repo.done(); - }); + assertThatThrownBy(() -> { + execute(context -> { + NewRepository repo = context.createRepository("fake", "java"); + createRule(repo, "newKey1"); + createRule(repo, "newKey1"); + repo.done(); + }); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("The rule 'newKey1' of repository 'fake' is declared several times"); } private void execute(RulesDefinition... defs) { diff --git a/server/sonar-webserver-core/src/test/java/org/sonar/server/search/BaseDocTest.java b/server/sonar-webserver-core/src/test/java/org/sonar/server/search/BaseDocTest.java index 73de32ba141..db2094a43c4 100644 --- a/server/sonar-webserver-core/src/test/java/org/sonar/server/search/BaseDocTest.java +++ b/server/sonar-webserver-core/src/test/java/org/sonar/server/search/BaseDocTest.java @@ -24,22 +24,19 @@ import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Map; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.server.es.BaseDoc; import org.sonar.server.es.EsUtils; import org.sonar.server.es.Index; import org.sonar.server.es.IndexType; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.fail; public class BaseDocTest { private final IndexType.IndexMainType someType = IndexType.main(Index.simple("bar"), "donut"); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void getField() { @@ -128,10 +125,9 @@ public class BaseDocTest { }; - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("parent must be set on a doc associated to a IndexRelationType (see BaseDoc#setParent(String))"); - - doc.getFields(); + assertThatThrownBy(() -> doc.getFields()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("parent must be set on a doc associated to a IndexRelationType (see BaseDoc#setParent(String))"); } @Test diff --git a/server/sonar-webserver-core/src/test/java/org/sonar/server/startup/GeneratePluginIndexTest.java b/server/sonar-webserver-core/src/test/java/org/sonar/server/startup/GeneratePluginIndexTest.java index 9bb6a6dc0f2..b9d21f2ad39 100644 --- a/server/sonar-webserver-core/src/test/java/org/sonar/server/startup/GeneratePluginIndexTest.java +++ b/server/sonar-webserver-core/src/test/java/org/sonar/server/startup/GeneratePluginIndexTest.java @@ -35,6 +35,7 @@ import org.sonar.server.plugins.ServerPluginRepository; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.server.plugins.PluginType.BUNDLED; @@ -71,14 +72,15 @@ public class GeneratePluginIndexTest { underTest.stop(); } - @Test(expected = IllegalStateException.class) + @Test public void shouldThrowWhenUnableToWrite() throws IOException { File wrongParent = temp.newFile(); wrongParent.createNewFile(); File wrongIndex = new File(wrongParent, "index.txt"); when(serverFileSystem.getPluginIndex()).thenReturn(wrongIndex); - new GeneratePluginIndex(serverFileSystem, serverPluginRepository).start(); + assertThatThrownBy(() -> new GeneratePluginIndex(serverFileSystem, serverPluginRepository).start()) + .isInstanceOf(IllegalStateException.class); } private ServerPlugin newInstalledPlugin(String key, boolean supportSonarLint) throws IOException { diff --git a/server/sonar-webserver-core/src/test/java/org/sonar/server/startup/RegisterMetricsTest.java b/server/sonar-webserver-core/src/test/java/org/sonar/server/startup/RegisterMetricsTest.java index aebccfc0a3f..7d459119fdb 100644 --- a/server/sonar-webserver-core/src/test/java/org/sonar/server/startup/RegisterMetricsTest.java +++ b/server/sonar-webserver-core/src/test/java/org/sonar/server/startup/RegisterMetricsTest.java @@ -38,6 +38,7 @@ import org.sonar.db.metric.MetricDto; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.core.util.stream.MoreCollectors.uniqueIndex; public class RegisterMetricsTest { @@ -140,19 +141,21 @@ public class RegisterMetricsTest { assertThat(dbTester.countRowsOfTable("metrics")).isEqualTo(CoreMetrics.getMetrics().size()); } - @Test(expected = IllegalStateException.class) + @Test public void fail_if_duplicated_plugin_metrics() { Metrics plugin1 = new TestMetrics(new Metric.Builder("m1", "In first plugin", Metric.ValueType.FLOAT).create()); Metrics plugin2 = new TestMetrics(new Metric.Builder("m1", "In second plugin", Metric.ValueType.FLOAT).create()); - new RegisterMetrics(dbClient, uuidFactory, new Metrics[] {plugin1, plugin2}).start(); + assertThatThrownBy(() -> new RegisterMetrics(dbClient, uuidFactory, new Metrics[] {plugin1, plugin2}).start()) + .isInstanceOf(IllegalStateException.class); } - @Test(expected = IllegalStateException.class) + @Test public void fail_if_plugin_duplicates_core_metric() { Metrics plugin = new TestMetrics(new Metric.Builder("ncloc", "In plugin", Metric.ValueType.FLOAT).create()); - new RegisterMetrics(dbClient, uuidFactory, new Metrics[] {plugin}).start(); + assertThatThrownBy(() -> new RegisterMetrics(dbClient, uuidFactory, new Metrics[] {plugin}).start()) + .isInstanceOf(IllegalStateException.class); } private static class TestMetrics implements Metrics { diff --git a/server/sonar-webserver-core/src/test/java/org/sonar/server/startup/RegisterPermissionTemplatesTest.java b/server/sonar-webserver-core/src/test/java/org/sonar/server/startup/RegisterPermissionTemplatesTest.java index da21ea3c1f4..cf76cb55e30 100644 --- a/server/sonar-webserver-core/src/test/java/org/sonar/server/startup/RegisterPermissionTemplatesTest.java +++ b/server/sonar-webserver-core/src/test/java/org/sonar/server/startup/RegisterPermissionTemplatesTest.java @@ -24,7 +24,6 @@ import java.util.Objects; import java.util.Optional; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.security.DefaultGroups; import org.sonar.api.utils.System2; import org.sonar.api.utils.log.LogTester; @@ -48,8 +47,6 @@ public class RegisterPermissionTemplatesTest { public DbTester db = DbTester.create(System2.INSTANCE); @Rule public LogTester logTester = new LogTester(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private RegisterPermissionTemplates underTest = new RegisterPermissionTemplates(db.getDbClient(), UuidFactoryFast.getInstance(), System2.INSTANCE, new DefaultGroupFinder(db.getDbClient())); diff --git a/server/sonar-webserver-es/src/test/java/org/sonar/server/es/IndexCreatorTest.java b/server/sonar-webserver-es/src/test/java/org/sonar/server/es/IndexCreatorTest.java index 428d45f897c..09130fbe76a 100644 --- a/server/sonar-webserver-es/src/test/java/org/sonar/server/es/IndexCreatorTest.java +++ b/server/sonar-webserver-es/src/test/java/org/sonar/server/es/IndexCreatorTest.java @@ -35,7 +35,6 @@ import org.elasticsearch.common.collect.ImmutableOpenMap; import org.elasticsearch.common.settings.Settings; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.utils.log.LogTester; import org.sonar.api.utils.log.LoggerLevel; @@ -48,6 +47,7 @@ import org.sonar.server.es.newindex.SettingsConfiguration; import org.sonar.server.platform.db.migration.es.MigrationEsClient; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.server.es.IndexType.main; @@ -62,8 +62,6 @@ public class IndexCreatorTest { @Rule public LogTester logTester = new LogTester(); @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Rule public EsTester es = EsTester.createCustom(); private MetadataIndexDefinition metadataIndexDefinition = new MetadataIndexDefinition(new MapSettings().asConfig()); @@ -124,10 +122,9 @@ public class IndexCreatorTest { run(new FakeIndexDefinition()); // v2 - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Blue/green deployment is not supported. Elasticsearch index [fakes] changed and needs to be dropped."); - - run(new FakeIndexDefinitionV2()); + assertThatThrownBy(() -> run(new FakeIndexDefinitionV2())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Blue/green deployment is not supported. Elasticsearch index [fakes] changed and needs to be dropped."); } @Test diff --git a/server/sonar-webserver-es/src/test/java/org/sonar/server/es/metadata/EsDbCompatibilityImplTest.java b/server/sonar-webserver-es/src/test/java/org/sonar/server/es/metadata/EsDbCompatibilityImplTest.java index d10509121ed..7c4467f1c46 100644 --- a/server/sonar-webserver-es/src/test/java/org/sonar/server/es/metadata/EsDbCompatibilityImplTest.java +++ b/server/sonar-webserver-es/src/test/java/org/sonar/server/es/metadata/EsDbCompatibilityImplTest.java @@ -23,9 +23,7 @@ import java.util.HashMap; import java.util.Map; import java.util.Optional; import javax.annotation.CheckForNull; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.Mockito; import org.sonar.db.DbClient; import org.sonar.server.es.Index; @@ -42,8 +40,6 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class EsDbCompatibilityImplTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private DbClient dbClient = mock(DbClient.class, Mockito.RETURNS_DEEP_STUBS); private MetadataIndex metadataIndex = spy(new TestMetadataIndex()); diff --git a/server/sonar-webserver-es/src/test/java/org/sonar/server/issue/index/IssueIndexFacetsTest.java b/server/sonar-webserver-es/src/test/java/org/sonar/server/issue/index/IssueIndexFacetsTest.java index cb779d27eca..23c526e0e4f 100644 --- a/server/sonar-webserver-es/src/test/java/org/sonar/server/issue/index/IssueIndexFacetsTest.java +++ b/server/sonar-webserver-es/src/test/java/org/sonar/server/issue/index/IssueIndexFacetsTest.java @@ -26,7 +26,6 @@ import java.util.TimeZone; import org.elasticsearch.action.search.SearchResponse; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.impl.utils.TestSystem2; import org.sonar.api.rules.RuleType; import org.sonar.api.utils.System2; @@ -50,7 +49,6 @@ import static java.util.stream.Collectors.toList; import static java.util.stream.IntStream.rangeClosed; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.entry; -import static org.junit.rules.ExpectedException.none; import static org.sonar.api.issue.Issue.RESOLUTION_FALSE_POSITIVE; import static org.sonar.api.issue.Issue.RESOLUTION_FIXED; import static org.sonar.api.issue.Issue.RESOLUTION_REMOVED; @@ -79,8 +77,6 @@ public class IssueIndexFacetsTest { public EsTester es = EsTester.create(); @Rule public UserSessionRule userSessionRule = UserSessionRule.standalone(); - @Rule - public ExpectedException expectedException = none(); private final TimeZone defaultTimezone = getTimeZone("GMT-01:00"); private System2 system2 = new TestSystem2().setNow(1_500_000_000_000L).setDefaultTimeZone(defaultTimezone); @Rule diff --git a/server/sonar-webserver-es/src/test/java/org/sonar/server/issue/index/IssueIndexFiltersTest.java b/server/sonar-webserver-es/src/test/java/org/sonar/server/issue/index/IssueIndexFiltersTest.java index 26b2f8f1faa..d03c3b9fe3e 100644 --- a/server/sonar-webserver-es/src/test/java/org/sonar/server/issue/index/IssueIndexFiltersTest.java +++ b/server/sonar-webserver-es/src/test/java/org/sonar/server/issue/index/IssueIndexFiltersTest.java @@ -28,7 +28,6 @@ import org.assertj.core.api.Fail; import org.elasticsearch.search.SearchHit; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.impl.utils.TestSystem2; import org.sonar.api.issue.Issue; import org.sonar.api.rule.Severity; @@ -54,7 +53,7 @@ import static java.util.Collections.singletonList; import static java.util.TimeZone.getTimeZone; import static java.util.stream.Collectors.toList; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.rules.ExpectedException.none; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.resources.Qualifiers.APP; import static org.sonar.api.resources.Qualifiers.PROJECT; import static org.sonar.api.utils.DateUtils.addDays; @@ -72,8 +71,6 @@ public class IssueIndexFiltersTest { public EsTester es = EsTester.create(); @Rule public UserSessionRule userSessionRule = UserSessionRule.standalone(); - @Rule - public ExpectedException expectedException = none(); private final System2 system2 = new TestSystem2().setNow(1_500_000_000_000L).setDefaultTimeZone(getTimeZone("GMT-01:00")); @Rule public DbTester db = DbTester.create(system2); @@ -428,20 +425,20 @@ public class IssueIndexFiltersTest { // Search for issues of project 1 having less than 15 days assertThatSearchReturnsOnly(IssueQuery.builder() - .createdAfterByProjectUuids(ImmutableMap.of(project1.uuid(), new IssueQuery.PeriodStart(addDays(now, -15), true))), + .createdAfterByProjectUuids(ImmutableMap.of(project1.uuid(), new IssueQuery.PeriodStart(addDays(now, -15), true))), project1Issue1.key()); // Search for issues of project 1 having less than 14 days and project 2 having less then 25 days assertThatSearchReturnsOnly(IssueQuery.builder() - .createdAfterByProjectUuids(ImmutableMap.of( - project1.uuid(), new IssueQuery.PeriodStart(addDays(now, -14), true), - project2.uuid(), new IssueQuery.PeriodStart(addDays(now, -25), true))), + .createdAfterByProjectUuids(ImmutableMap.of( + project1.uuid(), new IssueQuery.PeriodStart(addDays(now, -14), true), + project2.uuid(), new IssueQuery.PeriodStart(addDays(now, -25), true))), project1Issue1.key(), project2Issue1.key()); // Search for issues of project 1 having less than 30 days assertThatSearchReturnsOnly(IssueQuery.builder() - .createdAfterByProjectUuids(ImmutableMap.of( - project1.uuid(), new IssueQuery.PeriodStart(addDays(now, -30), true))), + .createdAfterByProjectUuids(ImmutableMap.of( + project1.uuid(), new IssueQuery.PeriodStart(addDays(now, -30), true))), project1Issue1.key(), project1Issue2.key()); // Search for issues of project 1 and project 2 having less than 5 days @@ -477,23 +474,23 @@ public class IssueIndexFiltersTest { // Search for issues of project 1 branch 1 having less than 15 days assertThatSearchReturnsOnly(IssueQuery.builder() - .mainBranch(false) - .createdAfterByProjectUuids(ImmutableMap.of(project1Branch1.uuid(), new IssueQuery.PeriodStart(addDays(now, -15), true))), + .mainBranch(false) + .createdAfterByProjectUuids(ImmutableMap.of(project1Branch1.uuid(), new IssueQuery.PeriodStart(addDays(now, -15), true))), project1Branch1Issue1.key()); // Search for issues of project 1 branch 1 having less than 14 days and project 2 branch 1 having less then 25 days assertThatSearchReturnsOnly(IssueQuery.builder() - .mainBranch(false) - .createdAfterByProjectUuids(ImmutableMap.of( - project1Branch1.uuid(), new IssueQuery.PeriodStart(addDays(now, -14), true), - project2Branch1.uuid(), new IssueQuery.PeriodStart(addDays(now, -25), true))), + .mainBranch(false) + .createdAfterByProjectUuids(ImmutableMap.of( + project1Branch1.uuid(), new IssueQuery.PeriodStart(addDays(now, -14), true), + project2Branch1.uuid(), new IssueQuery.PeriodStart(addDays(now, -25), true))), project1Branch1Issue1.key(), project2Branch1Issue1.key()); // Search for issues of project 1 branch 1 having less than 30 days assertThatSearchReturnsOnly(IssueQuery.builder() - .mainBranch(false) - .createdAfterByProjectUuids(ImmutableMap.of( - project1Branch1.uuid(), new IssueQuery.PeriodStart(addDays(now, -30), true))), + .mainBranch(false) + .createdAfterByProjectUuids(ImmutableMap.of( + project1Branch1.uuid(), new IssueQuery.PeriodStart(addDays(now, -30), true))), project1Branch1Issue1.key(), project1Branch1Issue2.key()); // Search for issues of project 1 branch 1 and project 2 branch 2 having less than 5 days @@ -698,10 +695,10 @@ public class IssueIndexFiltersTest { .createdAfter(parseDate("2014-09-19")).createdBefore(parseDate("2014-09-21")), "I1"); // 20 < createdAt < 20: exception - expectedException.expect(IllegalArgumentException.class); - underTest.search(IssueQuery.builder() + assertThatThrownBy(() -> underTest.search(IssueQuery.builder() .createdAfter(parseDate("2014-09-20")).createdBefore(parseDate("2014-09-20")) - .build(), new SearchOptions()); + .build(), new SearchOptions())) + .isInstanceOf(IllegalArgumentException.class); } @Test @@ -732,10 +729,10 @@ public class IssueIndexFiltersTest { @Test public void fail_if_created_before_equals_created_after() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Start bound cannot be larger or equal to end bound"); - - underTest.search(IssueQuery.builder().createdAfter(parseDate("2014-09-20")).createdBefore(parseDate("2014-09-20")).build(), new SearchOptions()); + assertThatThrownBy(() -> underTest.search(IssueQuery.builder().createdAfter(parseDate("2014-09-20")) + .createdBefore(parseDate("2014-09-20")).build(), new SearchOptions())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Start bound cannot be larger or equal to end bound"); } @Test diff --git a/server/sonar-webserver-es/src/test/java/org/sonar/server/issue/index/IssueIndexSecurityHotspotsTest.java b/server/sonar-webserver-es/src/test/java/org/sonar/server/issue/index/IssueIndexSecurityHotspotsTest.java index 645e95dc87f..d6cfe7717a4 100644 --- a/server/sonar-webserver-es/src/test/java/org/sonar/server/issue/index/IssueIndexSecurityHotspotsTest.java +++ b/server/sonar-webserver-es/src/test/java/org/sonar/server/issue/index/IssueIndexSecurityHotspotsTest.java @@ -27,7 +27,6 @@ import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.search.SearchHit; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.impl.utils.TestSystem2; import org.sonar.api.rule.Severity; import org.sonar.api.utils.System2; @@ -48,7 +47,6 @@ import static java.util.TimeZone.getTimeZone; import static java.util.stream.Collectors.toList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.entry; -import static org.junit.rules.ExpectedException.none; import static org.sonar.api.resources.Qualifiers.PROJECT; import static org.sonar.api.rule.Severity.INFO; import static org.sonar.api.rule.Severity.MAJOR; @@ -66,8 +64,6 @@ public class IssueIndexSecurityHotspotsTest { public EsTester es = EsTester.create(); @Rule public UserSessionRule userSessionRule = UserSessionRule.standalone(); - @Rule - public ExpectedException expectedException = none(); private System2 system2 = new TestSystem2().setNow(1_500_000_000_000L).setDefaultTimeZone(getTimeZone("GMT-01:00")); @Rule public DbTester db = DbTester.create(system2); diff --git a/server/sonar-webserver-es/src/test/java/org/sonar/server/issue/index/IssueIndexSecurityReportsTest.java b/server/sonar-webserver-es/src/test/java/org/sonar/server/issue/index/IssueIndexSecurityReportsTest.java index eaf2b49080d..08724047fb4 100644 --- a/server/sonar-webserver-es/src/test/java/org/sonar/server/issue/index/IssueIndexSecurityReportsTest.java +++ b/server/sonar-webserver-es/src/test/java/org/sonar/server/issue/index/IssueIndexSecurityReportsTest.java @@ -23,10 +23,8 @@ import java.util.List; import java.util.Map; import java.util.OptionalInt; import java.util.stream.Collectors; - import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.impl.utils.TestSystem2; import org.sonar.api.issue.Issue; import org.sonar.api.rule.Severity; @@ -49,7 +47,6 @@ import static java.util.TimeZone.getTimeZone; import static java.util.stream.Collectors.toList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.tuple; -import static org.junit.rules.ExpectedException.none; import static org.sonar.api.resources.Qualifiers.PROJECT; import static org.sonar.db.component.ComponentTesting.newPrivateProjectDto; import static org.sonar.server.issue.IssueDocTesting.newDoc; @@ -64,8 +61,6 @@ public class IssueIndexSecurityReportsTest { public EsTester es = EsTester.create(); @Rule public UserSessionRule userSessionRule = UserSessionRule.standalone(); - @Rule - public ExpectedException expectedException = none(); private System2 system2 = new TestSystem2().setNow(1_500_000_000_000L).setDefaultTimeZone(getTimeZone("GMT-01:00")); @Rule public DbTester db = DbTester.create(system2); diff --git a/server/sonar-webserver-es/src/test/java/org/sonar/server/issue/index/IssueIndexSortTest.java b/server/sonar-webserver-es/src/test/java/org/sonar/server/issue/index/IssueIndexSortTest.java index 0dfdbfb9987..18b89e03804 100644 --- a/server/sonar-webserver-es/src/test/java/org/sonar/server/issue/index/IssueIndexSortTest.java +++ b/server/sonar-webserver-es/src/test/java/org/sonar/server/issue/index/IssueIndexSortTest.java @@ -26,7 +26,6 @@ import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.search.SearchHit; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.impl.utils.TestSystem2; import org.sonar.api.issue.Issue; import org.sonar.api.rule.Severity; @@ -45,7 +44,6 @@ import static java.util.Arrays.stream; import static java.util.TimeZone.getTimeZone; import static java.util.stream.Collectors.toList; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.rules.ExpectedException.none; import static org.mockito.Mockito.mock; import static org.sonar.api.resources.Qualifiers.PROJECT; import static org.sonar.api.utils.DateUtils.parseDateTime; @@ -59,8 +57,6 @@ public class IssueIndexSortTest { public EsTester es = EsTester.create(); @Rule public UserSessionRule userSessionRule = UserSessionRule.standalone(); - @Rule - public ExpectedException expectedException = none(); private final System2 system2 = new TestSystem2().setNow(1_500_000_000_000L).setDefaultTimeZone(getTimeZone("GMT-01:00")); @Rule public DbTester db = DbTester.create(system2); diff --git a/server/sonar-webserver-es/src/test/java/org/sonar/server/issue/index/IssueIndexTest.java b/server/sonar-webserver-es/src/test/java/org/sonar/server/issue/index/IssueIndexTest.java index 95124161328..4e2e4d43053 100644 --- a/server/sonar-webserver-es/src/test/java/org/sonar/server/issue/index/IssueIndexTest.java +++ b/server/sonar-webserver-es/src/test/java/org/sonar/server/issue/index/IssueIndexTest.java @@ -21,22 +21,18 @@ package org.sonar.server.issue.index; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterators; - import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; - import org.apache.lucene.search.TotalHits; import org.apache.lucene.search.TotalHits.Relation; import org.assertj.core.groups.Tuple; import org.elasticsearch.action.search.SearchResponse; -import org.elasticsearch.common.document.DocumentField; import org.elasticsearch.search.SearchHit; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.impl.utils.TestSystem2; import org.sonar.api.issue.Issue; import org.sonar.api.utils.System2; @@ -63,7 +59,6 @@ import static java.util.stream.Collectors.toList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.entry; import static org.assertj.core.api.Assertions.tuple; -import static org.junit.rules.ExpectedException.none; import static org.mockito.Mockito.mock; import static org.sonar.api.issue.Issue.RESOLUTION_FIXED; import static org.sonar.api.resources.Qualifiers.PROJECT; @@ -82,8 +77,6 @@ public class IssueIndexTest { public EsTester es = EsTester.create(); @Rule public UserSessionRule userSessionRule = UserSessionRule.standalone(); - @Rule - public ExpectedException expectedException = none(); private final System2 system2 = new TestSystem2().setNow(1_500_000_000_000L).setDefaultTimeZone(getTimeZone("GMT-01:00")); @Rule public DbTester db = DbTester.create(system2); diff --git a/server/sonar-webserver-es/src/test/java/org/sonar/server/issue/index/IssueQueryFactoryTest.java b/server/sonar-webserver-es/src/test/java/org/sonar/server/issue/index/IssueQueryFactoryTest.java index 97844486643..eba149036e2 100644 --- a/server/sonar-webserver-es/src/test/java/org/sonar/server/issue/index/IssueQueryFactoryTest.java +++ b/server/sonar-webserver-es/src/test/java/org/sonar/server/issue/index/IssueQueryFactoryTest.java @@ -28,7 +28,6 @@ import java.util.Date; import java.util.Map; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.resources.Qualifiers; import org.sonar.api.rule.RuleKey; import org.sonar.db.DbTester; @@ -43,6 +42,7 @@ import org.sonar.server.tester.UserSessionRule; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; @@ -63,8 +63,6 @@ public class IssueQueryFactoryTest { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Rule public DbTester db = DbTester.create(); private final RuleDbTester ruleDbTester = new RuleDbTester(db); @@ -257,10 +255,9 @@ public class IssueQueryFactoryTest { .setComponents(singletonList("foo")) .setComponentUuids(singletonList("bar")); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("At most one of the following parameters can be provided: componentKeys and componentUuids"); - - underTest.create(request); + assertThatThrownBy(() -> underTest.create(request)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("At most one of the following parameters can be provided: componentKeys and componentUuids"); } @Test @@ -268,10 +265,9 @@ public class IssueQueryFactoryTest { SearchRequest request = new SearchRequest() .setTimeZone("Poitou-Charentes"); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("TimeZone 'Poitou-Charentes' cannot be parsed as a valid zone ID"); - - underTest.create(request); + assertThatThrownBy(() -> underTest.create(request)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("TimeZone 'Poitou-Charentes' cannot be parsed as a valid zone ID"); } @Test @@ -421,14 +417,14 @@ public class IssueQueryFactoryTest { assertThat(underTest.create(new SearchRequest() .setProjects(singletonList(branch.getKey())) .setBranch(branch.getBranch()))) - .extracting(IssueQuery::branchUuid, query -> new ArrayList<>(query.projectUuids()), IssueQuery::isMainBranch) - .containsOnly(branch.uuid(), singletonList(project.uuid()), false); + .extracting(IssueQuery::branchUuid, query -> new ArrayList<>(query.projectUuids()), IssueQuery::isMainBranch) + .containsOnly(branch.uuid(), singletonList(project.uuid()), false); assertThat(underTest.create(new SearchRequest() .setComponents(singletonList(branch.getKey())) .setBranch(branch.getBranch()))) - .extracting(IssueQuery::branchUuid, query -> new ArrayList<>(query.projectUuids()), IssueQuery::isMainBranch) - .containsOnly(branch.uuid(), singletonList(project.uuid()), false); + .extracting(IssueQuery::branchUuid, query -> new ArrayList<>(query.projectUuids()), IssueQuery::isMainBranch) + .containsOnly(branch.uuid(), singletonList(project.uuid()), false); } @Test @@ -440,22 +436,22 @@ public class IssueQueryFactoryTest { assertThat(underTest.create(new SearchRequest() .setComponents(singletonList(file.getKey())) .setBranch(branch.getBranch()))) - .extracting(IssueQuery::branchUuid, query -> new ArrayList<>(query.componentUuids()), IssueQuery::isMainBranch) - .containsOnly(branch.uuid(), singletonList(file.uuid()), false); + .extracting(IssueQuery::branchUuid, query -> new ArrayList<>(query.componentUuids()), IssueQuery::isMainBranch) + .containsOnly(branch.uuid(), singletonList(file.uuid()), false); assertThat(underTest.create(new SearchRequest() .setComponents(singletonList(branch.getKey())) .setFiles(singletonList(file.path())) .setBranch(branch.getBranch()))) - .extracting(IssueQuery::branchUuid, query -> new ArrayList<>(query.files()), IssueQuery::isMainBranch) - .containsOnly(branch.uuid(), singletonList(file.path()), false); + .extracting(IssueQuery::branchUuid, query -> new ArrayList<>(query.files()), IssueQuery::isMainBranch) + .containsOnly(branch.uuid(), singletonList(file.path()), false); assertThat(underTest.create(new SearchRequest() .setProjects(singletonList(branch.getKey())) .setFiles(singletonList(file.path())) .setBranch(branch.getBranch()))) - .extracting(IssueQuery::branchUuid, query -> new ArrayList<>(query.files()), IssueQuery::isMainBranch) - .containsOnly(branch.uuid(), singletonList(file.path()), false); + .extracting(IssueQuery::branchUuid, query -> new ArrayList<>(query.files()), IssueQuery::isMainBranch) + .containsOnly(branch.uuid(), singletonList(file.path()), false); } @Test @@ -468,8 +464,8 @@ public class IssueQueryFactoryTest { .setComponents(singletonList(file.getKey())) .setBranch(branch.getBranch()) .setOnComponentOnly(true))) - .extracting(IssueQuery::branchUuid, query -> new ArrayList<>(query.componentUuids()), IssueQuery::isMainBranch) - .containsOnly(branch.uuid(), singletonList(file.uuid()), false); + .extracting(IssueQuery::branchUuid, query -> new ArrayList<>(query.componentUuids()), IssueQuery::isMainBranch) + .containsOnly(branch.uuid(), singletonList(file.uuid()), false); } @Test @@ -480,13 +476,13 @@ public class IssueQueryFactoryTest { assertThat(underTest.create(new SearchRequest() .setProjects(singletonList(project.getKey())) .setBranch("master"))) - .extracting(IssueQuery::branchUuid, query -> new ArrayList<>(query.projectUuids()), IssueQuery::isMainBranch) - .containsOnly(project.uuid(), singletonList(project.uuid()), true); + .extracting(IssueQuery::branchUuid, query -> new ArrayList<>(query.projectUuids()), IssueQuery::isMainBranch) + .containsOnly(project.uuid(), singletonList(project.uuid()), true); assertThat(underTest.create(new SearchRequest() .setComponents(singletonList(project.getKey())) .setBranch("master"))) - .extracting(IssueQuery::branchUuid, query -> new ArrayList<>(query.projectUuids()), IssueQuery::isMainBranch) - .containsOnly(project.uuid(), singletonList(project.uuid()), true); + .extracting(IssueQuery::branchUuid, query -> new ArrayList<>(query.projectUuids()), IssueQuery::isMainBranch) + .containsOnly(project.uuid(), singletonList(project.uuid()), true); } @Test @@ -499,7 +495,7 @@ public class IssueQueryFactoryTest { userSession.addProjectPermission(USER, application); assertThat(underTest.create(new SearchRequest() - .setComponents(singletonList(application.getKey()))) + .setComponents(singletonList(application.getKey()))) .viewUuids()).containsExactly(application.uuid()); } @@ -521,16 +517,16 @@ public class IssueQueryFactoryTest { assertThat(underTest.create(new SearchRequest() .setComponents(singletonList(applicationBranch1.getKey())) .setBranch(applicationBranch1.getBranch()))) - .extracting(IssueQuery::branchUuid, query -> new ArrayList<>(query.projectUuids()), IssueQuery::isMainBranch) - .containsOnly(applicationBranch1.uuid(), Collections.emptyList(), false); + .extracting(IssueQuery::branchUuid, query -> new ArrayList<>(query.projectUuids()), IssueQuery::isMainBranch) + .containsOnly(applicationBranch1.uuid(), Collections.emptyList(), false); // Search on project1Branch1 assertThat(underTest.create(new SearchRequest() .setComponents(singletonList(applicationBranch1.getKey())) .setProjects(singletonList(project1.getKey())) .setBranch(applicationBranch1.getBranch()))) - .extracting(IssueQuery::branchUuid, query -> new ArrayList<>(query.projectUuids()), IssueQuery::isMainBranch) - .containsOnly(applicationBranch1.uuid(), singletonList(project1.uuid()), false); + .extracting(IssueQuery::branchUuid, query -> new ArrayList<>(query.projectUuids()), IssueQuery::isMainBranch) + .containsOnly(applicationBranch1.uuid(), singletonList(project1.uuid()), false); } @Test @@ -561,20 +557,18 @@ public class IssueQueryFactoryTest { @Test public void fail_if_since_leak_period_and_created_after_set_at_the_same_time() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Parameters 'createdAfter' and 'sinceLeakPeriod' cannot be set simultaneously"); - - underTest.create(new SearchRequest() + assertThatThrownBy(() -> underTest.create(new SearchRequest() .setSinceLeakPeriod(true) - .setCreatedAfter("2013-07-25T07:35:00+0100")); + .setCreatedAfter("2013-07-25T07:35:00+0100"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Parameters 'createdAfter' and 'sinceLeakPeriod' cannot be set simultaneously"); } @Test public void fail_if_no_component_provided_with_since_leak_period() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("One and only one component must be provided when searching since leak period"); - - underTest.create(new SearchRequest().setSinceLeakPeriod(true)); + assertThatThrownBy(() -> underTest.create(new SearchRequest().setSinceLeakPeriod(true))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("One and only one component must be provided when searching since leak period"); } @Test @@ -582,21 +576,19 @@ public class IssueQueryFactoryTest { ComponentDto project1 = db.components().insertPrivateProject(); ComponentDto project2 = db.components().insertPrivateProject(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("One and only one component must be provided when searching since leak period"); - - underTest.create(new SearchRequest() + assertThatThrownBy(() -> underTest.create(new SearchRequest() .setSinceLeakPeriod(true) - .setComponents(asList(project1.getKey(), project2.getKey()))); + .setComponents(asList(project1.getKey(), project2.getKey())))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("One and only one component must be provided when searching since leak period"); } @Test public void fail_if_date_is_not_formatted_correctly() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("'unknown-date' cannot be parsed as either a date or date+time"); - - underTest.create(new SearchRequest() - .setCreatedAfter("unknown-date")); + assertThatThrownBy(() -> underTest.create(new SearchRequest() + .setCreatedAfter("unknown-date"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("'unknown-date' cannot be parsed as either a date or date+time"); } } diff --git a/server/sonar-webserver-es/src/test/java/org/sonar/server/measure/index/ProjectMeasuresIndexTest.java b/server/sonar-webserver-es/src/test/java/org/sonar/server/measure/index/ProjectMeasuresIndexTest.java index 4510f12b08d..7681d78b0b8 100644 --- a/server/sonar-webserver-es/src/test/java/org/sonar/server/measure/index/ProjectMeasuresIndexTest.java +++ b/server/sonar-webserver-es/src/test/java/org/sonar/server/measure/index/ProjectMeasuresIndexTest.java @@ -32,7 +32,6 @@ import java.util.Map; import java.util.stream.IntStream; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.api.utils.System2; import org.sonar.db.component.ComponentDto; @@ -56,6 +55,7 @@ import static java.util.Arrays.stream; import static java.util.Collections.singletonList; import static java.util.stream.Collectors.toList; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.entry; import static org.sonar.api.measures.CoreMetrics.ALERT_STATUS_KEY; import static org.sonar.api.measures.CoreMetrics.COVERAGE_KEY; @@ -107,8 +107,6 @@ public class ProjectMeasuresIndexTest { @Rule public EsTester es = EsTester.create(); @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @DataProvider @@ -1686,19 +1684,17 @@ public class ProjectMeasuresIndexTest { } @Test - public void fail_if_page_size_greater_than_500() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Page size must be lower than or equals to 100"); - - underTest.searchTags("whatever", 1, 101); + public void fail_if_page_size_greater_than_100() { + assertThatThrownBy(() -> underTest.searchTags("whatever", 1, 101)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Page size must be lower than or equals to 100"); } @Test public void fail_if_page_greater_than_20() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Page must be between 0 and 20"); - - underTest.searchTags("whatever", 21, 100); + assertThatThrownBy(() -> underTest.searchTags("whatever", 21, 100)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Page must be between 0 and 20"); } private void index(ProjectMeasuresDoc... docs) { diff --git a/server/sonar-webserver-es/src/test/java/org/sonar/server/measure/index/ProjectMeasuresIndexTextSearchTest.java b/server/sonar-webserver-es/src/test/java/org/sonar/server/measure/index/ProjectMeasuresIndexTextSearchTest.java index a3c231f8eaf..a5e2b71ee4d 100644 --- a/server/sonar-webserver-es/src/test/java/org/sonar/server/measure/index/ProjectMeasuresIndexTextSearchTest.java +++ b/server/sonar-webserver-es/src/test/java/org/sonar/server/measure/index/ProjectMeasuresIndexTextSearchTest.java @@ -24,7 +24,6 @@ import java.util.List; import java.util.Map; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.utils.System2; import org.sonar.db.component.ComponentDto; import org.sonar.server.es.EsTester; @@ -55,8 +54,6 @@ public class ProjectMeasuresIndexTextSearchTest { @Rule public EsTester es = EsTester.create(); @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Rule public UserSessionRule userSession = UserSessionRule.standalone(); private ProjectMeasuresIndexer projectMeasureIndexer = new ProjectMeasuresIndexer(null, es.client()); diff --git a/server/sonar-webserver-es/src/test/java/org/sonar/server/measure/index/ProjectMeasuresQueryTest.java b/server/sonar-webserver-es/src/test/java/org/sonar/server/measure/index/ProjectMeasuresQueryTest.java index f4b4ef1480e..f72695ad6f5 100644 --- a/server/sonar-webserver-es/src/test/java/org/sonar/server/measure/index/ProjectMeasuresQueryTest.java +++ b/server/sonar-webserver-es/src/test/java/org/sonar/server/measure/index/ProjectMeasuresQueryTest.java @@ -19,22 +19,18 @@ */ package org.sonar.server.measure.index; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.measures.Metric.Level; import org.sonar.server.measure.index.ProjectMeasuresQuery.MetricCriterion; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.groups.Tuple.tuple; import static org.sonar.api.measures.Metric.Level.OK; import static org.sonar.server.measure.index.ProjectMeasuresQuery.Operator.EQ; public class ProjectMeasuresQueryTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); - private ProjectMeasuresQuery underTest = new ProjectMeasuresQuery(); @Test @@ -84,25 +80,22 @@ public class ProjectMeasuresQueryTest { @Test public void fail_to_set_null_sort() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("Sort cannot be null"); - - underTest.setSort(null); + assertThatThrownBy(() -> underTest.setSort(null)) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("Sort cannot be null"); } @Test public void fail_to_get_value_when_no_data() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("The criterion for metric coverage has no data"); - - MetricCriterion.createNoData("coverage").getValue(); + assertThatThrownBy(() -> MetricCriterion.createNoData("coverage").getValue()) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("The criterion for metric coverage has no data"); } @Test public void fail_to_get_operator_when_no_data() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("The criterion for metric coverage has no data"); - - MetricCriterion.createNoData("coverage").getOperator(); + assertThatThrownBy(() -> MetricCriterion.createNoData("coverage").getOperator()) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("The criterion for metric coverage has no data"); } } diff --git a/server/sonar-webserver-es/src/test/java/org/sonar/server/permission/index/PermissionIndexerTest.java b/server/sonar-webserver-es/src/test/java/org/sonar/server/permission/index/PermissionIndexerTest.java index 20fb3bf8fb9..dc1e577f9ac 100644 --- a/server/sonar-webserver-es/src/test/java/org/sonar/server/permission/index/PermissionIndexerTest.java +++ b/server/sonar-webserver-es/src/test/java/org/sonar/server/permission/index/PermissionIndexerTest.java @@ -22,7 +22,6 @@ package org.sonar.server.permission.index; import java.util.Collection; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.utils.System2; import org.sonar.db.DbSession; import org.sonar.db.DbTester; @@ -50,8 +49,6 @@ public class PermissionIndexerTest { private static final IndexMainType INDEX_TYPE_FOO_AUTH = IndexType.main(FooIndexDefinition.DESCRIPTOR, TYPE_AUTHORIZATION); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester db = DbTester.create(System2.INSTANCE); @Rule diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almintegration/ws/SetPatActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almintegration/ws/SetPatActionTest.java index 556a2970c60..08cce9c1adf 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almintegration/ws/SetPatActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almintegration/ws/SetPatActionTest.java @@ -22,7 +22,6 @@ package org.sonar.server.almintegration.ws; import java.util.Optional; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbTester; import org.sonar.db.alm.pat.AlmPatDto; @@ -36,13 +35,12 @@ import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.db.permission.GlobalPermission.PROVISION_PROJECTS; public class SetPatActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -151,13 +149,14 @@ public class SetPatActionTest { AlmSettingDto almSetting = db.almSettings().insertBitbucketCloudAlmSetting(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Username cannot be null for Bitbucket Cloud"); - - ws.newRequest() - .setParam("almSetting", almSetting.getKey()) - .setParam("pat", "12345678987654321") - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam("almSetting", almSetting.getKey()) + .setParam("pat", "12345678987654321") + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Username cannot be null for Bitbucket Cloud"); } @Test @@ -165,13 +164,14 @@ public class SetPatActionTest { UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("ALM Setting 'notExistingKey' not found"); - - ws.newRequest() - .setParam("almSetting", "notExistingKey") - .setParam("pat", "12345678987654321") - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam("almSetting", "notExistingKey") + .setParam("pat", "12345678987654321") + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("ALM Setting 'notExistingKey' not found"); } @Test @@ -180,20 +180,20 @@ public class SetPatActionTest { AlmSettingDto almSetting = db.almSettings().insertGitHubAlmSetting(); userSession.logIn(user).addPermission(PROVISION_PROJECTS); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Only Azure DevOps, Bitbucket Server, GitLab ALM and Bitbucket Cloud Settings are supported."); - - ws.newRequest() - .setParam("almSetting", almSetting.getKey()) - .setParam("pat", "12345678987654321") - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam("almSetting", almSetting.getKey()) + .setParam("pat", "12345678987654321") + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Only Azure DevOps, Bitbucket Server, GitLab ALM and Bitbucket Cloud Settings are supported."); } @Test public void fail_when_not_logged_in() { - expectedException.expect(UnauthorizedException.class); - - ws.newRequest().execute(); + assertThatThrownBy(() -> ws.newRequest().execute()) + .isInstanceOf(UnauthorizedException.class); } @Test @@ -201,10 +201,9 @@ public class SetPatActionTest { UserDto user = db.users().insertUser(); userSession.logIn(user); - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - - ws.newRequest().execute(); + assertThatThrownBy(() -> ws.newRequest().execute()) + .isInstanceOf(ForbiddenException.class) + .hasMessage("Insufficient privileges"); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almintegration/ws/azure/ListAzureProjectsActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almintegration/ws/azure/ListAzureProjectsActionTest.java index c73e70b2e08..008deceb8bb 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almintegration/ws/azure/ListAzureProjectsActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almintegration/ws/azure/ListAzureProjectsActionTest.java @@ -20,13 +20,10 @@ package org.sonar.server.almintegration.ws.azure; import com.google.common.collect.ImmutableList; - import java.util.List; - import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.alm.client.azure.AzureDevOpsHttpClient; import org.sonar.alm.client.azure.GsonAzureProject; import org.sonar.alm.client.azure.GsonAzureProjectList; @@ -54,8 +51,6 @@ import static org.sonar.db.alm.integration.pat.AlmPatsTesting.newAlmPatDto; import static org.sonar.db.permission.GlobalPermission.PROVISION_PROJECTS; public class ListAzureProjectsActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almintegration/ws/bitbucketserver/ImportBitbucketServerProjectActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almintegration/ws/bitbucketserver/ImportBitbucketServerProjectActionTest.java index c3daabb2714..28348f93309 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almintegration/ws/bitbucketserver/ImportBitbucketServerProjectActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almintegration/ws/bitbucketserver/ImportBitbucketServerProjectActionTest.java @@ -19,11 +19,15 @@ */ package org.sonar.server.almintegration.ws.bitbucketserver; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.alm.client.bitbucketserver.BitbucketServerRestClient; import org.sonar.alm.client.bitbucketserver.Branch; import org.sonar.alm.client.bitbucketserver.BranchesList; @@ -57,6 +61,7 @@ import org.sonarqube.ws.Projects; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.apache.commons.lang.math.JVMRandom.nextLong; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; @@ -65,16 +70,8 @@ import static org.sonar.db.alm.integration.pat.AlmPatsTesting.newAlmPatDto; import static org.sonar.db.permission.GlobalPermission.PROVISION_PROJECTS; import static org.sonar.db.permission.GlobalPermission.SCAN; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.Optional; -import java.util.stream.Collectors; - public class ImportBitbucketServerProjectActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -174,28 +171,30 @@ public class ImportBitbucketServerProjectActionTest { String projectKey = project.getKey() + "_" + repo.getSlug(); db.components().insertPublicProject(p -> p.setDbKey(projectKey)); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Could not create null, key already exists: " + projectKey); - - when(bitbucketServerRestClient.getRepo(any(), any(), any(), any())).thenReturn(repo); - when(bitbucketServerRestClient.getBranches(any(), any(), any(), any())).thenReturn(defaultBranchesList); - - ws.newRequest() - .setParam("almSetting", almSetting.getKey()) - .setParam("projectKey", "projectKey") - .setParam("repositorySlug", "repo-slug") - .execute(); + assertThatThrownBy(() -> { + when(bitbucketServerRestClient.getRepo(any(), any(), any(), any())).thenReturn(repo); + when(bitbucketServerRestClient.getBranches(any(), any(), any(), any())).thenReturn(defaultBranchesList); + + ws.newRequest() + .setParam("almSetting", almSetting.getKey()) + .setParam("projectKey", "projectKey") + .setParam("repositorySlug", "repo-slug") + .execute(); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Could not create null, key already exists: " + projectKey); } @Test public void fail_when_not_logged_in() { - expectedException.expect(UnauthorizedException.class); - - ws.newRequest() - .setParam("almSetting", "sdgfdshfjztutz") - .setParam("projectKey", "projectKey") - .setParam("repositorySlug", "repo-slug") - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam("almSetting", "sdgfdshfjztutz") + .setParam("projectKey", "projectKey") + .setParam("repositorySlug", "repo-slug") + .execute(); + }) + .isInstanceOf(UnauthorizedException.class); } @Test @@ -203,14 +202,15 @@ public class ImportBitbucketServerProjectActionTest { UserDto user = db.users().insertUser(); userSession.logIn(user).addPermission(SCAN); - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - - ws.newRequest() - .setParam("almSetting", "sdgfdshfjztutz") - .setParam("projectKey", "projectKey") - .setParam("repositorySlug", "repo-slug") - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam("almSetting", "sdgfdshfjztutz") + .setParam("projectKey", "projectKey") + .setParam("repositorySlug", "repo-slug") + .execute(); + }) + .isInstanceOf(ForbiddenException.class) + .hasMessage("Insufficient privileges"); } @Test @@ -219,12 +219,13 @@ public class ImportBitbucketServerProjectActionTest { userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertGitHubAlmSetting(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("personal access token for '" + almSetting.getKey() + "' is missing"); - - ws.newRequest() - .setParam("almSetting", almSetting.getKey()) - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam("almSetting", almSetting.getKey()) + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("personal access token for '" + almSetting.getKey() + "' is missing"); } @Test @@ -234,12 +235,13 @@ public class ImportBitbucketServerProjectActionTest { AlmPatDto almPatDto = newAlmPatDto(); db.getDbClient().almPatDao().insert(db.getSession(), almPatDto, user.getLogin(), null); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("ALM Setting 'testKey' not found"); - - ws.newRequest() - .setParam("almSetting", "testKey") - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam("almSetting", "testKey") + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("ALM Setting 'testKey' not found"); } @Test @@ -247,12 +249,13 @@ public class ImportBitbucketServerProjectActionTest { UserDto user = db.users().insertUser(); userSession.logIn(user); - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - - ws.newRequest() - .setParam("almSetting", "anyvalue") - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam("almSetting", "anyvalue") + .execute(); + }) + .isInstanceOf(ForbiddenException.class) + .hasMessage("Insufficient privileges"); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almintegration/ws/bitbucketserver/SearchBitbucketServerReposActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almintegration/ws/bitbucketserver/SearchBitbucketServerReposActionTest.java index 24748721ce0..a795bf2c570 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almintegration/ws/bitbucketserver/SearchBitbucketServerReposActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almintegration/ws/bitbucketserver/SearchBitbucketServerReposActionTest.java @@ -24,7 +24,6 @@ import java.util.List; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.alm.client.bitbucketserver.BitbucketServerRestClient; import org.sonar.alm.client.bitbucketserver.Project; import org.sonar.alm.client.bitbucketserver.Repository; @@ -46,6 +45,7 @@ import org.sonarqube.ws.AlmIntegrations; import org.sonarqube.ws.AlmIntegrations.SearchBitbucketserverReposWsResponse; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; @@ -55,8 +55,6 @@ import static org.sonar.db.permission.GlobalPermission.PROVISION_PROJECTS; public class SearchBitbucketServerReposActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -187,12 +185,13 @@ public class SearchBitbucketServerReposActionTest { userSession.logIn(user).addPermission(PROVISION_PROJECTS); AlmSettingDto almSetting = db.almSettings().insertGitHubAlmSetting(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("No personal access token found"); - - ws.newRequest() - .setParam("almSetting", almSetting.getKey()) - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam("almSetting", almSetting.getKey()) + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("No personal access token found"); } @Test @@ -202,34 +201,37 @@ public class SearchBitbucketServerReposActionTest { AlmPatDto almPatDto = newAlmPatDto(); db.getDbClient().almPatDao().insert(db.getSession(), almPatDto, user.getLogin(), null); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("ALM Setting 'testKey' not found"); - - ws.newRequest() - .setParam("almSetting", "testKey") - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam("almSetting", "testKey") + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("ALM Setting 'testKey' not found"); } @Test public void fail_when_not_logged_in() { - expectedException.expect(UnauthorizedException.class); - - ws.newRequest() - .setParam("almSetting", "anyvalue") - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam("almSetting", "anyvalue") + .execute(); + }) + .isInstanceOf(UnauthorizedException.class); } @Test public void fail_when_no_creation_project_permission() { UserDto user = db.users().insertUser(); userSession.logIn(user); - - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - - ws.newRequest() - .setParam("almSetting", "anyvalue") - .execute(); + + assertThatThrownBy(() -> { + ws.newRequest() + .setParam("almSetting", "anyvalue") + .execute(); + }) + .isInstanceOf(ForbiddenException.class) + .hasMessage("Insufficient privileges"); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/CountBindingActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/CountBindingActionTest.java index 510780bda09..140f4b50837 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/CountBindingActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/CountBindingActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.almsettings.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbTester; import org.sonar.db.alm.setting.AlmSettingDto; @@ -36,14 +35,13 @@ import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.AlmSettings.CountBindingWsResponse; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.groups.Tuple.tuple; import static org.mockito.Mockito.mock; import static org.sonar.test.JsonAssert.assertJson; public class CountBindingActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -92,12 +90,11 @@ public class CountBindingActionTest { UserDto user = db.users().insertUser(); userSession.logIn(user).setSystemAdministrator(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("ALM setting with key 'unknown' cannot be found"); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("almSetting", "unknown") - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("ALM setting with key 'unknown' cannot be found"); } @Test @@ -106,11 +103,10 @@ public class CountBindingActionTest { userSession.logIn(user); AlmSettingDto githubAlmSetting = db.almSettings().insertGitHubAlmSetting(); - expectedException.expect(ForbiddenException.class); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("almSetting", githubAlmSetting.getKey()) - .execute(); + .execute()) + .isInstanceOf(ForbiddenException.class); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/CreateAzureActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/CreateAzureActionTest.java index da14c3f8473..7a37f1eaed7 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/CreateAzureActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/CreateAzureActionTest.java @@ -22,7 +22,6 @@ package org.sonar.server.almsettings.ws; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.config.internal.Encryption; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbTester; @@ -36,14 +35,13 @@ import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.groups.Tuple.tuple; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class CreateAzureActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -86,14 +84,13 @@ public class CreateAzureActionTest { userSession.logIn(user).setSystemAdministrator(); AlmSettingDto azureAlmSetting = db.almSettings().insertAzureAlmSetting(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(String.format("An ALM setting with key '%s' already exist", azureAlmSetting.getKey())); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("key", azureAlmSetting.getKey()) .setParam("personalAccessToken", "98765432100") .setParam("url", "https://ado.sonarqube.com/") - .execute(); + .execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(String.format("An ALM setting with key '%s' already exist", azureAlmSetting.getKey())); } @Test @@ -103,14 +100,13 @@ public class CreateAzureActionTest { userSession.logIn(user).setSystemAdministrator(); db.almSettings().insertAzureAlmSetting(); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("A AZURE_DEVOPS setting is already defined"); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("key", "key") .setParam("personalAccessToken", "98765432100") .setParam("url", "https://ado.sonarqube.com/") - .execute(); + .execute()) + .isInstanceOf(BadRequestException.class) + .hasMessageContaining("A AZURE_DEVOPS setting is already defined"); } @Test @@ -118,12 +114,11 @@ public class CreateAzureActionTest { UserDto user = db.users().insertUser(); userSession.logIn(user); - expectedException.expect(ForbiddenException.class); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("key", "Azure Server - Dev Team") .setParam("personalAccessToken", "98765432100") - .execute(); + .execute()) + .isInstanceOf(ForbiddenException.class); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/CreateBitbucketActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/CreateBitbucketActionTest.java index d899ddadd27..9dd456d70c8 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/CreateBitbucketActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/CreateBitbucketActionTest.java @@ -22,7 +22,6 @@ package org.sonar.server.almsettings.ws; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.config.internal.Encryption; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbTester; @@ -36,14 +35,13 @@ import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.groups.Tuple.tuple; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class CreateBitbucketActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -57,7 +55,7 @@ public class CreateBitbucketActionTest { multipleAlmFeatureProvider))); @Before - public void before(){ + public void before() { when(multipleAlmFeatureProvider.enabled()).thenReturn(false); } @@ -84,14 +82,13 @@ public class CreateBitbucketActionTest { userSession.logIn(user).setSystemAdministrator(); AlmSettingDto bitbucketAlmSetting = db.almSettings().insertBitbucketAlmSetting(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(String.format("An ALM setting with key '%s' already exist", bitbucketAlmSetting.getKey())); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("key", bitbucketAlmSetting.getKey()) .setParam("url", "https://bitbucket.enterprise.com") .setParam("personalAccessToken", "98765432100") - .execute(); + .execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(String.format("An ALM setting with key '%s' already exist", bitbucketAlmSetting.getKey())); } @Test @@ -101,14 +98,13 @@ public class CreateBitbucketActionTest { userSession.logIn(user).setSystemAdministrator(); db.almSettings().insertBitbucketAlmSetting(); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("A BITBUCKET setting is already defined"); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("key", "otherKey") .setParam("url", "https://bitbucket.enterprise.com") .setParam("personalAccessToken", "98765432100") - .execute(); + .execute()) + .isInstanceOf(BadRequestException.class) + .hasMessageContaining("A BITBUCKET setting is already defined"); } @Test @@ -118,14 +114,13 @@ public class CreateBitbucketActionTest { userSession.logIn(user).setSystemAdministrator(); db.almSettings().insertBitbucketCloudAlmSetting(); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("A BITBUCKET_CLOUD setting is already defined"); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("key", "otherKey") .setParam("url", "https://bitbucket.enterprise.com") .setParam("personalAccessToken", "98765432100") - .execute(); + .execute()) + .isInstanceOf(BadRequestException.class) + .hasMessageContaining("A BITBUCKET_CLOUD setting is already defined"); } @Test @@ -133,13 +128,13 @@ public class CreateBitbucketActionTest { UserDto user = db.users().insertUser(); userSession.logIn(user); - expectedException.expect(ForbiddenException.class); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("key", "Bitbucket Server - Dev Team") .setParam("url", "https://bitbucket.enterprise.com") .setParam("personalAccessToken", "98765432100") - .execute(); + .setParam("personalAccessToken", "98765432100") + .execute()) + .isInstanceOf(ForbiddenException.class); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/CreateBitbucketCloudActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/CreateBitbucketCloudActionTest.java index cb7f30be4be..c5a65b8bafa 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/CreateBitbucketCloudActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/CreateBitbucketCloudActionTest.java @@ -22,7 +22,6 @@ package org.sonar.server.almsettings.ws; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.config.internal.Encryption; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbTester; @@ -36,14 +35,13 @@ import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.groups.Tuple.tuple; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class CreateBitbucketCloudActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -85,15 +83,14 @@ public class CreateBitbucketCloudActionTest { userSession.logIn(user).setSystemAdministrator(); AlmSettingDto bitbucketAlmSetting = db.almSettings().insertBitbucketAlmSetting(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(String.format("An ALM setting with key '%s' already exist", bitbucketAlmSetting.getKey())); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("key", bitbucketAlmSetting.getKey()) .setParam("workspace", "workspace1") .setParam("clientId", "id") .setParam("clientSecret", "secret") - .execute(); + .execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(String.format("An ALM setting with key '%s' already exist", bitbucketAlmSetting.getKey())); } @Test @@ -103,15 +100,14 @@ public class CreateBitbucketCloudActionTest { userSession.logIn(user).setSystemAdministrator(); db.almSettings().insertBitbucketCloudAlmSetting(); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("A BITBUCKET_CLOUD setting is already defined"); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("key", "otherKey") .setParam("workspace", "workspace1") .setParam("clientId", "id") .setParam("clientSecret", "secret") - .execute(); + .execute()) + .isInstanceOf(BadRequestException.class) + .hasMessageContaining("A BITBUCKET_CLOUD setting is already defined"); } @Test @@ -121,15 +117,14 @@ public class CreateBitbucketCloudActionTest { userSession.logIn(user).setSystemAdministrator(); db.almSettings().insertBitbucketAlmSetting(); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("A BITBUCKET setting is already defined"); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("key", "otherKey") .setParam("workspace", "workspace1") .setParam("clientId", "id") .setParam("clientSecret", "secret") - .execute(); + .execute()) + .isInstanceOf(BadRequestException.class) + .hasMessageContaining("A BITBUCKET setting is already defined"); } @Test @@ -137,14 +132,13 @@ public class CreateBitbucketCloudActionTest { UserDto user = db.users().insertUser(); userSession.logIn(user); - expectedException.expect(ForbiddenException.class); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("key", "Bitbucket Server - Dev Team") .setParam("clientId", "id") .setParam("clientSecret", "secret") .setParam("workspace", "workspace1") - .execute(); + .execute()) + .isInstanceOf(ForbiddenException.class); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/CreateGithubActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/CreateGithubActionTest.java index 6ab9d86a433..825881f5598 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/CreateGithubActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/CreateGithubActionTest.java @@ -22,7 +22,6 @@ package org.sonar.server.almsettings.ws; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.config.internal.Encryption; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbTester; @@ -33,17 +32,17 @@ import org.sonar.server.component.ComponentFinder; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.tester.UserSessionRule; +import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.groups.Tuple.tuple; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class CreateGithubActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -108,17 +107,17 @@ public class CreateGithubActionTest { userSession.logIn(user).setSystemAdministrator(); AlmSettingDto gitHubAlmSetting = db.almSettings().insertGitHubAlmSetting(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(String.format("An ALM setting with key '%s' already exist", gitHubAlmSetting.getKey())); - - ws.newRequest() + TestRequest request = ws.newRequest() .setParam("key", gitHubAlmSetting.getKey()) .setParam("url", "https://github.enterprise.com") .setParam("appId", "12345") .setParam("privateKey", "678910") .setParam("clientId", "client_1234") - .setParam("clientSecret", "client_so_secret") - .execute(); + .setParam("clientSecret", "client_so_secret"); + + assertThatThrownBy(() -> request.execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(String.format("An ALM setting with key '%s' already exist", gitHubAlmSetting.getKey())); } @Test @@ -128,17 +127,17 @@ public class CreateGithubActionTest { userSession.logIn(user).setSystemAdministrator(); db.almSettings().insertGitHubAlmSetting(); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("A GITHUB setting is already defined"); - - ws.newRequest() + TestRequest request = ws.newRequest() .setParam("key", "key") .setParam("url", "https://github.enterprise.com") .setParam("appId", "12345") .setParam("privateKey", "678910") .setParam("clientId", "client_1234") - .setParam("clientSecret", "client_so_secret") - .execute(); + .setParam("clientSecret", "client_so_secret"); + + assertThatThrownBy(() -> request.execute()) + .isInstanceOf(BadRequestException.class) + .hasMessageContaining("A GITHUB setting is already defined"); } @Test @@ -146,16 +145,16 @@ public class CreateGithubActionTest { UserDto user = db.users().insertUser(); userSession.logIn(user); - expectedException.expect(ForbiddenException.class); - - ws.newRequest() + TestRequest request = ws.newRequest() .setParam("key", "GitHub Server - Dev Team") .setParam("url", "https://github.enterprise.com") .setParam("appId", "12345") .setParam("privateKey", "678910") .setParam("clientId", "client_1234") - .setParam("clientSecret", "client_so_secret") - .execute(); + .setParam("clientSecret", "client_so_secret"); + + assertThatThrownBy(() -> request.execute()) + .isInstanceOf(ForbiddenException.class); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/CreateGitlabActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/CreateGitlabActionTest.java index e1cf4fd2e06..3ce4aa1dffc 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/CreateGitlabActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/CreateGitlabActionTest.java @@ -23,7 +23,6 @@ import org.assertj.core.api.Assertions; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.config.internal.Encryption; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbTester; @@ -38,14 +37,13 @@ import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.groups.Tuple.tuple; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class CreateGitlabActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -116,14 +114,13 @@ public class CreateGitlabActionTest { userSession.logIn(user).setSystemAdministrator(); AlmSettingDto gitlabAlmSetting = db.almSettings().insertGitlabAlmSetting(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(String.format("An ALM setting with key '%s' already exist", gitlabAlmSetting.getKey())); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("key", gitlabAlmSetting.getKey()) .setParam("personalAccessToken", "98765432100") .setParam("url", GITLAB_URL) - .execute(); + .execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(String.format("An ALM setting with key '%s' already exist", gitlabAlmSetting.getKey())); } @Test @@ -133,14 +130,13 @@ public class CreateGitlabActionTest { userSession.logIn(user).setSystemAdministrator(); db.almSettings().insertGitlabAlmSetting(); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("A GITLAB setting is already defined"); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("key", "anotherKey") .setParam("personalAccessToken", "98765432100") .setParam("url", GITLAB_URL) - .execute(); + .execute()) + .isInstanceOf(BadRequestException.class) + .hasMessageContaining("A GITLAB setting is already defined"); } @Test @@ -148,12 +144,11 @@ public class CreateGitlabActionTest { UserDto user = db.users().insertUser(); userSession.logIn(user); - expectedException.expect(ForbiddenException.class); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("key", "Gitlab - Dev Team") .setParam("personalAccessToken", "98765432100") - .execute(); + .execute()) + .isInstanceOf(ForbiddenException.class); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/DeleteActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/DeleteActionTest.java index 2cb6f9fe2f4..0a039c91c5b 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/DeleteActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/DeleteActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.almsettings.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbTester; import org.sonar.db.alm.pat.AlmPatDto; @@ -36,13 +35,12 @@ import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.groups.Tuple.tuple; import static org.mockito.Mockito.mock; public class DeleteActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -106,12 +104,11 @@ public class DeleteActionTest { UserDto user = db.users().insertUser(); userSession.logIn(user).setSystemAdministrator(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("ALM setting with key 'unknown' cannot be found"); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("key", "unknown") - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("ALM setting with key 'unknown' cannot be found"); } @Test @@ -120,11 +117,10 @@ public class DeleteActionTest { userSession.logIn(user); AlmSettingDto almSettingDto = db.almSettings().insertGitHubAlmSetting(); - expectedException.expect(ForbiddenException.class); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("key", almSettingDto.getKey()) - .execute(); + .execute()) + .isInstanceOf(ForbiddenException.class); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/GetBindingActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/GetBindingActionTest.java index 14137385a35..11685edce0d 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/GetBindingActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/GetBindingActionTest.java @@ -22,7 +22,6 @@ package org.sonar.server.almsettings.ws; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbTester; import org.sonar.db.alm.setting.AlmSettingDto; @@ -38,6 +37,7 @@ import org.sonarqube.ws.AlmSettings; import org.sonarqube.ws.AlmSettings.GetBindingWsResponse; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.groups.Tuple.tuple; import static org.sonar.api.web.UserRole.ADMIN; import static org.sonar.api.web.UserRole.USER; @@ -45,8 +45,6 @@ import static org.sonar.test.JsonAssert.assertJson; public class GetBindingActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -143,11 +141,10 @@ public class GetBindingActionTest { AlmSettingDto githubAlmSetting = db.almSettings().insertGitHubAlmSetting(); db.almSettings().insertGitHubProjectAlmSetting(githubAlmSetting, project); - expectedException.expect(NotFoundException.class); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("project", "unknown") - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class); } @Test @@ -156,11 +153,10 @@ public class GetBindingActionTest { AlmSettingDto githubAlmSetting = db.almSettings().insertGitHubAlmSetting(); db.almSettings().insertGitHubProjectAlmSetting(githubAlmSetting, project); - expectedException.expect(ForbiddenException.class); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("project", project.getKey()) - .execute(); + .execute()) + .isInstanceOf(ForbiddenException.class); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/ListActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/ListActionTest.java index 4532cf60019..d5adb15b5a8 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/ListActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/ListActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.almsettings.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.resources.ResourceTypes; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbTester; @@ -49,8 +48,6 @@ import static org.sonar.db.permission.GlobalPermission.PROVISION_PROJECTS; import static org.sonar.test.JsonAssert.assertJson; public class ListActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -108,8 +105,8 @@ public class ListActionTest { @Test public void fail_when_missing_create_project_permission() { - expectedException.expect(ForbiddenException.class); - ws.newRequest().execute(); + assertThatThrownBy(() -> ws.newRequest().execute()) + .isInstanceOf(ForbiddenException.class); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/ListDefinitionsActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/ListDefinitionsActionTest.java index c78ff05081f..5153b08e93b 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/ListDefinitionsActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/ListDefinitionsActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.almsettings.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.db.DbTester; @@ -36,8 +35,8 @@ import org.sonarqube.ws.AlmSettings.AlmSettingGithub; import org.sonarqube.ws.AlmSettings.AlmSettingGitlab; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; -import static org.junit.rules.ExpectedException.none; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.server.tester.UserSessionRule.standalone; @@ -46,8 +45,6 @@ import static org.sonarqube.ws.AlmSettings.ListDefinitionsWsResponse; public class ListDefinitionsActionTest { - @Rule - public ExpectedException expectedException = none(); @Rule public UserSessionRule userSession = standalone(); @@ -156,9 +153,8 @@ public class ListDefinitionsActionTest { userSession.logIn(user); db.almSettings().insertGitHubAlmSetting(); - expectedException.expect(ForbiddenException.class); - - ws.newRequest().executeProtobuf(ListDefinitionsWsResponse.class); + assertThatThrownBy(() -> ws.newRequest().executeProtobuf(ListDefinitionsWsResponse.class)) + .isInstanceOf(ForbiddenException.class); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/UpdateAzureActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/UpdateAzureActionTest.java index d26e59986e5..78d9ac5523e 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/UpdateAzureActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/UpdateAzureActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.almsettings.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.config.internal.Encryption; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbTester; @@ -36,13 +35,12 @@ import org.sonar.server.ws.WsActionTester; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.groups.Tuple.tuple; import static org.mockito.Mockito.mock; public class UpdateAzureActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -112,14 +110,13 @@ public class UpdateAzureActionTest { UserDto user = db.users().insertUser(); userSession.logIn(user).setSystemAdministrator(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("ALM setting with key 'unknown' cannot be found"); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("key", "unknown") .setParam("personalAccessToken", "0123456789") .setParam("url", AZURE_URL) - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("ALM setting with key 'unknown' cannot be found"); } @Test @@ -129,15 +126,14 @@ public class UpdateAzureActionTest { AlmSettingDto almSetting1 = db.almSettings().insertAzureAlmSetting(); AlmSettingDto almSetting2 = db.almSettings().insertAzureAlmSetting(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(format("An ALM setting with key '%s' already exists", almSetting2.getKey())); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("key", almSetting1.getKey()) .setParam("newKey", almSetting2.getKey()) .setParam("personalAccessToken", "0123456789") .setParam("url", AZURE_URL) - .execute(); + .execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(format("An ALM setting with key '%s' already exists", almSetting2.getKey())); } @Test @@ -146,13 +142,12 @@ public class UpdateAzureActionTest { userSession.logIn(user); AlmSettingDto almSettingDto = db.almSettings().insertAzureAlmSetting(); - expectedException.expect(ForbiddenException.class); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("key", almSettingDto.getKey()) .setParam("newKey", "Azure Server - Infra Team") .setParam("personalAccessToken", "0123456789") - .execute(); + .execute()) + .isInstanceOf(ForbiddenException.class); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/UpdateBitbucketActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/UpdateBitbucketActionTest.java index 19927eb0fa6..c0a527983f1 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/UpdateBitbucketActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/UpdateBitbucketActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.almsettings.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.config.internal.Encryption; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbTester; @@ -36,13 +35,12 @@ import org.sonar.server.ws.WsActionTester; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.groups.Tuple.tuple; import static org.mockito.Mockito.mock; public class UpdateBitbucketActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -109,15 +107,14 @@ public class UpdateBitbucketActionTest { public void fail_when_key_does_not_match_existing_alm_setting() { UserDto user = db.users().insertUser(); userSession.logIn(user).setSystemAdministrator(); - - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("ALM setting with key 'unknown' cannot be found"); - - ws.newRequest() + + assertThatThrownBy(() -> ws.newRequest() .setParam("key", "unknown") .setParam("url", "https://bitbucket.enterprise-unicorn.com") .setParam("personalAccessToken", "0123456789") - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("ALM setting with key 'unknown' cannot be found"); } @Test @@ -127,15 +124,14 @@ public class UpdateBitbucketActionTest { AlmSettingDto almSetting1 = db.almSettings().insertBitbucketAlmSetting(); AlmSettingDto almSetting2 = db.almSettings().insertBitbucketAlmSetting(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(format("An ALM setting with key '%s' already exists", almSetting2.getKey())); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("key", almSetting1.getKey()) .setParam("newKey", almSetting2.getKey()) .setParam("url", "https://bitbucket.enterprise-unicorn.com") .setParam("personalAccessToken", "0123456789") - .execute(); + .execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(format("An ALM setting with key '%s' already exists", almSetting2.getKey())); } @Test @@ -144,14 +140,13 @@ public class UpdateBitbucketActionTest { userSession.logIn(user); AlmSettingDto almSettingDto = db.almSettings().insertBitbucketAlmSetting(); - expectedException.expect(ForbiddenException.class); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("key", almSettingDto.getKey()) .setParam("newKey", "Bitbucket Server - Infra Team") .setParam("url", "https://bitbucket.enterprise-unicorn.com") .setParam("personalAccessToken", "0123456789") - .execute(); + .execute()) + .isInstanceOf(ForbiddenException.class); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/UpdateGithubActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/UpdateGithubActionTest.java index d100ba0674e..8f90c95c284 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/UpdateGithubActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/UpdateGithubActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.almsettings.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.config.internal.Encryption; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbTester; @@ -32,17 +31,17 @@ import org.sonar.server.component.ComponentFinder; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.tester.UserSessionRule; +import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.groups.Tuple.tuple; import static org.mockito.Mockito.mock; public class UpdateGithubActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -143,18 +142,18 @@ public class UpdateGithubActionTest { UserDto user = db.users().insertUser(); userSession.logIn(user).setSystemAdministrator(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("ALM setting with key 'unknown' cannot be found"); - - ws.newRequest() + TestRequest request = ws.newRequest() .setParam("key", "unknown") .setParam("newKey", "GitHub Server - Infra Team") .setParam("url", "https://github.enterprise-unicorn.com") .setParam("appId", "54321") .setParam("privateKey", "10987654321") .setParam("clientId", "client_1234") - .setParam("clientSecret", "client_so_secret") - .execute(); + .setParam("clientSecret", "client_so_secret"); + + assertThatThrownBy(() -> request.execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("ALM setting with key 'unknown' cannot be found"); } @Test @@ -164,18 +163,18 @@ public class UpdateGithubActionTest { AlmSettingDto almSetting1 = db.almSettings().insertGitHubAlmSetting(); AlmSettingDto almSetting2 = db.almSettings().insertGitHubAlmSetting(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(format("An ALM setting with key '%s' already exists", almSetting2.getKey())); - - ws.newRequest() + TestRequest request = ws.newRequest() .setParam("key", almSetting1.getKey()) .setParam("newKey", almSetting2.getKey()) .setParam("url", "https://github.enterprise-unicorn.com") .setParam("appId", "54321") .setParam("privateKey", "10987654321") .setParam("clientId", "client_1234") - .setParam("clientSecret", "client_so_secret") - .execute(); + .setParam("clientSecret", "client_so_secret"); + + assertThatThrownBy(() -> request.execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(format("An ALM setting with key '%s' already exists", almSetting2.getKey())); } @Test @@ -184,17 +183,17 @@ public class UpdateGithubActionTest { userSession.logIn(user); AlmSettingDto almSettingDto = db.almSettings().insertGitHubAlmSetting(); - expectedException.expect(ForbiddenException.class); - - ws.newRequest() + TestRequest request = ws.newRequest() .setParam("key", almSettingDto.getKey()) .setParam("newKey", "GitHub Server - Infra Team") .setParam("url", "https://github.enterprise-unicorn.com") .setParam("appId", "54321") .setParam("privateKey", "10987654321") .setParam("clientId", "client_1234") - .setParam("clientSecret", "client_so_secret") - .execute(); + .setParam("clientSecret", "client_so_secret"); + + assertThatThrownBy(() -> request.execute()) + .isInstanceOf(ForbiddenException.class); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/UpdateGitlabActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/UpdateGitlabActionTest.java index 073e64f89ac..7b249ada4a8 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/UpdateGitlabActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/almsettings/ws/UpdateGitlabActionTest.java @@ -23,7 +23,6 @@ import org.assertj.core.api.Assertions; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.config.internal.Encryption; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbTester; @@ -39,14 +38,13 @@ import org.sonar.server.ws.WsActionTester; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.groups.Tuple.tuple; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class UpdateGitlabActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -136,14 +134,13 @@ public class UpdateGitlabActionTest { UserDto user = db.users().insertUser(); userSession.logIn(user).setSystemAdministrator(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("ALM setting with key 'unknown' cannot be found"); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("key", "unknown") .setParam("personalAccessToken", "0123456789") .setParam("url", GITLAB_URL) - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("ALM setting with key 'unknown' cannot be found"); } @Test @@ -153,15 +150,14 @@ public class UpdateGitlabActionTest { AlmSettingDto almSetting1 = db.almSettings().insertGitlabAlmSetting(); AlmSettingDto almSetting2 = db.almSettings().insertGitlabAlmSetting(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(format("An ALM setting with key '%s' already exists", almSetting2.getKey())); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("key", almSetting1.getKey()) .setParam("newKey", almSetting2.getKey()) .setParam("personalAccessToken", "0123456789") .setParam("url", GITLAB_URL) - .execute(); + .execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(format("An ALM setting with key '%s' already exists", almSetting2.getKey())); } @Test @@ -170,14 +166,13 @@ public class UpdateGitlabActionTest { userSession.logIn(user); AlmSettingDto almSettingDto = db.almSettings().insertGitlabAlmSetting(); - expectedException.expect(ForbiddenException.class); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("key", almSettingDto.getKey()) .setParam("newKey", "Gitlab - Infra Team") .setParam("personalAccessToken", "0123456789") .setParam("url", GITLAB_URL) - .execute(); + .execute()) + .isInstanceOf(ForbiddenException.class); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/badge/ws/MeasureActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/badge/ws/MeasureActionTest.java index c94cc4258cc..a0c263a98c9 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/badge/ws/MeasureActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/badge/ws/MeasureActionTest.java @@ -29,7 +29,6 @@ import java.util.Locale; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.api.CoreProperties; import org.sonar.api.config.Configuration; @@ -54,6 +53,7 @@ import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.api.measures.CoreMetrics.BUGS_KEY; import static org.sonar.api.measures.CoreMetrics.COVERAGE_KEY; @@ -77,8 +77,6 @@ import static org.sonar.server.badge.ws.SvgGenerator.Color.QUALITY_GATE_WARN; @RunWith(DataProviderRunner.class) public class MeasureActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -415,13 +413,14 @@ public class MeasureActionTest { MetricDto metric = createQualityGateMetric(); db.measures().insertLiveMeasure(project, metric, m -> m.setData("UNKNOWN")); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("No enum constant org.sonar.api.measures.Metric.Level.UNKNOWN"); - - ws.newRequest() - .setParam("project", project.getKey()) - .setParam("metric", metric.getKey()) - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam("project", project.getKey()) + .setParam("metric", metric.getKey()) + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("No enum constant org.sonar.api.measures.Metric.Level.UNKNOWN"); } @Test @@ -431,13 +430,14 @@ public class MeasureActionTest { MetricDto metric = db.measures().insertMetric(m -> m.setKey(BUGS_KEY).setValueType(INT.name())); db.measures().insertLiveMeasure(project, metric, m -> m.setValue(null)); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Measure has not been found"); - - ws.newRequest() - .setParam("project", project.getKey()) - .setParam("metric", metric.getKey()) - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam("project", project.getKey()) + .setParam("metric", metric.getKey()) + .execute(); + }) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Measure has not been found"); } @Test @@ -445,13 +445,14 @@ public class MeasureActionTest { ComponentDto project = db.components().insertPublicProject(); userSession.registerComponents(project); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Metric 'bugs' hasn't been found"); - - ws.newRequest() - .setParam("project", project.getKey()) - .setParam("metric", BUGS_KEY) - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam("project", project.getKey()) + .setParam("metric", BUGS_KEY) + .execute(); + }) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Metric 'bugs' hasn't been found"); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/badge/ws/QualityGateActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/badge/ws/QualityGateActionTest.java index de3c268b23a..4161a7bdbaf 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/badge/ws/QualityGateActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/badge/ws/QualityGateActionTest.java @@ -30,7 +30,6 @@ import java.util.Locale; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.api.CoreProperties; import org.sonar.api.config.Configuration; @@ -52,6 +51,7 @@ import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.api.measures.CoreMetrics.ALERT_STATUS_KEY; import static org.sonar.api.measures.Metric.Level.ERROR; @@ -63,8 +63,6 @@ import static org.sonar.db.component.BranchType.BRANCH; @RunWith(DataProviderRunner.class) public class QualityGateActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -338,12 +336,13 @@ public class QualityGateActionTest { MetricDto metric = createQualityGateMetric(); db.measures().insertLiveMeasure(project, metric, m -> m.setData("UNKNOWN")); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("No enum constant org.sonar.api.measures.Metric.Level.UNKNOWN"); - - ws.newRequest() - .setParam("project", project.getKey()) - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam("project", project.getKey()) + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("No enum constant org.sonar.api.measures.Metric.Level.UNKNOWN"); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/badge/ws/SvgGeneratorTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/badge/ws/SvgGeneratorTest.java index db4af768adf..5d0a081a717 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/badge/ws/SvgGeneratorTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/badge/ws/SvgGeneratorTest.java @@ -23,7 +23,6 @@ import java.io.IOException; import org.apache.commons.io.IOUtils; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.measures.Metric; import org.sonar.db.DbTester; @@ -31,14 +30,13 @@ import org.sonar.server.tester.UserSessionRule; import static java.nio.charset.StandardCharsets.UTF_8; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.measures.Metric.Level.ERROR; import static org.sonar.api.measures.Metric.Level.WARN; import static org.sonar.server.badge.ws.SvgGenerator.Color.DEFAULT; public class SvgGeneratorTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -93,9 +91,8 @@ public class SvgGeneratorTest { mapSettings.setProperty("sonar.sonarcloud.enabled", false); initSvgGenerator(); - expectedException.expectMessage("Invalid character 'é'"); - - underTest.generateError("Méssage with accent"); + assertThatThrownBy(() -> underTest.generateError("Méssage with accent")) + .hasMessage("Invalid character 'é'"); } private void initSvgGenerator() { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/batch/BatchIndexTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/batch/BatchIndexTest.java index e6104c0e811..b59c2a516f6 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/batch/BatchIndexTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/batch/BatchIndexTest.java @@ -26,12 +26,12 @@ import org.apache.commons.lang.CharUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.platform.ServerFileSystem; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -40,8 +40,6 @@ public class BatchIndexTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); - @Rule - public ExpectedException thrown = ExpectedException.none(); private File jar; @@ -84,23 +82,25 @@ public class BatchIndexTest { */ @Test public void check_location_of_file() { - thrown.expect(NotFoundException.class); - thrown.expectMessage("Bad filename: ../sonar-batch.jar"); - - BatchIndex batchIndex = new BatchIndex(fs); - batchIndex.start(); - - batchIndex.getFile("../sonar-batch.jar"); + assertThatThrownBy(() -> { + BatchIndex batchIndex = new BatchIndex(fs); + batchIndex.start(); + + batchIndex.getFile("../sonar-batch.jar"); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("Bad filename: ../sonar-batch.jar"); } @Test public void file_does_not_exist() { - thrown.expect(NotFoundException.class); - thrown.expectMessage("Bad filename: other.jar"); - - BatchIndex batchIndex = new BatchIndex(fs); - batchIndex.start(); - - batchIndex.getFile("other.jar"); + assertThatThrownBy(() -> { + BatchIndex batchIndex = new BatchIndex(fs); + batchIndex.start(); + + batchIndex.getFile("other.jar"); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("Bad filename: other.jar"); } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/batch/FileActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/batch/FileActionTest.java index 5d8c8cc56c4..55cfee20347 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/batch/FileActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/batch/FileActionTest.java @@ -24,7 +24,6 @@ import org.apache.commons.io.FileUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.sonar.api.server.ws.WebService; import org.sonar.server.exceptions.NotFoundException; @@ -33,13 +32,12 @@ import org.sonar.server.ws.WsActionTester; import static org.apache.commons.io.FileUtils.writeStringToFile; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class FileActionTest { - @Rule - public ExpectedException thrown = ExpectedException.none(); @Rule public TemporaryFolder temp = new TemporaryFolder(); @@ -75,16 +73,16 @@ public class FileActionTest { writeStringToFile(new File(batchDir, "sonar-batch.jar"), "foo"); batchIndex.start(); - thrown.expect(NotFoundException.class); - thrown.expectMessage("Bad filename: unknown"); - tester.newRequest().setParam("name", "unknown").execute(); + assertThatThrownBy(() -> tester.newRequest().setParam("name", "unknown").execute()) + .isInstanceOf(NotFoundException.class) + .hasMessage("Bad filename: unknown"); } @Test public void throw_IAE_when_no_name_parameter() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("The 'name' parameter is missing"); - tester.newRequest().execute(); + assertThatThrownBy(() -> tester.newRequest().execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("The 'name' parameter is missing"); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/batch/IndexActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/batch/IndexActionTest.java index 0db56e0d629..ca99b69218a 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/batch/IndexActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/batch/IndexActionTest.java @@ -24,7 +24,6 @@ import org.apache.commons.io.FileUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.sonar.api.server.ws.WebService; import org.sonar.server.platform.ServerFileSystem; @@ -32,13 +31,12 @@ import org.sonar.server.ws.WsActionTester; import static org.apache.commons.io.FileUtils.writeStringToFile; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class IndexActionTest { - @Rule - public ExpectedException thrown = ExpectedException.none(); @Rule public TemporaryFolder temp = new TemporaryFolder(); @@ -70,8 +68,9 @@ public class IndexActionTest { @Test public void throw_ISE_when_no_file() { - thrown.expect(IllegalStateException.class); - tester.newRequest().execute(); + assertThatThrownBy(() -> tester.newRequest().execute()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("No available files"); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/batch/IssuesActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/batch/IssuesActionTest.java index 85f968861b9..6b71f603f6d 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/batch/IssuesActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/batch/IssuesActionTest.java @@ -25,7 +25,6 @@ import javax.annotation.Nullable; import org.assertj.core.groups.Tuple; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.rules.RuleType; import org.sonar.api.utils.System2; import org.sonar.api.web.UserRole; @@ -49,6 +48,7 @@ import org.sonar.server.ws.WsActionTester; import static java.lang.String.format; import static org.apache.commons.lang.math.RandomUtils.nextInt; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.api.rules.RuleType.BUG; import static org.sonar.db.component.ComponentTesting.newDirectory; @@ -63,8 +63,6 @@ public class IssuesActionTest { private System2 system2 = System2.INSTANCE; - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester db = DbTester.create(system2); @Rule @@ -181,7 +179,7 @@ public class IssuesActionTest { RuleDefinitionDto external = db.rules().insert(ruleDefinitionDto -> ruleDefinitionDto.setIsExternal(true)); IssueDto issueFromExteralruleOnFile = db.issues().insert(external, project, file, i -> i.setKee("ON_FILE_FROM_EXTERNAL").setType(randomRuleTypeExceptHotspot())); - + RuleDefinitionDto migrated = db.rules().insert(); db.executeUpdateSql("update rules set is_external=? where rules.uuid = ?", false, migrated.getUuid()); IssueDto issueFromMigratedRule = db.issues().insert(migrated, project, file, i -> i.setKee("MIGRATED").setType(randomRuleTypeExceptHotspot())); @@ -281,10 +279,9 @@ public class IssuesActionTest { ComponentDto directory = db.components().insertComponent(newDirectory(project, "src/main/java")); addPermissionTo(project); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Component of scope 'DIR' is not allowed"); - - call(directory.getKey()); + assertThatThrownBy(() -> call(directory.getKey())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Component of scope 'DIR' is not allowed"); } @Test @@ -310,17 +307,15 @@ public class IssuesActionTest { ComponentDto project = db.components().insertPrivateProject(); ComponentDto file = db.components().insertComponent(newFileDto(project)); - expectedException.expect(ForbiddenException.class); - - tester.newRequest().setParam("key", file.getKey()).execute(); + assertThatThrownBy(() -> tester.newRequest().setParam("key", file.getKey()).execute()) + .isInstanceOf(ForbiddenException.class); } @Test public void fail_if_component_does_not_exist() { - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Component key 'does_not_exist' not found"); - - tester.newRequest().setParam("key", "does_not_exist").execute(); + assertThatThrownBy(() -> tester.newRequest().setParam("key", "does_not_exist").execute()) + .isInstanceOf(NotFoundException.class) + .hasMessage("Component key 'does_not_exist' not found"); } @Test @@ -329,13 +324,14 @@ public class IssuesActionTest { db.components().insertProjectBranch(project, b -> b.setKey("my_branch")); addPermissionTo(project); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(format("Component '%s' on branch 'does_not_exist' not found", project.getKey())); - - tester.newRequest() - .setParam("key",project.getKey()) - .setParam("branch", "does_not_exist") - .execute(); + assertThatThrownBy(() -> { + tester.newRequest() + .setParam("key",project.getKey()) + .setParam("branch", "does_not_exist") + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage(format("Component '%s' on branch 'does_not_exist' not found", project.getKey())); } private void addPermissionTo(ComponentDto project) { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/batch/ProjectDataLoaderTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/batch/ProjectDataLoaderTest.java index 41147c8d996..ea9d8351dbb 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/batch/ProjectDataLoaderTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/batch/ProjectDataLoaderTest.java @@ -21,7 +21,6 @@ package org.sonar.server.batch; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.resources.Qualifiers; import org.sonar.api.resources.Scopes; @@ -45,6 +44,7 @@ import org.sonar.server.tester.UserSessionRule; import static com.google.common.collect.ImmutableList.of; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.sonar.core.permission.GlobalPermissions.SCAN_EXECUTION; @@ -55,8 +55,6 @@ public class ProjectDataLoaderTest { @Rule public DbTester db = DbTester.create(); @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Rule public UserSessionRule userSession = UserSessionRule.standalone(); private DbClient dbClient = db.getDbClient(); @@ -71,12 +69,13 @@ public class ProjectDataLoaderTest { ComponentDto project = db.components().insertPrivateProject(); userSession.logIn().addProjectPermission(SCAN_EXECUTION, project); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(format("Component '%s' on branch '%s' not found", project.getKey(), "unknown_branch")); - - underTest.load(ProjectDataQuery.create() - .setProjectKey(project.getKey()) - .setBranch("unknown_branch")); + assertThatThrownBy(() -> { + underTest.load(ProjectDataQuery.create() + .setProjectKey(project.getKey()) + .setBranch("unknown_branch")); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage(format("Component '%s' on branch '%s' not found", project.getKey(), "unknown_branch")); } @Test @@ -144,27 +143,24 @@ public class ProjectDataLoaderTest { @Test public void fails_with_NPE_if_query_is_null() { - expectedException.expect(NullPointerException.class); - - underTest.load(null); + assertThatThrownBy(() -> underTest.load(null)) + .isInstanceOf(NullPointerException.class); } @Test public void fails_with_NFE_if_query_is_empty() { - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Component key 'null' not found"); - - underTest.load(ProjectDataQuery.create()); + assertThatThrownBy(() -> underTest.load(ProjectDataQuery.create())) + .isInstanceOf(NotFoundException.class) + .hasMessage("Component key 'null' not found"); } @Test public void throws_NotFoundException_if_component_does_not_exist() { String key = "theKey"; - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Component key 'theKey' not found"); - - underTest.load(ProjectDataQuery.create().setProjectKey(key)); + assertThatThrownBy(() -> underTest.load(ProjectDataQuery.create().setProjectKey(key))) + .isInstanceOf(NotFoundException.class) + .hasMessage("Component key 'theKey' not found"); } @Test @@ -204,10 +200,9 @@ public class ProjectDataLoaderTest { ComponentDto project = db.components().insertPrivateProject(); userSession.logIn(); - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("You're not authorized to push analysis results to the SonarQube server. Please contact your SonarQube administrator."); - - underTest.load(ProjectDataQuery.create().setProjectKey(project.getKey())); + assertThatThrownBy(() -> underTest.load(ProjectDataQuery.create().setProjectKey(project.getKey()))) + .isInstanceOf(ForbiddenException.class) + .hasMessage("You're not authorized to push analysis results to the SonarQube server. Please contact your SonarQube administrator."); } private static FileSourceDto newFileSourceDto(ComponentDto file) { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/branch/pr/ws/DeleteActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/branch/pr/ws/DeleteActionTest.java index de09ee66f41..4ca77aa68e1 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/branch/pr/ws/DeleteActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/branch/pr/ws/DeleteActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.branch.pr.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; @@ -39,14 +38,13 @@ import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.sonar.db.component.BranchType.PULL_REQUEST; public class DeleteActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester db = DbTester.create(System2.INSTANCE); @@ -88,28 +86,25 @@ public class DeleteActionTest { public void fail_if_missing_project_parameter() { userSession.logIn(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The 'project' parameter is missing"); - - ws.newRequest().execute(); + assertThatThrownBy(() -> ws.newRequest().execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("The 'project' parameter is missing"); } @Test public void fail_if_missing_pull_request_parameter() { userSession.logIn(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The 'pullRequest' parameter is missing"); - - ws.newRequest().setParam("project", "projectName").execute(); + assertThatThrownBy(() -> ws.newRequest().setParam("project", "projectName").execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("The 'pullRequest' parameter is missing"); } @Test public void fail_if_not_logged_in() { - expectedException.expect(UnauthorizedException.class); - expectedException.expectMessage("Authentication is required"); - - ws.newRequest().execute(); + assertThatThrownBy(() -> ws.newRequest().execute()) + .isInstanceOf(UnauthorizedException.class) + .hasMessageContaining("Authentication is required"); } @Test @@ -117,26 +112,24 @@ public class DeleteActionTest { ComponentDto project = db.components().insertPrivateProject(p -> p.setDbKey("orwell")); userSession.logIn().addProjectPermission(UserRole.ADMIN, project); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Pull request '1984' is not found for project 'orwell'"); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("project", project.getDbKey()) .setParam("pullRequest", "1984") - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("Pull request '1984' is not found for project 'orwell'"); } @Test public void fail_if_project_does_not_exist() { userSession.logIn(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Project 'foo' not found"); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("project", "foo") .setParam("pullRequest", "123") - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("Project 'foo' not found"); } private void verifyDeletedKey(String key) { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/branch/pr/ws/ListActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/branch/pr/ws/ListActionTest.java index 0fb56925660..c428da10c60 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/branch/pr/ws/ListActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/branch/pr/ws/ListActionTest.java @@ -22,7 +22,6 @@ package org.sonar.server.branch.pr.ws; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.resources.ResourceTypes; import org.sonar.api.server.ws.Change; import org.sonar.api.server.ws.WebService; @@ -55,6 +54,7 @@ import org.sonarqube.ws.ProjectPullRequests.PullRequest; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.api.issue.Issue.RESOLUTION_FALSE_POSITIVE; import static org.sonar.api.issue.Issue.RESOLUTION_FIXED; @@ -76,8 +76,6 @@ import static org.sonarqube.ws.ProjectPullRequests.Status; public class ListActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester db = DbTester.create(System2.INSTANCE); @Rule @@ -408,20 +406,18 @@ public class ListActionTest { userSession.logIn().addProjectPermission(UserRole.USER, project); ComponentDto branch = db.components().insertProjectBranch(project); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(format("Project '%s' not found", branch.getDbKey())); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("project", branch.getDbKey()) - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining(format("Project '%s' not found", branch.getDbKey())); } @Test public void fail_if_missing_project_parameter() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The 'project' parameter is missing"); - - ws.newRequest().execute(); + assertThatThrownBy(() -> ws.newRequest().execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("The 'project' parameter is missing"); } @Test @@ -430,22 +426,16 @@ public class ListActionTest { ComponentDto file = db.components().insertComponent(ComponentTesting.newFileDto(project)); userSession.logIn().addProjectPermission(UserRole.USER, project); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Project '" + file.getDbKey() + "' not found"); - - ws.newRequest() - .setParam("project", file.getDbKey()) - .execute(); + assertThatThrownBy(() -> ws.newRequest().setParam("project", file.getDbKey()).execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("Project '" + file.getDbKey() + "' not found"); } @Test public void fail_if_project_does_not_exist() { - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Project 'foo' not found"); - - ws.newRequest() - .setParam("project", "foo") - .execute(); + assertThatThrownBy(() -> ws.newRequest().setParam("project", "foo").execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("Project 'foo' not found"); } @Test @@ -458,11 +448,8 @@ public class ListActionTest { .setPullRequestData(DbProjectBranches.PullRequestData.newBuilder().setBranch("feature/bar").build())); userSession.logIn().addProjectPermission(CODEVIEWER, project); - expectedException.expect(ForbiddenException.class); - - ws.newRequest() - .setParam("project", project.getDbKey()) - .execute(); + assertThatThrownBy(() -> ws.newRequest().setParam("project", project.getDbKey()).execute()) + .isInstanceOf(ForbiddenException.class); } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/branch/ws/DeleteActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/branch/ws/DeleteActionTest.java index 79415ce47d2..3d0a900bbeb 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/branch/ws/DeleteActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/branch/ws/DeleteActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.branch.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; @@ -42,13 +41,12 @@ import org.sonar.server.ws.WsActionTester; import static java.util.Collections.singleton; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; public class DeleteActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester db = DbTester.create(System2.INSTANCE); @@ -81,28 +79,25 @@ public class DeleteActionTest { public void fail_if_missing_project_parameter() { userSession.logIn(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The 'project' parameter is missing"); - - tester.newRequest().execute(); + assertThatThrownBy(() -> tester.newRequest().execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("The 'project' parameter is missing"); } @Test public void fail_if_missing_branch_parameter() { userSession.logIn(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The 'branch' parameter is missing"); - - tester.newRequest().setParam("project", "projectName").execute(); + assertThatThrownBy(() -> tester.newRequest().setParam("project", "projectName").execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("The 'branch' parameter is missing"); } @Test public void fail_if_not_logged_in() { - expectedException.expect(UnauthorizedException.class); - expectedException.expectMessage("Authentication is required"); - - tester.newRequest().execute(); + assertThatThrownBy(() -> tester.newRequest().execute()) + .isInstanceOf(UnauthorizedException.class) + .hasMessageContaining("Authentication is required"); } @Test @@ -110,26 +105,24 @@ public class DeleteActionTest { ComponentDto project = db.components().insertPrivateProject(); userSession.logIn().addProjectPermission(UserRole.ADMIN, project); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Branch 'branch1' not found"); - - tester.newRequest() + assertThatThrownBy(() -> tester.newRequest() .setParam("project", project.getDbKey()) .setParam("branch", "branch1") - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("Branch 'branch1' not found"); } @Test public void fail_if_project_does_not_exist() { userSession.logIn(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Project 'foo' not found"); - - tester.newRequest() + assertThatThrownBy(() -> tester.newRequest() .setParam("project", "foo") .setParam("branch", "branch1") - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("Project 'foo' not found"); } @Test @@ -139,13 +132,12 @@ public class DeleteActionTest { userSession.logIn().addProjectPermission(UserRole.ADMIN, project); // not found because the DB keys don't contain the name - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Only non-main branches can be deleted"); - - tester.newRequest() + assertThatThrownBy(() -> tester.newRequest() .setParam("project", project.getKey()) .setParam("branch", "main") - .execute(); + .execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Only non-main branches can be deleted"); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/branch/ws/ListActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/branch/ws/ListActionTest.java index 4ab7125fc8d..7e031ea2484 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/branch/ws/ListActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/branch/ws/ListActionTest.java @@ -22,7 +22,6 @@ package org.sonar.server.branch.ws; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.resources.ResourceTypes; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; @@ -48,6 +47,7 @@ import org.sonarqube.ws.ProjectBranches.ListWsResponse; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.Mockito.mock; import static org.sonar.api.measures.CoreMetrics.ALERT_STATUS_KEY; @@ -63,8 +63,6 @@ import static org.sonar.test.JsonAssert.assertJson; public class ListActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester db = DbTester.create(System2.INSTANCE); @Rule @@ -271,20 +269,18 @@ public class ListActionTest { userSession.logIn().addProjectPermission(USER, project); ComponentDto branch = db.components().insertProjectBranch(project); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(format("Project '%s' not found", branch.getDbKey())); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("project", branch.getDbKey()) - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining(format("Project '%s' not found", branch.getDbKey())); } @Test public void fail_if_missing_project_parameter() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The 'project' parameter is missing"); - - ws.newRequest().execute(); + assertThatThrownBy(() -> ws.newRequest().execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("The 'project' parameter is missing"); } @Test @@ -293,22 +289,16 @@ public class ListActionTest { ComponentDto file = db.components().insertComponent(ComponentTesting.newFileDto(project)); userSession.logIn().addProjectPermission(USER, project); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Project '" + file.getDbKey() + "' not found"); - - ws.newRequest() - .setParam("project", file.getDbKey()) - .execute(); + assertThatThrownBy(() -> ws.newRequest().setParam("project", file.getDbKey()).execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("Project '" + file.getDbKey() + "' not found"); } @Test public void fail_if_project_does_not_exist() { - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Project 'foo' not found"); - - ws.newRequest() - .setParam("project", "foo") - .execute(); + assertThatThrownBy(() -> ws.newRequest().setParam("project", "foo").execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("Project 'foo' not found"); } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/branch/ws/RenameActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/branch/ws/RenameActionTest.java index 4b550ba71a7..9d6afc3aed7 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/branch/ws/RenameActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/branch/ws/RenameActionTest.java @@ -22,7 +22,6 @@ package org.sonar.server.branch.ws; import java.util.Optional; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.resources.ResourceTypes; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; @@ -39,11 +38,10 @@ import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.resources.Qualifiers.PROJECT; public class RenameActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester db = DbTester.create(System2.INSTANCE); @Rule @@ -67,28 +65,25 @@ public class RenameActionTest { public void fail_if_missing_project_parameter() { userSession.logIn(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The 'project' parameter is missing"); - - tester.newRequest().execute(); + assertThatThrownBy(() -> tester.newRequest().execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("The 'project' parameter is missing"); } @Test public void fail_if_missing_branch_parameter() { userSession.logIn(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The 'name' parameter is missing"); - - tester.newRequest().setParam("project", "projectName").execute(); + assertThatThrownBy(() -> tester.newRequest().setParam("project", "projectName").execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("The 'name' parameter is missing"); } @Test public void fail_if_not_logged_in() { - expectedException.expect(UnauthorizedException.class); - expectedException.expectMessage("Authentication is required"); - - tester.newRequest().execute(); + assertThatThrownBy(() -> tester.newRequest().execute()) + .isInstanceOf(UnauthorizedException.class) + .hasMessageContaining("Authentication is required"); } @Test @@ -96,13 +91,12 @@ public class RenameActionTest { userSession.logIn(); ComponentDto project = db.components().insertPublicProject(); - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - - tester.newRequest() + assertThatThrownBy(() -> tester.newRequest() .setParam("project", project.getKey()) .setParam("name", "branch1") - .execute(); + .execute()) + .isInstanceOf(ForbiddenException.class) + .hasMessageContaining("Insufficient privileges"); } @Test @@ -157,25 +151,23 @@ public class RenameActionTest { userSession.addProjectPermission(UserRole.ADMIN, project); db.components().insertProjectBranch(project, b -> b.setKey("branch")); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Impossible to update branch name: a branch with name \"branch\" already exists"); - - tester.newRequest() + assertThatThrownBy(() -> tester.newRequest() .setParam("project", project.getKey()) .setParam("name", "branch") - .execute(); + .execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Impossible to update branch name: a branch with name \"branch\" already exists"); } @Test public void fail_if_project_does_not_exist() { userSession.logIn(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Project 'foo' not found"); - - tester.newRequest() + assertThatThrownBy(() -> tester.newRequest() .setParam("project", "foo") .setParam("name", "branch1") - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("Project 'foo' not found"); } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/branch/ws/SetAutomaticDeletionProtectionActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/branch/ws/SetAutomaticDeletionProtectionActionTest.java index bbbb988b148..47909bebb2e 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/branch/ws/SetAutomaticDeletionProtectionActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/branch/ws/SetAutomaticDeletionProtectionActionTest.java @@ -22,7 +22,6 @@ package org.sonar.server.branch.ws; import java.util.Optional; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.resources.ResourceTypes; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; @@ -39,12 +38,11 @@ import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.resources.Qualifiers.PROJECT; public class SetAutomaticDeletionProtectionActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester db = DbTester.create(System2.INSTANCE); @Rule @@ -68,43 +66,39 @@ public class SetAutomaticDeletionProtectionActionTest { public void fail_if_missing_project_parameter() { userSession.logIn(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The 'project' parameter is missing"); - - tester.newRequest().execute(); + assertThatThrownBy(() -> tester.newRequest().execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("The 'project' parameter is missing"); } @Test public void fail_if_missing_branch_parameter() { userSession.logIn(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The 'branch' parameter is missing"); - - tester.newRequest() + assertThatThrownBy(() -> tester.newRequest() .setParam("project", "projectName") - .execute(); + .execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("The 'branch' parameter is missing"); } @Test public void fail_if_missing_value_parameter() { userSession.logIn(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The 'value' parameter is missing"); - - tester.newRequest() + assertThatThrownBy(() -> tester.newRequest() .setParam("project", "projectName") .setParam("branch", "foobar") - .execute(); + .execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("The 'value' parameter is missing"); } @Test public void fail_if_not_logged_in() { - expectedException.expect(UnauthorizedException.class); - expectedException.expectMessage("Authentication is required"); - - tester.newRequest().execute(); + assertThatThrownBy(() -> tester.newRequest().execute()) + .isInstanceOf(UnauthorizedException.class) + .hasMessageContaining("Authentication is required"); } @Test @@ -112,14 +106,13 @@ public class SetAutomaticDeletionProtectionActionTest { userSession.logIn(); ComponentDto project = db.components().insertPublicProject(); - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - - tester.newRequest() + assertThatThrownBy(() -> tester.newRequest() .setParam("project", project.getKey()) .setParam("branch", "branch1") .setParam("value", "true") - .execute(); + .execute()) + .isInstanceOf(ForbiddenException.class) + .hasMessageContaining("Insufficient privileges"); } @Test @@ -128,14 +121,14 @@ public class SetAutomaticDeletionProtectionActionTest { ComponentDto project = db.components().insertPublicProject(); ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey("branch1").setExcludeFromPurge(false)); userSession.addProjectPermission(UserRole.ADMIN, project); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Main branch of the project is always excluded from automatic deletion."); - tester.newRequest() + assertThatThrownBy(() -> tester.newRequest() .setParam("project", project.getKey()) .setParam("branch", "master") .setParam("value", "false") - .execute(); + .execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Main branch of the project is always excluded from automatic deletion."); } @Test @@ -166,28 +159,26 @@ public class SetAutomaticDeletionProtectionActionTest { userSession.logIn(); ComponentDto project = db.components().insertPublicProject(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Value of parameter 'value' (foobar) must be one of: [true, false, yes, no]"); - - tester.newRequest() + assertThatThrownBy(() -> tester.newRequest() .setParam("project", project.getKey()) .setParam("branch", "branch1") .setParam("value", "foobar") - .execute(); + .execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Value of parameter 'value' (foobar) must be one of: [true, false, yes, no]"); } @Test public void fail_if_project_does_not_exist() { userSession.logIn(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Project 'foo' not found"); - - tester.newRequest() + assertThatThrownBy(() -> tester.newRequest() .setParam("project", "foo") .setParam("branch", "branch1") .setParam("value", "true") - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("Project 'foo' not found"); } @Test @@ -196,13 +187,12 @@ public class SetAutomaticDeletionProtectionActionTest { ComponentDto project = db.components().insertPublicProject(); userSession.addProjectPermission(UserRole.ADMIN, project); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Branch 'branch1' not found for project '" + project.getKey() + "'"); - - tester.newRequest() + assertThatThrownBy(() -> tester.newRequest() .setParam("project", project.getKey()) .setParam("branch", "branch1") .setParam("value", "true") - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("Branch 'branch1' not found for project '" + project.getKey() + "'"); } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/ws/CancelActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/ws/CancelActionTest.java index ca09df9ba15..9ec1598ccc1 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/ws/CancelActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/ws/CancelActionTest.java @@ -22,7 +22,6 @@ package org.sonar.server.ce.ws; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.impl.utils.TestSystem2; import org.sonar.api.utils.System2; import org.sonar.api.web.UserRole; @@ -42,14 +41,13 @@ import org.sonar.server.ws.WsActionTester; import static java.util.Collections.emptyMap; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class CancelActionTest { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Rule public DbTester db = DbTester.create(); private System2 system2 = new TestSystem2(); @@ -122,10 +120,9 @@ public class CancelActionTest { public void throw_IllegalArgumentException_if_missing_id() { logInAsSystemAdministrator(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The 'id' parameter is missing"); - - tester.newRequest().execute(); + assertThatThrownBy(() -> tester.newRequest().execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("The 'id' parameter is missing"); } @Test @@ -134,12 +131,13 @@ public class CancelActionTest { ComponentDto project = db.components().insertPrivateProject(); CeQueueDto queue = createTaskSubmit(project); - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - - tester.newRequest() - .setParam("id", queue.getUuid()) - .execute(); + assertThatThrownBy(() -> { + tester.newRequest() + .setParam("id", queue.getUuid()) + .execute(); + }) + .isInstanceOf(ForbiddenException.class) + .hasMessage("Insufficient privileges"); } @Test @@ -147,12 +145,13 @@ public class CancelActionTest { userSession.logIn().setNonSystemAdministrator(); CeQueueDto queue = createTaskSubmit(null); - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - - tester.newRequest() - .setParam("id", queue.getUuid()) - .execute(); + assertThatThrownBy(() -> { + tester.newRequest() + .setParam("id", queue.getUuid()) + .execute(); + }) + .isInstanceOf(ForbiddenException.class) + .hasMessage("Insufficient privileges"); } @Test @@ -160,12 +159,13 @@ public class CancelActionTest { userSession.logIn().setNonSystemAdministrator(); CeQueueDto queue = createTaskSubmit(nonExistentComponentDot()); - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - - tester.newRequest() - .setParam("id", queue.getUuid()) - .execute(); + assertThatThrownBy(() -> { + tester.newRequest() + .setParam("id", queue.getUuid()) + .execute(); + }) + .isInstanceOf(ForbiddenException.class) + .hasMessage("Insufficient privileges"); } private static ComponentDto nonExistentComponentDot() { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/ws/CancelAllActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/ws/CancelAllActionTest.java index 7ce35cb3655..eddce021364 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/ws/CancelAllActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/ws/CancelAllActionTest.java @@ -21,12 +21,12 @@ package org.sonar.server.ce.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.ce.queue.CeQueue; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.WsActionTester; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; @@ -36,8 +36,6 @@ public class CancelAllActionTest { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private CeQueue queue = mock(CeQueue.class); private CancelAllAction underTest = new CancelAllAction(userSession, queue); @@ -56,12 +54,12 @@ public class CancelAllActionTest { public void throw_ForbiddenException_if_not_system_administrator() { userSession.logIn().setNonSystemAdministrator(); - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - - call(); - - verifyZeroInteractions(queue); + assertThatThrownBy(() -> { + call(); + verifyZeroInteractions(queue); + }) + .isInstanceOf(ForbiddenException.class) + .hasMessage("Insufficient privileges"); } private void call() { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/ws/InfoActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/ws/InfoActionTest.java index b2935055daf..c36eb3031d8 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/ws/InfoActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/ws/InfoActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.ce.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.ce.queue.CeQueue; import org.sonar.server.exceptions.ForbiddenException; @@ -31,14 +30,13 @@ import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.Ce; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class InfoActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @@ -95,10 +93,9 @@ public class InfoActionTest { public void throw_ForbiddenException_if_not_system_administrator() { userSession.logIn().setNonSystemAdministrator(); - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - - ws.newRequest().execute(); + assertThatThrownBy(() -> ws.newRequest().execute()) + .isInstanceOf(ForbiddenException.class) + .hasMessage("Insufficient privileges"); } @Test @@ -106,10 +103,9 @@ public class InfoActionTest { userSession.anonymous(); when(passcode.isValid(any())).thenReturn(false); - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - - ws.newRequest().execute(); + assertThatThrownBy(() -> ws.newRequest().execute()) + .isInstanceOf(ForbiddenException.class) + .hasMessage("Insufficient privileges"); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/ws/PauseActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/ws/PauseActionTest.java index ebd5d44534f..885f37e5fb1 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/ws/PauseActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/ws/PauseActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.ce.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.ce.queue.CeQueue; import org.sonar.server.exceptions.ForbiddenException; @@ -30,6 +29,7 @@ import org.sonar.server.user.SystemPasscode; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -37,8 +37,6 @@ import static org.mockito.Mockito.when; public class PauseActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @@ -70,10 +68,9 @@ public class PauseActionTest { public void throw_ForbiddenException_if_not_system_administrator() { userSession.logIn().setNonSystemAdministrator(); - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - - ws.newRequest().execute(); + assertThatThrownBy(() -> ws.newRequest().execute()) + .isInstanceOf(ForbiddenException.class) + .hasMessage("Insufficient privileges"); } @Test @@ -81,10 +78,9 @@ public class PauseActionTest { userSession.anonymous(); when(passcode.isValid(any())).thenReturn(false); - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - - ws.newRequest().execute(); + assertThatThrownBy(() -> ws.newRequest().execute()) + .isInstanceOf(ForbiddenException.class) + .hasMessage("Insufficient privileges"); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/ws/ResumeActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/ws/ResumeActionTest.java index 05a34eb82c1..e0e511fe657 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/ws/ResumeActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/ws/ResumeActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.ce.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.ce.queue.CeQueue; import org.sonar.server.exceptions.ForbiddenException; @@ -30,6 +29,7 @@ import org.sonar.server.user.SystemPasscode; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -37,8 +37,6 @@ import static org.mockito.Mockito.when; public class ResumeActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @@ -70,10 +68,9 @@ public class ResumeActionTest { public void throw_ForbiddenException_if_not_system_administrator() { userSession.logIn().setNonSystemAdministrator(); - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - - ws.newRequest().execute(); + assertThatThrownBy(() -> ws.newRequest().execute()) + .isInstanceOf(ForbiddenException.class) + .hasMessage("Insufficient privileges"); } @Test @@ -81,10 +78,9 @@ public class ResumeActionTest { userSession.anonymous(); when(passcode.isValid(any())).thenReturn(false); - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - - ws.newRequest().execute(); + assertThatThrownBy(() -> ws.newRequest().execute()) + .isInstanceOf(ForbiddenException.class) + .hasMessage("Insufficient privileges"); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/ws/WorkerCountActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/ws/WorkerCountActionTest.java index 766e4075802..7a04e556559 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/ws/WorkerCountActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ce/ws/WorkerCountActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.ce.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.ce.configuration.WorkerCountProvider; import org.sonar.server.exceptions.ForbiddenException; @@ -30,14 +29,13 @@ import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.Ce.WorkerCountResponse; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.test.JsonAssert.assertJson; public class WorkerCountActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @@ -71,9 +69,8 @@ public class WorkerCountActionTest { userSession.logIn().setNonSystemAdministrator(); WsActionTester ws = new WsActionTester(new WorkerCountAction(userSession)); - expectedException.expect(ForbiddenException.class); - - ws.newRequest().execute(); + assertThatThrownBy(() -> ws.newRequest().execute()) + .isInstanceOf(ForbiddenException.class); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/component/ws/ProjectMeasuresQueryFactoryTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/component/ws/ProjectMeasuresQueryFactoryTest.java index 8c15775f724..19d5771675b 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/component/ws/ProjectMeasuresQueryFactoryTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/component/ws/ProjectMeasuresQueryFactoryTest.java @@ -23,7 +23,6 @@ import java.util.Collections; import java.util.List; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.server.component.ws.FilterParser.Criterion; import org.sonar.server.measure.index.ProjectMeasuresQuery; import org.sonar.server.measure.index.ProjectMeasuresQuery.MetricCriterion; @@ -34,6 +33,7 @@ import static java.util.Collections.emptyList; import static java.util.Collections.emptySet; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.server.component.ws.ProjectMeasuresQueryFactory.newProjectMeasuresQuery; import static org.sonar.server.measure.index.ProjectMeasuresQuery.Operator; @@ -45,8 +45,6 @@ import static org.sonar.server.measure.index.ProjectMeasuresQuery.Operator.LTE; public class ProjectMeasuresQueryFactoryTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @@ -67,29 +65,32 @@ public class ProjectMeasuresQueryFactoryTest { @Test public void fail_when_no_value() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Value cannot be null for 'ncloc'"); - - newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("ncloc").setOperator(GT).setValue(null).build()), - emptySet()); + assertThatThrownBy(() -> { + newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("ncloc").setOperator(GT).setValue(null).build()), + emptySet()); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Value cannot be null for 'ncloc'"); } @Test public void fail_when_not_double() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Value 'ten' is not a number"); - - newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("ncloc").setOperator(GT).setValue("ten").build()), - emptySet()); + assertThatThrownBy(() -> { + newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("ncloc").setOperator(GT).setValue("ten").build()), + emptySet()); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Value 'ten' is not a number"); } @Test public void fail_when_no_operator() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Operator cannot be null for 'ncloc'"); - - newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("ncloc").setOperator(null).setValue("ten").build()), - emptySet()); + assertThatThrownBy(() -> { + newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("ncloc").setOperator(null).setValue("ten").build()), + emptySet()); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Operator cannot be null for 'ncloc'"); } @Test @@ -102,18 +103,20 @@ public class ProjectMeasuresQueryFactoryTest { @Test public void fail_to_create_query_on_quality_gate_when_operator_is_not_equal() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Only equals operator is available for quality gate criteria"); - - newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("alert_status").setOperator(GT).setValue("OK").build()), emptySet()); + assertThatThrownBy(() -> { + newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("alert_status").setOperator(GT).setValue("OK").build()), emptySet()); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Only equals operator is available for quality gate criteria"); } @Test public void fail_to_create_query_on_quality_gate_when_value_is_incorrect() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Unknown quality gate status : 'unknown'"); - - newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("alert_status").setOperator(EQ).setValue("unknown").build()), emptySet()); + assertThatThrownBy(() -> { + newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("alert_status").setOperator(EQ).setValue("unknown").build()), emptySet()); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Unknown quality gate status : 'unknown'"); } @Test @@ -126,18 +129,20 @@ public class ProjectMeasuresQueryFactoryTest { @Test public void fail_to_create_query_on_qualifier_when_operator_is_not_equal() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Only equals operator is available for qualifier criteria"); - - newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("qualifier").setOperator(GT).setValue("APP").build()), emptySet()); + assertThatThrownBy(() -> { + newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("qualifier").setOperator(GT).setValue("APP").build()), emptySet()); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Only equals operator is available for qualifier criteria"); } @Test public void fail_to_create_query_on_qualifier_when_value_is_incorrect() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Unknown qualifier : 'unknown'"); - - newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("qualifier").setOperator(EQ).setValue("unknown").build()), emptySet()); + assertThatThrownBy(() -> { + newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("qualifier").setOperator(EQ).setValue("unknown").build()), emptySet()); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Unknown qualifier : 'unknown'"); } @Test @@ -160,18 +165,20 @@ public class ProjectMeasuresQueryFactoryTest { @Test public void fail_to_create_query_on_language_using_in_operator_and_value() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Languages should be set either by using 'languages = java' or 'languages IN (java, js)"); - - newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("languages").setOperator(IN).setValue("java").build()), emptySet()); + assertThatThrownBy(() -> { + newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("languages").setOperator(IN).setValue("java").build()), emptySet()); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Languages should be set either by using 'languages = java' or 'languages IN (java, js)'"); } @Test public void fail_to_create_query_on_language_using_eq_operator_and_values() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Languages should be set either by using 'languages = java' or 'languages IN (java, js)"); - - newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("languages").setOperator(EQ).setValues(asList("java")).build()), emptySet()); + assertThatThrownBy(() -> { + newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("languages").setOperator(EQ).setValues(asList("java")).build()), emptySet()); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Languages should be set either by using 'languages = java' or 'languages IN (java, js)'"); } @Test @@ -194,18 +201,20 @@ public class ProjectMeasuresQueryFactoryTest { @Test public void fail_to_create_query_on_tag_using_in_operator_and_value() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Tags should be set either by using 'tags = java' or 'tags IN (finance, platform)"); - - newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("tags").setOperator(IN).setValue("java").build()), emptySet()); + assertThatThrownBy(() -> { + newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("tags").setOperator(IN).setValue("java").build()), emptySet()); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Tags should be set either by using 'tags = java' or 'tags IN (finance, platform)'"); } @Test public void fail_to_create_query_on_tag_using_eq_operator_and_values() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Tags should be set either by using 'tags = java' or 'tags IN (finance, platform)"); - - newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("tags").setOperator(EQ).setValues(asList("java")).build()), emptySet()); + assertThatThrownBy(() -> { + newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("tags").setOperator(EQ).setValues(asList("java")).build()), emptySet()); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Tags should be set either by using 'tags = java' or 'tags IN (finance, platform)'"); } @Test @@ -228,20 +237,22 @@ public class ProjectMeasuresQueryFactoryTest { @Test public void fail_to_create_query_having_q_with_no_value() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Query is invalid"); - - newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("query").setOperator(EQ).build()), - emptySet()); + assertThatThrownBy(() -> { + newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("query").setOperator(EQ).build()), + emptySet()); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Query is invalid"); } @Test public void fail_to_create_query_having_q_with_other_operator_than_equals() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Query should only be used with equals operator"); - - newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("query").setOperator(LT).setValue("java").build()), - emptySet()); + assertThatThrownBy(() -> { + newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("query").setOperator(LT).setValue("java").build()), + emptySet()); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Query should only be used with equals operator"); } @Test @@ -310,10 +321,10 @@ public class ProjectMeasuresQueryFactoryTest { @Test public void fail_to_use_no_data_with_operator_lower_than() { List criteria = singletonList(Criterion.builder().setKey("duplicated_lines_density").setOperator(LT).setValue("NO_DATA").build()); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("NO_DATA can only be used with equals operator"); - newProjectMeasuresQuery(criteria, emptySet()); + assertThatThrownBy(() -> newProjectMeasuresQuery(criteria, emptySet())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("NO_DATA can only be used with equals operator"); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/component/ws/ProjectMeasuresQueryValidatorTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/component/ws/ProjectMeasuresQueryValidatorTest.java index f77edb8e8ea..d02e7cb8e3f 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/component/ws/ProjectMeasuresQueryValidatorTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/component/ws/ProjectMeasuresQueryValidatorTest.java @@ -20,17 +20,14 @@ package org.sonar.server.component.ws; import java.util.Arrays; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.server.measure.index.ProjectMeasuresQuery; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.server.measure.index.ProjectMeasuresQuery.MetricCriterion.create; public class ProjectMeasuresQueryValidatorTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void query_with_empty_metrics_is_valid() { @@ -223,10 +220,9 @@ public class ProjectMeasuresQueryValidatorTest { } private void assertInvalidSortKey(String metricKey) { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Following metrics are not supported: '" + metricKey + "'"); - - ProjectMeasuresQueryValidator.validate(new ProjectMeasuresQuery().setSort(metricKey)); + assertThatThrownBy(() -> ProjectMeasuresQueryValidator.validate(new ProjectMeasuresQuery().setSort(metricKey))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Following metrics are not supported: '" + metricKey + "'"); } private static void assertValidFilterKey(String... metricKeys) { @@ -239,9 +235,9 @@ public class ProjectMeasuresQueryValidatorTest { } private void assertInvalidFilterKeys(String message, String... metricKeys) { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(message); - validateFilterKeys(metricKeys); + assertThatThrownBy(() -> validateFilterKeys(metricKeys)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage(message); } private static void validateFilterKeys(String... metricKeys) { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/developers/ws/SearchEventsActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/developers/ws/SearchEventsActionTest.java index f707f0f7623..35fae9f1080 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/developers/ws/SearchEventsActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/developers/ws/SearchEventsActionTest.java @@ -24,7 +24,6 @@ import java.util.stream.IntStream; import java.util.stream.Stream; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.platform.Server; import org.sonar.api.rules.RuleType; import org.sonar.api.server.ws.WebService; @@ -55,6 +54,7 @@ import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.apache.commons.lang.math.RandomUtils.nextInt; import static org.apache.commons.lang.math.RandomUtils.nextLong; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.argThat; @@ -79,8 +79,6 @@ public class SearchEventsActionTest { public EsTester es = EsTester.create(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private Server server = mock(Server.class); private IssueIndex issueIndex = new IssueIndex(es.client(), null, null, null); private IssueIndexSyncProgressChecker issueIndexSyncProgressChecker = mock(IssueIndexSyncProgressChecker.class); @@ -240,25 +238,27 @@ public class SearchEventsActionTest { userSession.anonymous(); ComponentDto project = db.components().insertPrivateProject(); - expectedException.expect(UnauthorizedException.class); - - ws.newRequest() - .setParam(PARAM_PROJECTS, project.getKey()) - .setParam(PARAM_FROM, formatDateTime(1_000L)) - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam(PARAM_PROJECTS, project.getKey()) + .setParam(PARAM_FROM, formatDateTime(1_000L)) + .execute(); + }) + .isInstanceOf(UnauthorizedException.class); } @Test public void fail_if_date_format_is_not_valid() { userSession.logIn().setRoot(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("'wat' cannot be parsed as either a date or date+time"); - ws.newRequest() - .setParam(PARAM_PROJECTS, "foo") - .setParam(PARAM_FROM, "wat") - .executeProtobuf(SearchEventsWsResponse.class); - + assertThatThrownBy(() -> { + ws.newRequest() + .setParam(PARAM_PROJECTS, "foo") + .setParam(PARAM_FROM, "wat") + .executeProtobuf(SearchEventsWsResponse.class); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("'wat' cannot be parsed as either a date or date+time"); } private static EventDto newQualityGateEvent(SnapshotDto analysis) { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/email/ws/SendActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/email/ws/SendActionTest.java index 899c3da6e11..3fd28f80fc5 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/email/ws/SendActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/email/ws/SendActionTest.java @@ -23,7 +23,6 @@ import javax.annotation.Nullable; import org.apache.commons.mail.EmailException; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.ForbiddenException; @@ -33,6 +32,7 @@ import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doThrow; @@ -41,8 +41,6 @@ import static org.mockito.Mockito.verify; public class SendActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @@ -73,28 +71,29 @@ public class SendActionTest { public void fail_when_to_param_is_missing() { logInAsSystemAdministrator(); - expectedException.expect(IllegalArgumentException.class); - - executeRequest(null, "Test Message from SonarQube", "This is a test message from SonarQube at http://localhost:9000"); + assertThatThrownBy(() -> { + executeRequest(null, "Test Message from SonarQube", "This is a test message from SonarQube at http://localhost:9000"); + }) + .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_when_message_param_is_missing() { logInAsSystemAdministrator(); - expectedException.expect(IllegalArgumentException.class); - - executeRequest("john@doo.com", "Test Message from SonarQube", null); + assertThatThrownBy(() -> { + executeRequest("john@doo.com", "Test Message from SonarQube", null); + }) + .isInstanceOf(IllegalArgumentException.class); } @Test public void throw_ForbiddenException_if_not_system_administrator() { userSession.logIn().setNonSystemAdministrator(); - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - - ws.newRequest().execute(); + assertThatThrownBy(() -> ws.newRequest().execute()) + .isInstanceOf(ForbiddenException.class) + .hasMessage("Insufficient privileges"); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/favorite/ws/AddActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/favorite/ws/AddActionTest.java index 9a0ffe2eca8..76f27fd3b97 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/favorite/ws/AddActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/favorite/ws/AddActionTest.java @@ -23,7 +23,6 @@ import java.util.List; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.api.web.UserRole; import org.sonar.db.DbClient; @@ -47,6 +46,7 @@ import static java.lang.String.format; import static java.net.HttpURLConnection.HTTP_NO_CONTENT; import static java.util.Optional.ofNullable; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.resources.Qualifiers.UNIT_TEST_FILE; import static org.sonar.api.web.UserRole.USER; import static org.sonar.db.component.ComponentTesting.newDirectory; @@ -55,8 +55,6 @@ import static org.sonar.server.favorite.ws.FavoritesWsParameters.PARAM_COMPONENT public class AddActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -92,27 +90,24 @@ public class AddActionTest { ComponentDto project = db.components().insertPrivateProject(); userSession.logIn().addProjectPermission(UserRole.ADMIN, project); - expectedException.expect(ForbiddenException.class); - - call(project.getKey()); + assertThatThrownBy(() -> call(project.getKey())) + .isInstanceOf(ForbiddenException.class); } @Test public void fail_when_component_is_not_found() { userSession.logIn(); - expectedException.expect(NotFoundException.class); - - call("P42"); + assertThatThrownBy(() -> call("P42")) + .isInstanceOf(NotFoundException.class); } @Test public void fail_when_user_is_not_authenticated() { ComponentDto project = db.components().insertPrivateProject(); - expectedException.expect(UnauthorizedException.class); - - call(project.getKey()); + assertThatThrownBy(() -> call(project.getKey())) + .isInstanceOf(UnauthorizedException.class); } @Test @@ -122,10 +117,9 @@ public class AddActionTest { UserDto user = db.users().insertUser(); userSession.logIn(user).addProjectPermission(USER, project); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(format("Component key '%s' not found", branch.getDbKey())); - - call(branch.getDbKey()); + assertThatThrownBy(() -> call(branch.getDbKey())) + .isInstanceOf(NotFoundException.class) + .hasMessage(format("Component key '%s' not found", branch.getDbKey())); } @Test @@ -135,10 +129,9 @@ public class AddActionTest { UserDto user = db.users().insertUser(); userSession.logIn(user).addProjectPermission(USER, project); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Only components with qualifiers TRK, VW, SVW, APP are supported"); - - call(directory.getKey()); + assertThatThrownBy(() -> call(directory.getKey())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Only components with qualifiers TRK, VW, SVW, APP are supported"); } @Test @@ -148,10 +141,9 @@ public class AddActionTest { UserDto user = db.users().insertUser(); userSession.logIn(user).addProjectPermission(USER, project); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Only components with qualifiers TRK, VW, SVW, APP are supported"); - - call(file.getKey()); + assertThatThrownBy(() -> call(file.getKey())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Only components with qualifiers TRK, VW, SVW, APP are supported"); } @Test @@ -161,10 +153,9 @@ public class AddActionTest { UserDto user = db.users().insertUser(); userSession.logIn(user).addProjectPermission(USER, project); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Only components with qualifiers TRK, VW, SVW, APP are supported"); - - call(unitTestFile.getKey()); + assertThatThrownBy(() -> call(unitTestFile.getKey())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Only components with qualifiers TRK, VW, SVW, APP are supported"); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/ClusterHealthTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/ClusterHealthTest.java index fe1ea691913..8778c609662 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/ClusterHealthTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/ClusterHealthTest.java @@ -26,9 +26,7 @@ import java.util.Random; import java.util.Set; import java.util.stream.IntStream; import java.util.stream.Stream; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.process.cluster.health.NodeDetails; import org.sonar.process.cluster.health.NodeHealth; @@ -36,29 +34,26 @@ import static java.util.stream.Collectors.toSet; import static java.util.stream.Stream.concat; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.process.cluster.health.NodeHealth.newNodeHealthBuilder; import static org.sonar.server.health.Health.newHealthCheckBuilder; public class ClusterHealthTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private final Random random = new Random(); @Test public void constructor_fails_with_NPE_if_Health_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("health can't be null"); - - new ClusterHealth(null, Collections.emptySet()); + assertThatThrownBy(() -> new ClusterHealth(null, Collections.emptySet())) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("health can't be null"); } @Test public void constructor_fails_with_NPE_if_NodeHealth_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("nodes can't be null"); - - new ClusterHealth(Health.GREEN, null); + assertThatThrownBy(() -> new ClusterHealth(Health.GREEN, null)) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("nodes can't be null"); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/HealthCheckerImplTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/HealthCheckerImplTest.java index e0c7ac76660..e159818175b 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/HealthCheckerImplTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/HealthCheckerImplTest.java @@ -28,9 +28,7 @@ import java.util.Set; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.process.cluster.health.NodeDetails; import org.sonar.process.cluster.health.NodeHealth; import org.sonar.process.cluster.health.SharedHealthState; @@ -38,20 +36,19 @@ import org.sonar.server.platform.WebServer; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.same; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.sonar.process.cluster.health.NodeDetails.newNodeDetailsBuilder; import static org.sonar.process.cluster.health.NodeHealth.newNodeHealthBuilder; -import static org.sonar.server.health.Health.newHealthCheckBuilder; import static org.sonar.server.health.Health.Status.GREEN; import static org.sonar.server.health.Health.Status.RED; import static org.sonar.server.health.Health.Status.YELLOW; +import static org.sonar.server.health.Health.newHealthCheckBuilder; public class HealthCheckerImplTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private final WebServer webServer = mock(WebServer.class); private final SharedHealthState sharedHealthState = mock(SharedHealthState.class); @@ -92,10 +89,10 @@ public class HealthCheckerImplTest { public void checkNode_returns_RED_status_if_at_least_one_RED_status_returned_by_NodeHealthCheck() { List statuses = new ArrayList<>(); Stream.of( - IntStream.range(0, 1 + random.nextInt(20)).mapToObj(i -> RED), // at least 1 RED - IntStream.range(0, random.nextInt(20)).mapToObj(i -> YELLOW), // between 0 and 19 YELLOW - IntStream.range(0, random.nextInt(20)).mapToObj(i -> GREEN) // between 0 and 19 GREEN - ).flatMap(s -> s) + IntStream.range(0, 1 + random.nextInt(20)).mapToObj(i -> RED), // at least 1 RED + IntStream.range(0, random.nextInt(20)).mapToObj(i -> YELLOW), // between 0 and 19 YELLOW + IntStream.range(0, random.nextInt(20)).mapToObj(i -> GREEN) // between 0 and 19 GREEN + ).flatMap(s -> s) .forEach(statuses::add); Collections.shuffle(statuses); HealthCheckerImpl underTest = newNodeHealthCheckerImpl(statuses.stream()); @@ -123,10 +120,9 @@ public class HealthCheckerImplTest { when(webServer.isStandalone()).thenReturn(true); HealthCheckerImpl underTest = new HealthCheckerImpl(webServer, new NodeHealthCheck[0], new ClusterHealthCheck[0], sharedHealthState); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Clustering is not enabled"); - - underTest.checkCluster(); + assertThatThrownBy(() -> underTest.checkCluster()) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Clustering is not enabled"); } @Test @@ -134,10 +130,9 @@ public class HealthCheckerImplTest { when(webServer.isStandalone()).thenReturn(false); HealthCheckerImpl underTest = new HealthCheckerImpl(webServer, new NodeHealthCheck[0], new ClusterHealthCheck[0], null); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("HealthState instance can't be null when clustering is enabled"); - - underTest.checkCluster(); + assertThatThrownBy(() -> underTest.checkCluster()) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("HealthState instance can't be null when clustering is enabled"); } @Test @@ -179,10 +174,10 @@ public class HealthCheckerImplTest { when(webServer.isStandalone()).thenReturn(false); List statuses = new ArrayList<>(); Stream.of( - IntStream.range(0, 1 + random.nextInt(20)).mapToObj(i -> RED), // at least 1 RED - IntStream.range(0, random.nextInt(20)).mapToObj(i -> YELLOW), // between 0 and 19 YELLOW - IntStream.range(0, random.nextInt(20)).mapToObj(i -> GREEN) // between 0 and 19 GREEN - ).flatMap(s -> s) + IntStream.range(0, 1 + random.nextInt(20)).mapToObj(i -> RED), // at least 1 RED + IntStream.range(0, random.nextInt(20)).mapToObj(i -> YELLOW), // between 0 and 19 YELLOW + IntStream.range(0, random.nextInt(20)).mapToObj(i -> GREEN) // between 0 and 19 GREEN + ).flatMap(s -> s) .forEach(statuses::add); Collections.shuffle(statuses); HealthCheckerImpl underTest = newClusterHealthCheckerImpl(statuses.stream()); diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/HealthTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/HealthTest.java index 52969ca8c90..04976b1e8a7 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/HealthTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/HealthTest.java @@ -25,17 +25,15 @@ import java.util.Set; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.assertj.core.api.AbstractCharSequenceAssert; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.ThrowableAssert.ThrowingCallable; import static org.sonar.server.health.Health.newHealthCheckBuilder; public class HealthTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private final Random random = new Random(); private final Health.Status anyStatus = Health.Status.values()[random.nextInt(Health.Status.values().length)]; @@ -45,18 +43,14 @@ public class HealthTest { public void build_throws_NPE_if_status_is_null() { Health.Builder builder = newHealthCheckBuilder(); - expectStatusNotNullNPE(); - - builder.build(); + expectStatusNotNullNPE(() -> builder.build()); } @Test public void setStatus_throws_NPE_if_status_is_null() { Health.Builder builder = newHealthCheckBuilder(); - expectStatusNotNullNPE(); - - builder.setStatus(null); + expectStatusNotNullNPE(() -> builder.setStatus(null)); } @Test @@ -70,28 +64,23 @@ public class HealthTest { public void addCause_throws_NPE_if_arg_is_null() { Health.Builder builder = newHealthCheckBuilder(); - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("cause can't be null"); - - builder.addCause(null); + assertThatThrownBy(() -> builder.addCause(null)) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("cause can't be null"); } @Test public void addCause_throws_IAE_if_arg_is_empty() { Health.Builder builder = newHealthCheckBuilder(); - expectCauseCannotBeEmptyIAE(); - - builder.addCause(""); + expectCauseCannotBeEmptyIAE(() -> builder.addCause("")); } @Test public void addCause_throws_IAE_if_arg_contains_only_spaces() { Health.Builder builder = newHealthCheckBuilder(); - expectCauseCannotBeEmptyIAE(); - - builder.addCause(Strings.repeat(" ", 1 + random.nextInt(5))); + expectCauseCannotBeEmptyIAE(() -> builder.addCause(Strings.repeat(" ", 1 + random.nextInt(5)))); } @Test @@ -172,13 +161,15 @@ public class HealthTest { } } - private void expectStatusNotNullNPE() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("status can't be null"); + private void expectStatusNotNullNPE(ThrowingCallable shouldRaiseThrowable) { + assertThatThrownBy(shouldRaiseThrowable) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("status can't be null"); } - private void expectCauseCannotBeEmptyIAE() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("cause can't be empty"); + private void expectCauseCannotBeEmptyIAE(ThrowingCallable shouldRaiseThrowable) { + assertThatThrownBy(shouldRaiseThrowable) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("cause can't be empty"); } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/NodeHealthProviderImplTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/NodeHealthProviderImplTest.java index ce3b39068f8..dea98c7042f 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/NodeHealthProviderImplTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/health/NodeHealthProviderImplTest.java @@ -23,9 +23,7 @@ import java.util.Arrays; import java.util.Date; import java.util.Random; import java.util.stream.IntStream; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.platform.Server; import org.sonar.process.NetworkUtils; @@ -35,15 +33,14 @@ import org.sonar.process.cluster.health.NodeHealth; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_HOST; -import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_NAME; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_HZ_PORT; +import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_NAME; public class NodeHealthProviderImplTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private final Random random = new Random(); private MapSettings mapSettings = new MapSettings(); @@ -53,19 +50,17 @@ public class NodeHealthProviderImplTest { @Test public void constructor_throws_ISE_if_node_name_property_is_not_set() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Property sonar.cluster.node.name is not defined"); - - new NodeHealthProviderImpl(mapSettings.asConfig(), healthChecker, server, networkUtils); + assertThatThrownBy(() -> new NodeHealthProviderImpl(mapSettings.asConfig(), healthChecker, server, networkUtils)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Property sonar.cluster.node.name is not defined"); } @Test public void constructor_thows_NPE_if_NetworkUtils_getHostname_returns_null() { mapSettings.setProperty(CLUSTER_NODE_NAME.getKey(), randomAlphanumeric(3)); - expectedException.expect(NullPointerException.class); - - new NodeHealthProviderImpl(mapSettings.asConfig(), healthChecker, server, networkUtils); + assertThatThrownBy(() -> new NodeHealthProviderImpl(mapSettings.asConfig(), healthChecker, server, networkUtils)) + .isInstanceOf(NullPointerException.class); } @Test @@ -73,19 +68,17 @@ public class NodeHealthProviderImplTest { mapSettings.setProperty(CLUSTER_NODE_NAME.getKey(), randomAlphanumeric(3)); when(networkUtils.getHostname()).thenReturn(randomAlphanumeric(23)); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Property sonar.cluster.node.port is not defined"); - - new NodeHealthProviderImpl(mapSettings.asConfig(), healthChecker, server, networkUtils); + assertThatThrownBy(() -> new NodeHealthProviderImpl(mapSettings.asConfig(), healthChecker, server, networkUtils)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Property sonar.cluster.node.port is not defined"); } @Test public void constructor_throws_NPE_is_Server_getStartedAt_is_null() { setRequiredPropertiesForConstructor(); - expectedException.expect(NullPointerException.class); - - new NodeHealthProviderImpl(mapSettings.asConfig(), healthChecker, server, networkUtils); + assertThatThrownBy(() -> new NodeHealthProviderImpl(mapSettings.asConfig(), healthChecker, server, networkUtils)) + .isInstanceOf(NullPointerException.class); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ActionTest.java index 0ead5a8b1a6..a7505536668 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ActionTest.java @@ -21,31 +21,27 @@ package org.sonar.server.issue; import java.util.Collection; import java.util.Map; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.core.issue.DefaultIssue; import org.sonar.server.user.UserSession; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + public class ActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void key_should_not_be_empty() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Action key must be set"); - - new FakeAction(""); + assertThatThrownBy(() -> new FakeAction("")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Action key must be set"); } @Test public void key_should_not_be_null() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Action key must be set"); - - new FakeAction(null); + assertThatThrownBy(() -> new FakeAction(null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Action key must be set"); } private static class FakeAction extends Action { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/AddTagsActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/AddTagsActionTest.java index 5e16e1370f1..8b9b4b214b5 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/AddTagsActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/AddTagsActionTest.java @@ -22,20 +22,17 @@ package org.sonar.server.issue; import com.google.common.collect.ImmutableSet; import java.util.HashMap; import java.util.Map; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.Mockito; import org.sonar.core.issue.DefaultIssue; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class AddTagsActionTest { - @Rule - public ExpectedException throwable = ExpectedException.none(); private IssueFieldsSetter issueUpdater = new IssueFieldsSetter(); private AddTagsAction underTest = new AddTagsAction(issueUpdater); @@ -57,18 +54,19 @@ public class AddTagsActionTest { @Test public void should_fail_if_tag_is_not_valid() { - throwable.expect(IllegalArgumentException.class); - throwable.expectMessage("Tag 'th ag' is invalid. Rule tags accept only the characters: a-z, 0-9, '+', '-', '#', '.'"); + assertThatThrownBy(() -> { + Map properties = new HashMap<>(); + properties.put("tags", "th ag"); - Map properties = new HashMap<>(); - properties.put("tags", "th ag"); - - DefaultIssue issue = mock(DefaultIssue.class); - when(issue.tags()).thenReturn(ImmutableSet.of("tag1", "tag3")); + DefaultIssue issue = mock(DefaultIssue.class); + when(issue.tags()).thenReturn(ImmutableSet.of("tag1", "tag3")); - Action.Context context = mock(Action.Context.class); - when(context.issue()).thenReturn(issue); + Action.Context context = mock(Action.Context.class); + when(context.issue()).thenReturn(issue); - underTest.execute(properties, context); + underTest.execute(properties, context); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Tag 'th ag' is invalid. Rule tags accept only the characters: a-z, 0-9, '+', '-', '#', '.'"); } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/AssignActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/AssignActionTest.java index 0ba5461b8fb..ee8e2bf5501 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/AssignActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/AssignActionTest.java @@ -27,7 +27,6 @@ import java.util.Map; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.issue.Issue; import org.sonar.core.issue.DefaultIssue; import org.sonar.core.issue.IssueChangeContext; @@ -40,15 +39,13 @@ import org.sonar.server.tester.UserSessionRule; import static java.util.Collections.emptyMap; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.rules.ExpectedException.none; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.server.tester.UserSessionRule.standalone; public class AssignActionTest { private static final String ISSUE_CURRENT_ASSIGNEE_UUID = "current assignee uuid"; - @Rule - public ExpectedException expectedException = none(); @Rule public UserSessionRule userSession = standalone(); @@ -105,28 +102,25 @@ public class AssignActionTest { @Test public void fail_if_assignee_is_not_verified() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Assignee is missing from the execution parameters"); - - underTest.execute(emptyMap(), context); + assertThatThrownBy(() -> underTest.execute(emptyMap(), context)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Assignee is missing from the execution parameters"); } @Test public void fail_if_assignee_does_not_exists() { - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Unknown user: arthur"); - - underTest.verify(ImmutableMap.of("assignee", "arthur"), singletonList(issue), userSession); + assertThatThrownBy(() -> underTest.verify(ImmutableMap.of("assignee", "arthur"), singletonList(issue), userSession)) + .isInstanceOf(NotFoundException.class) + .hasMessage("Unknown user: arthur"); } @Test public void fail_if_assignee_is_disabled() { db.users().insertUser(user -> user.setLogin("arthur").setActive(false)); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Unknown user: arthur"); - - underTest.verify(new HashMap<>(ImmutableMap.of("assignee", "arthur")), singletonList(issue), userSession); + assertThatThrownBy(() -> underTest.verify(new HashMap<>(ImmutableMap.of("assignee", "arthur")), singletonList(issue), userSession)) + .isInstanceOf(NotFoundException.class) + .hasMessage("Unknown user: arthur"); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/AvatarResolverImplTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/AvatarResolverImplTest.java index fd117d94189..8aa42944fd5 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/AvatarResolverImplTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/AvatarResolverImplTest.java @@ -19,17 +19,14 @@ */ package org.sonar.server.issue; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.db.user.UserTesting.newUserDto; public class AvatarResolverImplTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private AvatarResolverImpl underTest = new AvatarResolverImpl(); @@ -47,25 +44,22 @@ public class AvatarResolverImplTest { @Test public void fail_with_NP_when_user_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("User cannot be null"); - - underTest.create(null); + assertThatThrownBy(() -> underTest.create(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("User cannot be null"); } @Test public void fail_with_NP_when_email_is_null() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("Email cannot be null"); - - underTest.create(newUserDto("john", "John", null)); + assertThatThrownBy(() -> underTest.create(newUserDto("john", "John", null))) + .isInstanceOf(NullPointerException.class) + .hasMessage("Email cannot be null"); } @Test public void fail_when_email_is_empty() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("Email cannot be null"); - - underTest.create(newUserDto("john", "John", "")); + assertThatThrownBy(() -> underTest.create(newUserDto("john", "John", ""))) + .isInstanceOf(NullPointerException.class) + .hasMessage("Email cannot be null"); } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/IssueFinderTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/IssueFinderTest.java index 403429273a8..025c2bea8bf 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/IssueFinderTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/IssueFinderTest.java @@ -21,7 +21,6 @@ package org.sonar.server.issue; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.utils.System2; import org.sonar.db.DbTester; import org.sonar.db.component.ComponentDbTester; @@ -35,6 +34,7 @@ import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.tester.UserSessionRule; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.web.UserRole.CODEVIEWER; import static org.sonar.api.web.UserRole.USER; import static org.sonar.db.component.ComponentTesting.newFileDto; @@ -43,8 +43,6 @@ import static org.sonar.db.rule.RuleTesting.newRuleDto; public class IssueFinderTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @@ -74,9 +72,9 @@ public class IssueFinderTest { IssueDto issueDto = insertIssue(); addProjectPermission(issueDto, USER); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Issue with key 'UNKNOWN' does not exist"); - underTest.getByKey(db.getSession(), "UNKNOWN"); + assertThatThrownBy(() -> underTest.getByKey(db.getSession(), "UNKNOWN")) + .isInstanceOf(NotFoundException.class) + .hasMessage("Issue with key 'UNKNOWN' does not exist"); } @Test @@ -84,8 +82,8 @@ public class IssueFinderTest { IssueDto issueDto = insertIssue(); addProjectPermission(issueDto, CODEVIEWER); - expectedException.expect(ForbiddenException.class); - underTest.getByKey(db.getSession(), issueDto.getKey()); + assertThatThrownBy(() -> underTest.getByKey(db.getSession(), issueDto.getKey())) + .isInstanceOf(ForbiddenException.class); } private IssueDto insertIssue() { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/RemoveTagsActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/RemoveTagsActionTest.java index a9fd6e2bf14..748948c830f 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/RemoveTagsActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/RemoveTagsActionTest.java @@ -22,20 +22,17 @@ package org.sonar.server.issue; import com.google.common.collect.ImmutableSet; import java.util.HashMap; import java.util.Map; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.Mockito; import org.sonar.core.issue.DefaultIssue; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class RemoveTagsActionTest { - @Rule - public ExpectedException throwable = ExpectedException.none(); private IssueFieldsSetter issueUpdater = new IssueFieldsSetter(); private RemoveTagsAction action = new RemoveTagsAction(issueUpdater); @@ -57,18 +54,19 @@ public class RemoveTagsActionTest { @Test public void should_fail_if_tag_is_not_valid() { - throwable.expect(IllegalArgumentException.class); - throwable.expectMessage("Tag 'th ag' is invalid. Rule tags accept only the characters: a-z, 0-9, '+', '-', '#', '.'"); + assertThatThrownBy(() -> { + Map properties = new HashMap<>(); + properties.put("tags", "th ag"); - Map properties = new HashMap<>(); - properties.put("tags", "th ag"); - - DefaultIssue issue = mock(DefaultIssue.class); - when(issue.tags()).thenReturn(ImmutableSet.of("tag1", "tag3")); + DefaultIssue issue = mock(DefaultIssue.class); + when(issue.tags()).thenReturn(ImmutableSet.of("tag1", "tag3")); - Action.Context context = mock(Action.Context.class); - when(context.issue()).thenReturn(issue); + Action.Context context = mock(Action.Context.class); + when(context.issue()).thenReturn(issue); - action.execute(properties, context); + action.execute(properties, context); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Tag 'th ag' is invalid. Rule tags accept only the characters: a-z, 0-9, '+', '-', '#', '.'"); } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/SetSeverityActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/SetSeverityActionTest.java index 5317fc4bfb2..b3988c2f84c 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/SetSeverityActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/SetSeverityActionTest.java @@ -25,7 +25,6 @@ import java.util.Date; import java.util.Map; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.issue.Issue; import org.sonar.api.rules.RuleType; import org.sonar.core.issue.DefaultIssue; @@ -39,6 +38,7 @@ import org.sonar.server.tester.AnonymousMockUserSession; import org.sonar.server.tester.UserSessionRule; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.rule.Severity.MAJOR; import static org.sonar.api.rule.Severity.MINOR; import static org.sonar.api.web.UserRole.ISSUE_ADMIN; @@ -52,8 +52,6 @@ public class SetSeverityActionTest { private static final Date NOW = new Date(10_000_000_000L); private static final String USER_LOGIN = "john"; - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @@ -86,10 +84,9 @@ public class SetSeverityActionTest { @Test public void fail_if_parameter_not_found() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Missing parameter : 'severity'"); - - action.verify(ImmutableMap.of("unknwown", MINOR), Lists.newArrayList(), new AnonymousMockUserSession()); + assertThatThrownBy(() -> action.verify(ImmutableMap.of("unknwown", MINOR), Lists.newArrayList(), new AnonymousMockUserSession())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Missing parameter : 'severity'"); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/SetTypeActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/SetTypeActionTest.java index 15de85fe891..3d219f387a8 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/SetTypeActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/SetTypeActionTest.java @@ -25,7 +25,6 @@ import java.util.Date; import java.util.Map; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.issue.Issue; import org.sonar.core.issue.DefaultIssue; import org.sonar.core.issue.FieldDiffs; @@ -37,6 +36,7 @@ import org.sonar.db.rule.RuleDto; import org.sonar.server.tester.UserSessionRule; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.rules.RuleType.BUG; import static org.sonar.api.rules.RuleType.VULNERABILITY; import static org.sonar.api.web.UserRole.ISSUE_ADMIN; @@ -50,8 +50,6 @@ public class SetTypeActionTest { private static final Date NOW = new Date(10_000_000_000L); private static final String USER_LOGIN = "john"; - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @@ -83,18 +81,16 @@ public class SetTypeActionTest { @Test public void verify_fail_if_parameter_not_found() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Missing parameter : 'type'"); - - action.verify(ImmutableMap.of("unknwown", VULNERABILITY.name()), Lists.newArrayList(), userSession); + assertThatThrownBy(() -> action.verify(ImmutableMap.of("unknwown", VULNERABILITY.name()), Lists.newArrayList(), userSession)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Missing parameter : 'type'"); } @Test public void verify_fail_if_type_is_invalid() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Unknown type : unknown"); - - action.verify(ImmutableMap.of("type", "unknown"), Lists.newArrayList(), userSession); + assertThatThrownBy(() -> action.verify(ImmutableMap.of("type", "unknown"), Lists.newArrayList(), userSession)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Unknown type : unknown"); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/TransitionActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/TransitionActionTest.java index ab378589b7a..2538d53ae98 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/TransitionActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/TransitionActionTest.java @@ -25,7 +25,6 @@ import java.util.Date; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.issue.Issue; import org.sonar.api.rules.RuleType; import org.sonar.core.issue.DefaultIssue; @@ -42,6 +41,7 @@ import org.sonar.server.tester.UserSessionRule; import static java.util.Collections.emptyList; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.api.issue.Issue.STATUS_CLOSED; @@ -51,8 +51,6 @@ import static org.sonar.db.rule.RuleTesting.newRule; public class TransitionActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @@ -105,9 +103,9 @@ public class TransitionActionTest { @Test public void fail_to_verify_when_parameter_not_found() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Missing parameter : 'transition'"); - action.verify(ImmutableMap.of("unknown", "reopen"), Lists.newArrayList(), userSession); + assertThatThrownBy(() -> action.verify(ImmutableMap.of("unknown", "reopen"), Lists.newArrayList(), userSession)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Missing parameter : 'transition'"); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/TransitionServiceTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/TransitionServiceTest.java index aa8a8d44118..ac35cc3c59e 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/TransitionServiceTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/TransitionServiceTest.java @@ -24,7 +24,6 @@ import java.util.List; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.core.issue.DefaultIssue; import org.sonar.core.issue.IssueChangeContext; import org.sonar.db.DbTester; @@ -37,6 +36,7 @@ import org.sonar.server.issue.workflow.Transition; import org.sonar.server.tester.UserSessionRule; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.issue.Issue.STATUS_CONFIRMED; import static org.sonar.api.issue.Issue.STATUS_OPEN; import static org.sonar.api.rules.RuleType.CODE_SMELL; @@ -49,8 +49,6 @@ public class TransitionServiceTest { public DbTester db = DbTester.create(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private IssueFieldsSetter updater = new IssueFieldsSetter(); private IssueWorkflow workflow = new IssueWorkflow(new FunctionExecutor(updater), updater); @@ -135,9 +133,8 @@ public class TransitionServiceTest { IssueDto externalIssue = db.issues().insert(externalRule, project, file, i -> i.setStatus(STATUS_OPEN).setResolution(null).setType(CODE_SMELL)); DefaultIssue defaultIssue = externalIssue.toDefaultIssue(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Transition is not allowed on issues imported from external rule engines"); - - underTest.doTransition(defaultIssue, IssueChangeContext.createUser(new Date(), "user_uuid"), "confirm"); + assertThatThrownBy(() -> underTest.doTransition(defaultIssue, IssueChangeContext.createUser(new Date(), "user_uuid"), "confirm")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Transition is not allowed on issues imported from external rule engines"); } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/AddCommentActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/AddCommentActionTest.java index df2d4846b60..afb1dc6f4b8 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/AddCommentActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/AddCommentActionTest.java @@ -23,7 +23,6 @@ import javax.annotation.Nullable; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; @@ -73,8 +72,6 @@ public class AddCommentActionTest { private static final long NOW = 10_000_000_000L; - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); @@ -148,24 +145,24 @@ public class AddCommentActionTest { public void fail_when_missing_issue_key() { userSession.logIn("john"); - expectedException.expect(IllegalArgumentException.class); - call(null, "please fix it"); + assertThatThrownBy(() -> call(null, "please fix it")) + .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_when_issue_does_not_exist() { userSession.logIn("john"); - expectedException.expect(NotFoundException.class); - call("ABCD", "please fix it"); + assertThatThrownBy(() -> call("ABCD", "please fix it")) + .isInstanceOf(NotFoundException.class); } @Test public void fail_when_missing_comment_text() { userSession.logIn("john"); - expectedException.expect(IllegalArgumentException.class); - call("ABCD", null); + assertThatThrownBy(() -> call("ABCD", null)) + .isInstanceOf(IllegalArgumentException.class); } @Test @@ -173,14 +170,14 @@ public class AddCommentActionTest { IssueDto issueDto = issueDbTester.insertIssue(); loginWithBrowsePermission(issueDto, USER); - expectedException.expect(IllegalArgumentException.class); - call(issueDto.getKey(), ""); + assertThatThrownBy(() -> call(issueDto.getKey(), "")) + .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_when_not_authenticated() { - expectedException.expect(UnauthorizedException.class); - call("ABCD", "please fix it"); + assertThatThrownBy(() -> call("ABCD", "please fix it")) + .isInstanceOf(UnauthorizedException.class); } @Test @@ -188,8 +185,8 @@ public class AddCommentActionTest { IssueDto issueDto = issueDbTester.insertIssue(); loginWithBrowsePermission(issueDto, CODEVIEWER); - expectedException.expect(ForbiddenException.class); - call(issueDto.getKey(), "please fix it"); + assertThatThrownBy(() -> call(issueDto.getKey(), "please fix it")) + .isInstanceOf(ForbiddenException.class); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/AssignActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/AssignActionTest.java index 6721fd34c11..bd45ea6ea3d 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/AssignActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/AssignActionTest.java @@ -23,7 +23,6 @@ import java.util.Optional; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.impl.utils.TestSystem2; import org.sonar.api.rules.RuleType; import org.sonar.core.util.SequenceUuidFactory; @@ -52,7 +51,6 @@ import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.rules.ExpectedException.none; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -71,8 +69,6 @@ public class AssignActionTest { private TestSystem2 system2 = new TestSystem2().setNow(NOW); - @Rule - public ExpectedException expectedException = none(); @Rule public UserSessionRule userSession = standalone(); @Rule @@ -194,12 +190,13 @@ public class AssignActionTest { public void fail_when_assignee_does_not_exist() { IssueDto issue = newIssueWithBrowsePermission(); - expectedException.expect(NotFoundException.class); - - ws.newRequest() - .setParam("issue", issue.getKey()) - .setParam("assignee", "unknown") - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam("issue", issue.getKey()) + .setParam("assignee", "unknown") + .execute(); + }) + .isInstanceOf(NotFoundException.class); } @Test @@ -226,12 +223,13 @@ public class AssignActionTest { IssueDto issue = newIssueWithBrowsePermission(); db.users().insertUser(user -> user.setActive(false)); - expectedException.expect(NotFoundException.class); - - ws.newRequest() - .setParam("issue", issue.getKey()) - .setParam("assignee", "unknown") - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam("issue", issue.getKey()) + .setParam("assignee", "unknown") + .execute(); + }) + .isInstanceOf(NotFoundException.class); } @Test @@ -239,12 +237,13 @@ public class AssignActionTest { IssueDto issue = newIssue(PREVIOUS_ASSIGNEE); userSession.anonymous(); - expectedException.expect(UnauthorizedException.class); - - ws.newRequest() - .setParam("issue", issue.getKey()) - .setParam("assignee", "_me") - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam("issue", issue.getKey()) + .setParam("assignee", "_me") + .execute(); + }) + .isInstanceOf(UnauthorizedException.class); } @Test @@ -252,12 +251,13 @@ public class AssignActionTest { IssueDto issue = newIssue(PREVIOUS_ASSIGNEE); setUserWithPermission(issue, CODEVIEWER); - expectedException.expect(ForbiddenException.class); - - ws.newRequest() - .setParam("issue", issue.getKey()) - .setParam("assignee", "_me") - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam("issue", issue.getKey()) + .setParam("assignee", "_me") + .execute(); + }) + .isInstanceOf(ForbiddenException.class); } private UserDto insertUser(String login) { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/AuthorsActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/AuthorsActionTest.java index 07f43c717c5..fecb04c841d 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/AuthorsActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/AuthorsActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.issue.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.api.server.ws.WebService.Param; import org.sonar.api.utils.System2; @@ -47,6 +46,7 @@ import org.sonarqube.ws.Issues.AuthorsResponse; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.groups.Tuple.tuple; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; @@ -67,8 +67,6 @@ public class AuthorsActionTest { public EsTester es = EsTester.create(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private final IssueIndex issueIndex = new IssueIndex(es.client(), System2.INSTANCE, userSession, new WebAuthorizationTypeSupport(userSession)); private final AsyncIssueIndexing asyncIssueIndexing = mock(AsyncIssueIndexing.class); @@ -234,9 +232,8 @@ public class AuthorsActionTest { public void fail_when_user_is_not_logged() { userSession.anonymous(); - expectedException.expect(UnauthorizedException.class); - - ws.newRequest().execute(); + assertThatThrownBy(() -> ws.newRequest().execute()) + .isInstanceOf(UnauthorizedException.class); } @Test @@ -246,24 +243,26 @@ public class AuthorsActionTest { ComponentDto file = db.components().insertComponent(newFileDto(project)); permissionIndexer.allowOnlyAnyone(project); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(format("Component '%s' must be a project", file.getKey())); - - ws.newRequest() - .setParam("project", file.getKey()) - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam("project", file.getKey()) + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage(format("Component '%s' must be a project", file.getKey())); } @Test public void fail_when_project_does_not_exist() { userSession.logIn(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Component key 'unknown' not found"); - - ws.newRequest() - .setParam("project", "unknown") - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam("project", "unknown") + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("Component key 'unknown' not found"); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/BulkChangeActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/BulkChangeActionTest.java index 6912f1d1d56..429b17b9d54 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/BulkChangeActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/BulkChangeActionTest.java @@ -28,7 +28,6 @@ import javax.annotation.Nullable; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; import org.sonar.api.impl.utils.TestSystem2; import org.sonar.api.rules.RuleType; @@ -73,6 +72,7 @@ import static java.util.Collections.singletonList; import static java.util.Objects.requireNonNull; import static java.util.Optional.ofNullable; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -103,8 +103,6 @@ public class BulkChangeActionTest { private System2 system2 = new TestSystem2().setNow(NOW); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester db = DbTester.create(system2); @Rule @@ -669,33 +667,36 @@ public class BulkChangeActionTest { IssueDto issue = db.issues().insertIssue(rule, project, project, i -> i.setType(BUG) .setStatus(STATUS_OPEN).setResolution(null)); - expectedException.expectMessage("At least one action must be provided"); - expectedException.expect(IllegalArgumentException.class); - - call(builder() - .setIssues(singletonList(issue.getKey())) - .setComment("type was badly defined") - .build()); + assertThatThrownBy(() -> { + call(builder() + .setIssues(singletonList(issue.getKey())) + .setComment("type was badly defined") + .build()); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("At least one action must be provided"); } @Test public void fail_when_number_of_issues_is_more_than_500() { userSession.logIn("john"); - expectedException.expectMessage("Number of issues is limited to 500"); - expectedException.expect(IllegalArgumentException.class); - - call(builder() - .setIssues(IntStream.range(0, 510).mapToObj(String::valueOf).collect(Collectors.toList())) - .setSetSeverity(MINOR) - .build()); + assertThatThrownBy(() -> { + call(builder() + .setIssues(IntStream.range(0, 510).mapToObj(String::valueOf).collect(Collectors.toList())) + .setSetSeverity(MINOR) + .build()); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Number of issues is limited to 500"); } @Test public void fail_when_not_authenticated() { - expectedException.expect(UnauthorizedException.class); - - call(builder().setIssues(singletonList("ABCD")).build()); + assertThatThrownBy(() -> { + call(builder().setIssues(singletonList("ABCD")).build()); + }) + .isInstanceOf(UnauthorizedException.class); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/ChangelogActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/ChangelogActionTest.java index 4f0bdc2bbf3..9e8e845f95c 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/ChangelogActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/ChangelogActionTest.java @@ -24,7 +24,6 @@ import javax.annotation.Nullable; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.DateUtils; import org.sonar.api.utils.System2; @@ -61,8 +60,6 @@ import static org.sonar.test.JsonAssert.assertJson; public class ChangelogActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester db = DbTester.create(System2.INSTANCE); @@ -291,8 +288,8 @@ public class ChangelogActionTest { IssueDto issueDto = insertNewIssue(); userSession.logIn("john").addProjectPermission(CODEVIEWER, project, file); - expectedException.expect(ForbiddenException.class); - call(issueDto.getKey()); + assertThatThrownBy(() -> call(issueDto.getKey())) + .isInstanceOf(ForbiddenException.class); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/DeleteCommentActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/DeleteCommentActionTest.java index 8baef6a14a7..3b0412bca21 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/DeleteCommentActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/DeleteCommentActionTest.java @@ -22,7 +22,6 @@ package org.sonar.server.issue.ws; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; @@ -54,8 +53,6 @@ import static org.sonar.api.web.UserRole.USER; public class DeleteCommentActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester dbTester = DbTester.create(); @Rule @@ -91,9 +88,9 @@ public class DeleteCommentActionTest { UserDto another = dbTester.users().insertUser(); loginAndAddProjectPermission(another, issueDto, USER); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("You can only delete your own comments"); - call(commentDto.getKey()); + assertThatThrownBy(() -> call(commentDto.getKey())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("You can only delete your own comments"); } @Test @@ -103,31 +100,31 @@ public class DeleteCommentActionTest { IssueChangeDto commentDto = issueDbTester.insertComment(issueDto, null, "please fix it"); loginAndAddProjectPermission(user, issueDto, USER); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("You can only delete your own comments"); - call(commentDto.getKey()); + assertThatThrownBy(() -> call(commentDto.getKey())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("You can only delete your own comments"); } @Test public void fail_when_missing_comment_key() { userSession.logIn("john"); - expectedException.expect(IllegalArgumentException.class); - call(null); + assertThatThrownBy(() -> call(null)) + .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_when_comment_does_not_exist() { userSession.logIn("john"); - expectedException.expect(NotFoundException.class); - call("ABCD"); + assertThatThrownBy(() -> call("ABCD")) + .isInstanceOf(NotFoundException.class); } @Test public void fail_when_not_authenticated() { - expectedException.expect(UnauthorizedException.class); - call("ABCD"); + assertThatThrownBy(() -> call("ABCD")) + .isInstanceOf(UnauthorizedException.class); } @Test @@ -137,8 +134,9 @@ public class DeleteCommentActionTest { IssueChangeDto commentDto = issueDbTester.insertComment(issueDto, user, "please fix it"); loginAndAddProjectPermission(user, issueDto, CODEVIEWER); - expectedException.expect(ForbiddenException.class); - call(commentDto.getKey()); + assertThatThrownBy(() -> call(commentDto.getKey())) + .isInstanceOf(ForbiddenException.class) + .hasMessage("Insufficient privileges"); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/DoTransitionActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/DoTransitionActionTest.java index 6073d09c704..9a23bdeeafd 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/DoTransitionActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/DoTransitionActionTest.java @@ -23,7 +23,6 @@ import javax.annotation.Nullable; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; import org.sonar.api.impl.utils.TestSystem2; import org.sonar.api.rules.RuleType; @@ -77,8 +76,6 @@ public class DoTransitionActionTest { private System2 system2 = new TestSystem2().setNow(NOW); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester db = DbTester.create(system2); @@ -136,10 +133,9 @@ public class DoTransitionActionTest { IssueDto externalIssue = db.issues().insertIssue(externalRule, project, file, i -> i.setStatus(STATUS_OPEN).setResolution(null).setType(CODE_SMELL)); userSession.logIn().addProjectPermission(USER, project, file); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Transition is not allowed on issues imported from external rule engines"); - - call(externalIssue.getKey(), "confirm"); + assertThatThrownBy(() -> call(externalIssue.getKey(), "confirm")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Transition is not allowed on issues imported from external rule engines"); } @Test @@ -160,16 +156,16 @@ public class DoTransitionActionTest { public void fail_if_issue_does_not_exist() { userSession.logIn(); - expectedException.expect(NotFoundException.class); - call("UNKNOWN", "confirm"); + assertThatThrownBy(() -> call("UNKNOWN", "confirm")) + .isInstanceOf(NotFoundException.class); } @Test public void fail_if_no_issue_param() { userSession.logIn(); - expectedException.expect(IllegalArgumentException.class); - call(null, "confirm"); + assertThatThrownBy(() -> call(null, "confirm")) + .isInstanceOf(IllegalArgumentException.class); } @Test @@ -180,8 +176,8 @@ public class DoTransitionActionTest { IssueDto issue = db.issues().insertIssue(rule, project, file, i -> i.setStatus(STATUS_OPEN).setResolution(null).setType(CODE_SMELL)); userSession.logIn().addProjectPermission(USER, project, file); - expectedException.expect(IllegalArgumentException.class); - call(issue.getKey(), null); + assertThatThrownBy(() -> call(issue.getKey(), null)) + .isInstanceOf(IllegalArgumentException.class); } @Test @@ -192,9 +188,8 @@ public class DoTransitionActionTest { IssueDto issue = db.issues().insertIssue(rule, project, file, i -> i.setStatus(STATUS_OPEN).setResolution(null).setType(CODE_SMELL)); userSession.logIn().addProjectPermission(CODEVIEWER, project, file); - expectedException.expect(ForbiddenException.class); - - call(issue.getKey(), "confirm"); + assertThatThrownBy(() -> call(issue.getKey(), "confirm")) + .isInstanceOf(ForbiddenException.class); } @Test @@ -206,16 +201,14 @@ public class DoTransitionActionTest { userSession.logIn().addProjectPermission(USER, project, file); // False-positive transition is requiring issue admin permission - expectedException.expect(ForbiddenException.class); - - call(issue.getKey(), "falsepositive"); + assertThatThrownBy(() -> call(issue.getKey(), "falsepositive")) + .isInstanceOf(ForbiddenException.class); } @Test public void fail_if_not_authenticated() { - expectedException.expect(UnauthorizedException.class); - - call("ISSUE_KEY", "confirm"); + assertThatThrownBy(() -> call("ISSUE_KEY", "confirm")) + .isInstanceOf(UnauthorizedException.class); } private TestResponse call(@Nullable String issueKey, @Nullable String transition) { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/EditCommentActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/EditCommentActionTest.java index c02aecef67e..66d63598ea3 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/EditCommentActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/EditCommentActionTest.java @@ -23,7 +23,6 @@ import javax.annotation.Nullable; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; @@ -59,8 +58,6 @@ public class EditCommentActionTest { private static final long NOW = 10_000_000_000L; - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester dbTester = DbTester.create(); @Rule @@ -119,9 +116,9 @@ public class EditCommentActionTest { UserDto another = dbTester.users().insertUser(); loginWithBrowsePermission(another, USER, issueDto); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("You can only edit your own comments"); - call(commentDto.getKey(), "please have a look"); + assertThatThrownBy(() -> call(commentDto.getKey(), "please have a look")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("You can only edit your own comments"); } @Test @@ -131,33 +128,33 @@ public class EditCommentActionTest { IssueChangeDto commentDto = issueDbTester.insertComment(issueDto, null, "please fix it"); loginWithBrowsePermission(user, USER, issueDto); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("You can only edit your own comments"); - call(commentDto.getKey(), "please have a look"); + assertThatThrownBy(() -> call(commentDto.getKey(), "please have a look")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("You can only edit your own comments"); } @Test public void fail_when_missing_comment_key() { userSession.logIn("john"); - expectedException.expect(IllegalArgumentException.class); - call(null, "please fix it"); + assertThatThrownBy(() -> call(null, "please fix it")) + .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_when_comment_does_not_exist() { userSession.logIn("john"); - expectedException.expect(NotFoundException.class); - call("ABCD", "please fix it"); + assertThatThrownBy(() -> call("ABCD", "please fix it")) + .isInstanceOf(NotFoundException.class); } @Test public void fail_when_missing_comment_text() { userSession.logIn("john"); - expectedException.expect(IllegalArgumentException.class); - call("ABCD", null); + assertThatThrownBy(() -> call("ABCD", null)) + .isInstanceOf(IllegalArgumentException.class); } @Test @@ -167,14 +164,14 @@ public class EditCommentActionTest { IssueChangeDto commentDto = issueDbTester.insertComment(issueDto, user, "please fix it"); loginWithBrowsePermission(user, USER, issueDto); - expectedException.expect(IllegalArgumentException.class); - call(commentDto.getKey(), ""); + assertThatThrownBy(() -> call(commentDto.getKey(), "")) + .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_when_not_authenticated() { - expectedException.expect(UnauthorizedException.class); - call("ABCD", "please fix it"); + assertThatThrownBy(() -> call("ABCD", "please fix it")) + .isInstanceOf(UnauthorizedException.class); } @Test @@ -184,8 +181,8 @@ public class EditCommentActionTest { IssueChangeDto commentDto = issueDbTester.insertComment(issueDto, user, "please fix it"); loginWithBrowsePermission(user, CODEVIEWER, issueDto); - expectedException.expect(ForbiddenException.class); - call(commentDto.getKey(), "please have a look"); + assertThatThrownBy(() -> call(commentDto.getKey(), "please have a look")) + .isInstanceOf(ForbiddenException.class); } @Test @@ -195,9 +192,9 @@ public class EditCommentActionTest { IssueChangeDto commentDto = issueDbTester.insertComment(issueDto, user, "please fix it"); loginWithBrowsePermission(user, CODEVIEWER, issueDto); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(String.format("Issue with key '%s' does not exist", issueDto.getKey())); - call(commentDto.getKey(), "please have a look"); + assertThatThrownBy(() -> call(commentDto.getKey(), "please have a look")) + .isInstanceOf(NotFoundException.class) + .hasMessage(String.format("Issue with key '%s' does not exist", issueDto.getKey())); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/IssueUpdaterTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/IssueUpdaterTest.java index 5abf71dc441..a6f94336ad7 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/IssueUpdaterTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/IssueUpdaterTest.java @@ -22,7 +22,6 @@ package org.sonar.server.issue.ws; import java.util.Date; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; import org.sonar.api.rule.RuleStatus; import org.sonar.api.utils.System2; @@ -68,8 +67,6 @@ public class IssueUpdaterTest { private System2 system2 = mock(System2.class); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester db = DbTester.create(system2); diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/SearchActionComponentsTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/SearchActionComponentsTest.java index cf5c562c910..c0a0c6df7b1 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/SearchActionComponentsTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/SearchActionComponentsTest.java @@ -24,7 +24,6 @@ import java.util.Arrays; import java.util.Date; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.resources.Languages; import org.sonar.api.resources.Qualifiers; import org.sonar.api.rule.RuleKey; @@ -82,8 +81,6 @@ import static org.sonarqube.ws.client.issue.IssuesWsParameters.PARAM_SINCE_LEAK_ public class SearchActionComponentsTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/SearchActionFacetsTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/SearchActionFacetsTest.java index 066e292c835..55d56d88b31 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/SearchActionFacetsTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/SearchActionFacetsTest.java @@ -26,7 +26,6 @@ import java.util.Random; import java.util.stream.IntStream; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.issue.Issue; import org.sonar.api.resources.Languages; import org.sonar.api.rules.RuleType; @@ -57,6 +56,7 @@ import org.sonarqube.ws.Issues.SearchWsResponse; import static com.google.common.collect.ImmutableMap.of; import static java.util.stream.Collectors.toMap; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.groups.Tuple.tuple; import static org.sonar.api.server.ws.WebService.Param.FACETS; import static org.sonar.db.component.ComponentTesting.newDirectory; @@ -78,8 +78,6 @@ public class SearchActionFacetsTest { public DbTester db = DbTester.create(); @Rule public EsTester es = EsTester.create(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private IssueIndex issueIndex = new IssueIndex(es.client(), System2.INSTANCE, userSession, new WebAuthorizationTypeSupport(userSession)); private IssueIndexer issueIndexer = new IssueIndexer(es.client(), db.getDbClient(), new IssueIteratorFactory(db.getDbClient()), null); @@ -207,12 +205,13 @@ public class SearchActionFacetsTest { indexPermissions(); indexIssues(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Facet(s) 'directories' require to also filter by project"); - - ws.newRequest() - .setParam(WebService.Param.FACETS, "directories") - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam(WebService.Param.FACETS, "directories") + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Facet(s) 'directories' require to also filter by project"); } @Test @@ -247,13 +246,14 @@ public class SearchActionFacetsTest { indexPermissions(); indexIssues(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Facet(s) 'files' require to also filter by project"); - - ws.newRequest() - .setParam(PARAM_FILES, file.path()) - .setParam(WebService.Param.FACETS, "files") - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam(PARAM_FILES, file.path()) + .setParam(WebService.Param.FACETS, "files") + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Facet(s) 'files' require to also filter by project"); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/SearchActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/SearchActionTest.java index 60fecb8c48f..95a711c8b56 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/SearchActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/SearchActionTest.java @@ -34,7 +34,6 @@ import java.util.stream.Stream; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.resources.Languages; import org.sonar.api.rule.RuleStatus; import org.sonar.api.rules.RuleType; @@ -89,7 +88,6 @@ import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.groups.Tuple.tuple; -import static org.junit.rules.ExpectedException.none; import static org.sonar.api.issue.Issue.RESOLUTION_FIXED; import static org.sonar.api.issue.Issue.STATUS_RESOLVED; import static org.sonar.api.resources.Qualifiers.UNIT_TEST_FILE; @@ -124,8 +122,6 @@ public class SearchActionTest { public DbTester db = DbTester.create(); @Rule public EsTester es = EsTester.create(); - @Rule - public ExpectedException expectedException = none(); private final DbClient dbClient = db.getDbClient(); private final DbSession session = db.getSession(); @@ -1261,12 +1257,14 @@ public class SearchActionTest { @Test public void paging_with_page_size_to_minus_one() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Page size must be between 1 and 500 (got -1)"); - ws.newRequest() - .setParam(WebService.Param.PAGE, "1") - .setParam(WebService.Param.PAGE_SIZE, "-1") - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam(WebService.Param.PAGE, "1") + .setParam(WebService.Param.PAGE_SIZE, "-1") + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Page size must be between 1 and 500 (got -1)"); } @Test @@ -1301,12 +1299,13 @@ public class SearchActionTest { @Test public void fail_when_invalid_format() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Date 'wrong-date-input' cannot be parsed as either a date or date+time"); - - ws.newRequest() - .setParam(PARAM_CREATED_AFTER, "wrong-date-input") - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam(PARAM_CREATED_AFTER, "wrong-date-input") + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Date 'wrong-date-input' cannot be parsed as either a date or date+time"); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/SetSeverityActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/SetSeverityActionTest.java index c063a786f7d..7a5ace056b8 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/SetSeverityActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/SetSeverityActionTest.java @@ -23,7 +23,6 @@ import java.util.List; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; @@ -70,8 +69,6 @@ import static org.sonar.api.web.UserRole.USER; public class SetSeverityActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester dbTester = DbTester.create(); @Rule @@ -132,9 +129,9 @@ public class SetSeverityActionTest { IssueDto issueDto = issueDbTester.insertIssue(i -> i.setSeverity("unknown")); setUserWithBrowseAndAdministerIssuePermission(issueDto); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Value of parameter 'severity' (unknown) must be one of: [INFO, MINOR, MAJOR, CRITICAL, BLOCKER]"); - call(issueDto.getKey(), "unknown"); + assertThatThrownBy(() -> call(issueDto.getKey(), "unknown")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Value of parameter 'severity' (unknown) must be one of: [INFO, MINOR, MAJOR, CRITICAL, BLOCKER]"); } @Test @@ -150,8 +147,8 @@ public class SetSeverityActionTest { @Test public void fail_when_not_authenticated() { - expectedException.expect(UnauthorizedException.class); - call("ABCD", MAJOR); + assertThatThrownBy(() -> call("ABCD", MAJOR)) + .isInstanceOf(UnauthorizedException.class); } @Test @@ -159,8 +156,8 @@ public class SetSeverityActionTest { IssueDto issueDto = issueDbTester.insertIssue(); logInAndAddProjectPermission(issueDto, ISSUE_ADMIN); - expectedException.expect(ForbiddenException.class); - call(issueDto.getKey(), MAJOR); + assertThatThrownBy(() -> call(issueDto.getKey(), MAJOR)) + .isInstanceOf(ForbiddenException.class); } @Test @@ -168,8 +165,8 @@ public class SetSeverityActionTest { IssueDto issueDto = issueDbTester.insertIssue(); logInAndAddProjectPermission(issueDto, USER); - expectedException.expect(ForbiddenException.class); - call(issueDto.getKey(), MAJOR); + assertThatThrownBy(() -> call(issueDto.getKey(), MAJOR)) + .isInstanceOf(ForbiddenException.class); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/SetTagsActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/SetTagsActionTest.java index 8b39af0b940..d616b8747df 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/SetTagsActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/SetTagsActionTest.java @@ -26,7 +26,6 @@ import java.util.function.Consumer; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; @@ -62,6 +61,7 @@ import org.sonar.server.ws.WsActionTester; import static java.util.Collections.singletonList; import static java.util.Optional.ofNullable; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; @@ -73,8 +73,6 @@ import static org.sonar.db.component.ComponentTesting.newPublicProjectDto; public class SetTagsActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester db = DbTester.create(); @Rule @@ -174,17 +172,15 @@ public class SetTagsActionTest { IssueDto issueDto = insertIssueForPublicProject(i -> i.setTags(singletonList("old-tag"))); logIn(issueDto); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Tags 'pol op' are invalid. Rule tags accept only the characters: a-z, 0-9, '+', '-', '#', '.'"); - - call(issueDto.getKey(), "pol op"); + assertThatThrownBy(() -> call(issueDto.getKey(), "pol op")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Tags 'pol op' are invalid. Rule tags accept only the characters: a-z, 0-9, '+', '-', '#', '.'"); } @Test public void fail_when_not_authenticated() { - expectedException.expect(UnauthorizedException.class); - - call("ABCD", "bug"); + assertThatThrownBy(() -> call("ABCD", "bug")) + .isInstanceOf(UnauthorizedException.class); } @Test @@ -192,9 +188,8 @@ public class SetTagsActionTest { IssueDto issueDto = db.issues().insertIssue(); logInAndAddProjectPermission(issueDto, ISSUE_ADMIN); - expectedException.expect(ForbiddenException.class); - - call(issueDto.getKey(), "bug"); + assertThatThrownBy(() -> call(issueDto.getKey(), "bug")) + .isInstanceOf(ForbiddenException.class); } @Test @@ -205,9 +200,8 @@ public class SetTagsActionTest { IssueDto issueDto = db.issues().insertHotspot(rule, project, file); logIn(issueDto); - expectedException.expect(NotFoundException.class); - - call(issueDto.getKey(), "bug"); + assertThatThrownBy(() -> call(issueDto.getKey(), "bug")) + .isInstanceOf(NotFoundException.class); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/SetTypeActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/SetTypeActionTest.java index dd40d5c5def..0538bae13a2 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/SetTypeActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/SetTypeActionTest.java @@ -30,7 +30,6 @@ import java.util.stream.Collectors; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.sonar.api.rules.RuleType; @@ -82,8 +81,6 @@ import static org.sonar.db.component.ComponentTesting.newFileDto; @RunWith(DataProviderRunner.class) public class SetTypeActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester dbTester = DbTester.create(); @Rule @@ -170,8 +167,8 @@ public class SetTypeActionTest { @Test public void fail_when_not_authenticated() { - expectedException.expect(UnauthorizedException.class); - call("ABCD", BUG.name()); + assertThatThrownBy(() -> call("ABCD", BUG.name())) + .isInstanceOf(UnauthorizedException.class); } @Test @@ -181,8 +178,9 @@ public class SetTypeActionTest { String permission = ISSUE_ADMIN; logInAndAddProjectPermission(login, issueDto, permission); - expectedException.expect(ForbiddenException.class); - call(issueDto.getKey(), BUG.name()); + assertThatThrownBy(() -> call(issueDto.getKey(), BUG.name())) + .isInstanceOf(ForbiddenException.class) + .hasMessage("Insufficient privileges"); } @Test @@ -191,8 +189,8 @@ public class SetTypeActionTest { IssueDto issueDto = issueDbTester.insertIssue(issue -> issue.setType(type)); logInAndAddProjectPermission("john", issueDto, USER); - expectedException.expect(ForbiddenException.class); - call(issueDto.getKey(), type.name()); + assertThatThrownBy(() -> call(issueDto.getKey(), type.name())) + .isInstanceOf(ForbiddenException.class); } @Test @@ -263,7 +261,7 @@ public class SetTypeActionTest { return EnumSet.allOf(RuleType.class) .stream() .filter(ruleType -> SECURITY_HOTSPOT != ruleType) - .map(t -> new Object[] {t}) + .map(t -> new Object[]{t}) .toArray(Object[][]::new); } @@ -275,7 +273,7 @@ public class SetTypeActionTest { .collect(Collectors.toSet()); return Sets.cartesianProduct(set, set) .stream() - .map(ruleTypes -> new Object[] {ruleTypes.get(0), ruleTypes.get(1)}) + .map(ruleTypes -> new Object[]{ruleTypes.get(0), ruleTypes.get(1)}) .toArray(Object[][]::new); } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/TagsActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/TagsActionTest.java index 7d86aa5c8d8..16f3efccf5b 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/TagsActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/TagsActionTest.java @@ -23,7 +23,6 @@ import com.google.protobuf.ProtocolStringList; import java.util.function.Consumer; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService.Action; import org.sonar.api.server.ws.WebService.Param; import org.sonar.api.utils.System2; @@ -50,6 +49,7 @@ import static java.lang.String.format; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; @@ -68,8 +68,6 @@ public class TagsActionTest { public DbTester db = DbTester.create(); @Rule public EsTester es = EsTester.create(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private IssueIndex issueIndex = new IssueIndex(es.client(), System2.INSTANCE, userSession, new WebAuthorizationTypeSupport(userSession)); private IssueIndexSyncProgressChecker issueIndexSyncProgressChecker = mock(IssueIndexSyncProgressChecker.class); @@ -343,12 +341,13 @@ public class TagsActionTest { indexIssues(); permissionIndexer.allowOnlyAnyone(project, project); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(format("Component '%s' must be a project", file.getKey())); - - ws.newRequest() - .setParam("project", file.getKey()) - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam("project", file.getKey()) + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage(format("Component '%s' must be a project", file.getKey())); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/language/LanguageValidationTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/language/LanguageValidationTest.java index 54bf3a9419c..1df6bbf1eee 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/language/LanguageValidationTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/language/LanguageValidationTest.java @@ -19,9 +19,7 @@ */ package org.sonar.server.language; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.resources.Language; import org.sonar.server.plugins.ServerPluginRepository; @@ -30,8 +28,6 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class LanguageValidationTest { - @Rule - public ExpectedException exception = ExpectedException.none(); @Test public void fail_if_conflicting_languages() { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/live/IssueMetricFormulaFactoryImplTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/live/IssueMetricFormulaFactoryImplTest.java index e0d87054c04..0842bd74cf5 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/live/IssueMetricFormulaFactoryImplTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/live/IssueMetricFormulaFactoryImplTest.java @@ -25,9 +25,7 @@ import java.util.HashSet; import java.util.Map; import java.util.Optional; import java.util.Set; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.issue.Issue; import org.sonar.api.measures.CoreMetrics; import org.sonar.api.measures.Metric; @@ -42,8 +40,6 @@ import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; public class IssueMetricFormulaFactoryImplTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private IssueMetricFormulaFactoryImpl underTest = new IssueMetricFormulaFactoryImpl(); diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/live/LiveMeasureComputerImplTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/live/LiveMeasureComputerImplTest.java index 4e027f4b952..9517e8e9e13 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/live/LiveMeasureComputerImplTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/live/LiveMeasureComputerImplTest.java @@ -32,7 +32,6 @@ import javax.annotation.Nullable; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.api.config.Configuration; import org.sonar.api.config.PropertyDefinitions; @@ -64,6 +63,7 @@ import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.singleton; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.eq; @@ -78,8 +78,6 @@ public class LiveMeasureComputerImplTest { @Rule public DbTester db = DbTester.create(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private final TestProjectIndexers projectIndexer = new TestProjectIndexers(); private MetricDto intMetric; @@ -378,12 +376,13 @@ public class LiveMeasureComputerImplTest { markProjectAsAnalyzed(project); Metric metric = new Metric.Builder(intMetric.getKey(), intMetric.getShortName(), Metric.ValueType.valueOf(intMetric.getValueType())).create(); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Fail to compute " + metric.getKey() + " on " + project.getDbKey()); - - run(project, new IssueMetricFormula(metric, false, (context, issueCounter) -> { - throw new NullPointerException("BOOM"); - })); + assertThatThrownBy(() -> { + run(project, new IssueMetricFormula(metric, false, (context, issueCounter) -> { + throw new NullPointerException("BOOM"); + })); + }) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Fail to compute " + metric.getKey() + " on " + project.getDbKey()); } private List run(ComponentDto component, IssueMetricFormula... formulas) { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/live/LiveQualityGateComputerImplTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/live/LiveQualityGateComputerImplTest.java index a755eb31e75..15a7e57cb12 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/live/LiveQualityGateComputerImplTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/live/LiveQualityGateComputerImplTest.java @@ -25,7 +25,6 @@ import java.util.Set; import java.util.stream.Collectors; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.config.Configuration; import org.sonar.api.config.internal.ConfigurationBridge; import org.sonar.api.config.internal.MapSettings; @@ -58,8 +57,6 @@ import static org.sonar.db.metric.MetricTesting.newMetricDto; public class LiveQualityGateComputerImplTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester db = DbTester.create(); diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/live/MeasureMatrixTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/live/MeasureMatrixTest.java index 038f627deac..5685d0ee8a8 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/live/MeasureMatrixTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/live/MeasureMatrixTest.java @@ -23,9 +23,7 @@ import java.util.ArrayList; import java.util.Collection; import java.util.Optional; import javax.annotation.Nullable; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ComponentTesting; import org.sonar.db.measure.LiveMeasureDto; @@ -34,6 +32,7 @@ import org.sonar.db.metric.MetricDto; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.db.metric.MetricTesting.newMetricDto; public class MeasureMatrixTest { @@ -43,8 +42,6 @@ public class MeasureMatrixTest { private static final MetricDto METRIC_1 = newMetricDto().setUuid("100"); private static final MetricDto METRIC_2 = newMetricDto().setUuid("200"); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void getMetric() { @@ -60,10 +57,9 @@ public class MeasureMatrixTest { Collection metrics = asList(METRIC_1); MeasureMatrix underTest = new MeasureMatrix(asList(PROJECT, FILE), metrics, new ArrayList<>()); - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("Metric with uuid " + METRIC_2.getUuid() + " not found"); - - underTest.getMetricByUuid(METRIC_2.getUuid()); + assertThatThrownBy(() -> underTest.getMetricByUuid(METRIC_2.getUuid())) + .isInstanceOf(NullPointerException.class) + .hasMessage("Metric with uuid " + METRIC_2.getUuid() + " not found"); } @Test @@ -79,10 +75,9 @@ public class MeasureMatrixTest { public void getMeasure_throws_IAE_if_metric_is_not_registered() { MeasureMatrix underTest = new MeasureMatrix(asList(PROJECT), asList(METRIC_1), emptyList()); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Metric with key _missing_ is not registered"); - - underTest.getMeasure(PROJECT, "_missing_"); + assertThatThrownBy(() -> underTest.getMeasure(PROJECT, "_missing_")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Metric with key _missing_ is not registered"); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/ws/ComponentActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/ws/ComponentActionTest.java index f51e1d3eb7d..44297a42475 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/ws/ComponentActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/ws/ComponentActionTest.java @@ -22,7 +22,6 @@ package org.sonar.server.measure.ws; import java.util.function.Function; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.api.server.ws.WebService.Param; import org.sonar.api.utils.System2; @@ -46,6 +45,7 @@ import org.sonarqube.ws.Measures.ComponentWsResponse; import static java.lang.Double.parseDouble; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.api.utils.DateUtils.parseDateTime; import static org.sonar.api.web.UserRole.USER; @@ -64,8 +64,6 @@ public class ComponentActionTest { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Rule public DbTester db = DbTester.create(System2.INSTANCE); private final WsActionTester ws = new WsActionTester(new ComponentAction(db.getDbClient(), TestComponentFinder.from(db), userSession)); @@ -304,10 +302,9 @@ public class ComponentActionTest { db.measures().insertMetric(m -> m.setKey("ncloc").setValueType("INT")); db.measures().insertMetric(m -> m.setKey("complexity").setValueType("INT")); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("The following metric keys are not found: unknown-metric, another-unknown-metric"); - - newRequest(project.getKey(), "ncloc, complexity, unknown-metric, another-unknown-metric"); + assertThatThrownBy(() -> newRequest(project.getKey(), "ncloc, complexity, unknown-metric, another-unknown-metric")) + .isInstanceOf(NotFoundException.class) + .hasMessage("The following metric keys are not found: unknown-metric, another-unknown-metric"); } @Test @@ -316,10 +313,9 @@ public class ComponentActionTest { userSession.addProjectPermission(UserRole.USER, project); db.components().insertSnapshot(project); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("At least one metric key must be provided"); - - newRequest(project.getKey(), ""); + assertThatThrownBy(() -> newRequest(project.getKey(), "")) + .isInstanceOf(BadRequestException.class) + .hasMessage("At least one metric key must be provided"); } @Test @@ -329,22 +325,22 @@ public class ComponentActionTest { db.components().insertSnapshot(project); MetricDto metric = db.measures().insertMetric(m -> m.setValueType("INT")); - expectedException.expect(ForbiddenException.class); - - newRequest(project.getKey(), metric.getKey()); + assertThatThrownBy(() -> newRequest(project.getKey(), metric.getKey())) + .isInstanceOf(ForbiddenException.class); } @Test public void fail_when_component_does_not_exist() { MetricDto metric = db.measures().insertMetric(m -> m.setValueType("INT")); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Component key 'project-key' not found"); - - ws.newRequest() - .setParam(PARAM_COMPONENT, "project-key") - .setParam(PARAM_METRIC_KEYS, metric.getKey()) - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam(PARAM_COMPONENT, "project-key") + .setParam(PARAM_METRIC_KEYS, metric.getKey()) + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("Component key 'project-key' not found"); } @Test @@ -354,13 +350,14 @@ public class ComponentActionTest { userSession.addProjectPermission(USER, project); MetricDto metric = db.measures().insertMetric(m -> m.setValueType("INT")); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(String.format("Component key '%s' not found", project.getKey())); - - ws.newRequest() - .setParam(PARAM_COMPONENT, project.getKey()) - .setParam(PARAM_METRIC_KEYS, metric.getKey()) - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam(PARAM_COMPONENT, project.getKey()) + .setParam(PARAM_METRIC_KEYS, metric.getKey()) + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage(String.format("Component key '%s' not found", project.getKey())); } @Test @@ -370,14 +367,15 @@ public class ComponentActionTest { userSession.addProjectPermission(UserRole.USER, project); db.components().insertProjectBranch(project, b -> b.setKey("my_branch")); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(String.format("Component '%s' on branch '%s' not found", file.getKey(), "another_branch")); - - ws.newRequest() - .setParam(PARAM_COMPONENT, file.getKey()) - .setParam(PARAM_BRANCH, "another_branch") - .setParam(PARAM_METRIC_KEYS, "ncloc") - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam(PARAM_COMPONENT, file.getKey()) + .setParam(PARAM_BRANCH, "another_branch") + .setParam(PARAM_METRIC_KEYS, "ncloc") + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage(String.format("Component '%s' on branch '%s' not found", file.getKey(), "another_branch")); } @Test @@ -387,13 +385,14 @@ public class ComponentActionTest { ComponentDto branch = db.components().insertProjectBranch(project); MetricDto metric = db.measures().insertMetric(m -> m.setValueType("INT")); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(format("Component key '%s' not found", branch.getDbKey())); - - ws.newRequest() - .setParam(PARAM_COMPONENT, branch.getDbKey()) - .setParam(PARAM_METRIC_KEYS, metric.getKey()) - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam(PARAM_COMPONENT, branch.getDbKey()) + .setParam(PARAM_METRIC_KEYS, metric.getKey()) + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage(format("Component key '%s' not found", branch.getDbKey())); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/ws/ComponentTreeActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/ws/ComponentTreeActionTest.java index c09b3e68524..8f467a74fc4 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/ws/ComponentTreeActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/ws/ComponentTreeActionTest.java @@ -24,7 +24,6 @@ import java.util.List; import java.util.stream.IntStream; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.measures.CoreMetrics; import org.sonar.api.measures.Metric; import org.sonar.api.server.ws.WebService.Param; @@ -56,6 +55,7 @@ import static java.lang.Double.parseDouble; import static java.lang.String.format; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_RATING_KEY; import static org.sonar.api.measures.Metric.ValueType.DISTRIB; @@ -73,8 +73,6 @@ import static org.sonar.db.component.BranchType.PULL_REQUEST; import static org.sonar.db.component.ComponentTesting.newDirectory; import static org.sonar.db.component.ComponentTesting.newFileDto; import static org.sonar.db.component.ComponentTesting.newProjectCopy; -import static org.sonar.db.component.ComponentTesting.newSubPortfolio; -import static org.sonar.db.component.ComponentTesting.newPortfolio; import static org.sonar.db.component.SnapshotTesting.newAnalysis; import static org.sonar.server.component.ws.MeasuresWsParameters.ADDITIONAL_PERIOD; import static org.sonar.server.component.ws.MeasuresWsParameters.DEPRECATED_ADDITIONAL_PERIODS; @@ -101,8 +99,6 @@ public class ComponentTreeActionTest { @Rule public UserSessionRule userSession = UserSessionRule.standalone().logIn().setRoot(); @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Rule public DbTester db = DbTester.create(System2.INSTANCE); private final I18nRule i18n = new I18nRule(); @@ -731,13 +727,14 @@ public class ComponentTreeActionTest { ComponentDto project = db.components().insertPrivateProject(); db.components().insertSnapshot(project); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("The 'metricKeys' parameter must contain at least one metric key"); - - ws.newRequest() - .setParam(PARAM_COMPONENT, project.getKey()) - .setParam(PARAM_METRIC_KEYS, "") - .executeProtobuf(ComponentTreeWsResponse.class); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam(PARAM_COMPONENT, project.getKey()) + .setParam(PARAM_METRIC_KEYS, "") + .executeProtobuf(ComponentTreeWsResponse.class); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("The 'metricKeys' parameter must contain at least one metric key"); } @Test @@ -746,12 +743,14 @@ public class ComponentTreeActionTest { db.components().insertSnapshot(project); insertNclocMetric(); insertNewViolationsMetric(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("The following metric keys are not found: unknown-metric, another-unknown-metric"); - ws.newRequest() - .setParam(PARAM_COMPONENT, project.getKey()) - .setParam(PARAM_METRIC_KEYS, "ncloc, new_violations, unknown-metric, another-unknown-metric").executeProtobuf(ComponentTreeWsResponse.class); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam(PARAM_COMPONENT, project.getKey()) + .setParam(PARAM_METRIC_KEYS, "ncloc, new_violations, unknown-metric, another-unknown-metric").executeProtobuf(ComponentTreeWsResponse.class); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("The following metric keys are not found: unknown-metric, another-unknown-metric"); } @Test @@ -762,13 +761,14 @@ public class ComponentTreeActionTest { dbClient.metricDao().insert(dbSession, newMetricDto().setKey("distrib2").setValueType(DISTRIB.name())); db.commit(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Metrics distrib1, distrib2 can't be requested in this web service. Please use api/measures/component"); - - ws.newRequest() - .setParam(PARAM_COMPONENT, project.getKey()) - .setParam(PARAM_METRIC_KEYS, "distrib1,distrib2") - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam(PARAM_COMPONENT, project.getKey()) + .setParam(PARAM_METRIC_KEYS, "distrib1,distrib2") + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Metrics distrib1, distrib2 can't be requested in this web service. Please use api/measures/component"); } @Test @@ -780,13 +780,14 @@ public class ComponentTreeActionTest { dbClient.metricDao().insert(dbSession, newMetricDto().setKey("data2").setValueType(DISTRIB.name())); db.commit(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Metrics data1, data2 can't be requested in this web service. Please use api/measures/component"); - - ws.newRequest() - .setParam(PARAM_COMPONENT, project.getKey()) - .setParam(PARAM_METRIC_KEYS, "data1,data2") - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam(PARAM_COMPONENT, project.getKey()) + .setParam(PARAM_METRIC_KEYS, "data1,data2") + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Metrics data1, data2 can't be requested in this web service. Please use api/measures/component"); } @Test @@ -798,13 +799,14 @@ public class ComponentTreeActionTest { .collect(MoreCollectors.toList()); db.commit(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("'metricKeys' can contains only 15 values, got 20"); - - ws.newRequest() - .setParam(PARAM_COMPONENT, project.getKey()) - .setParam(PARAM_METRIC_KEYS, Joiner.on(",").join(metrics)) - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam(PARAM_COMPONENT, project.getKey()) + .setParam(PARAM_METRIC_KEYS, Joiner.on(",").join(metrics)) + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("'metricKeys' can contains only 15 values, got 20"); } @Test @@ -813,14 +815,16 @@ public class ComponentTreeActionTest { db.components().insertSnapshot(project); insertNclocMetric(); insertNewViolationsMetric(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("'q' length (2) is shorter than the minimum authorized (3)"); - ws.newRequest() - .setParam(PARAM_COMPONENT, project.getKey()) - .setParam(PARAM_METRIC_KEYS, "ncloc, new_violations") - .setParam(Param.TEXT_QUERY, "fi") - .executeProtobuf(ComponentTreeWsResponse.class); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam(PARAM_COMPONENT, project.getKey()) + .setParam(PARAM_METRIC_KEYS, "ncloc, new_violations") + .setParam(Param.TEXT_QUERY, "fi") + .executeProtobuf(ComponentTreeWsResponse.class); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("'q' length (2) is shorter than the minimum authorized (3)"); } @Test @@ -829,28 +833,30 @@ public class ComponentTreeActionTest { ComponentDto project = db.components().insertPrivateProject(); db.components().insertSnapshot(project); - expectedException.expect(ForbiddenException.class); - - ws.newRequest() - .setParam(PARAM_COMPONENT, project.getKey()) - .setParam(PARAM_METRIC_KEYS, "ncloc") - .executeProtobuf(ComponentTreeWsResponse.class); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam(PARAM_COMPONENT, project.getKey()) + .setParam(PARAM_METRIC_KEYS, "ncloc") + .executeProtobuf(ComponentTreeWsResponse.class); + }) + .isInstanceOf(ForbiddenException.class); } @Test public void fail_when_sort_by_metric_and_no_metric_sort_provided() { ComponentDto project = db.components().insertPrivateProject(); db.components().insertSnapshot(project); - expectedException.expect(BadRequestException.class); - expectedException - .expectMessage("To sort by a metric, the 's' parameter must contain 'metric' or 'metricPeriod', and a metric key must be provided in the 'metricSort' parameter"); - ws.newRequest() - .setParam(PARAM_COMPONENT, project.getKey()) - .setParam(PARAM_METRIC_KEYS, "ncloc") - // PARAM_METRIC_SORT is not set - .setParam(SORT, METRIC_SORT) - .executeProtobuf(ComponentTreeWsResponse.class); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam(PARAM_COMPONENT, project.getKey()) + .setParam(PARAM_METRIC_KEYS, "ncloc") + // PARAM_METRIC_SORT is not set + .setParam(SORT, METRIC_SORT) + .executeProtobuf(ComponentTreeWsResponse.class); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("To sort by a metric, the 's' parameter must contain 'metric' or 'metricPeriod', and a metric key must be provided in the 'metricSort' parameter"); } @Test @@ -858,15 +864,16 @@ public class ComponentTreeActionTest { ComponentDto project = db.components().insertPrivateProject(); db.components().insertSnapshot(project); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("To sort by the 'complexity' metric, it must be in the list of metric keys in the 'metricKeys' parameter"); - - ws.newRequest() - .setParam(PARAM_COMPONENT, project.getKey()) - .setParam(PARAM_METRIC_KEYS, "ncloc,violations") - .setParam(PARAM_METRIC_SORT, "complexity") - .setParam(SORT, METRIC_SORT) - .executeProtobuf(ComponentTreeWsResponse.class); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam(PARAM_COMPONENT, project.getKey()) + .setParam(PARAM_METRIC_KEYS, "ncloc,violations") + .setParam(PARAM_METRIC_SORT, "complexity") + .setParam(SORT, METRIC_SORT) + .executeProtobuf(ComponentTreeWsResponse.class); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("To sort by the 'complexity' metric, it must be in the list of metric keys in the 'metricKeys' parameter"); } @Test @@ -874,16 +881,17 @@ public class ComponentTreeActionTest { ComponentDto project = db.components().insertPrivateProject(); db.components().insertSnapshot(project); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("To sort by a metric period, the 's' parameter must contain 'metricPeriod' and the 'metricPeriodSort' must be provided."); - - ws.newRequest() - .setParam(PARAM_COMPONENT, project.getKey()) - .setParam(PARAM_METRIC_KEYS, "ncloc") - .setParam(PARAM_METRIC_SORT, "ncloc") - // PARAM_METRIC_PERIOD_SORT_IS_NOT_SET - .setParam(SORT, METRIC_PERIOD_SORT) - .executeProtobuf(ComponentTreeWsResponse.class); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam(PARAM_COMPONENT, project.getKey()) + .setParam(PARAM_METRIC_KEYS, "ncloc") + .setParam(PARAM_METRIC_SORT, "ncloc") + // PARAM_METRIC_PERIOD_SORT_IS_NOT_SET + .setParam(SORT, METRIC_PERIOD_SORT) + .executeProtobuf(ComponentTreeWsResponse.class); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("To sort by a metric period, the 's' parameter must contain 'metricPeriod' and the 'metricPeriodSort' must be provided."); } @Test @@ -892,14 +900,15 @@ public class ComponentTreeActionTest { db.components().insertSnapshot(project); insertNclocMetric(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("'ps' value (2540) must be less than 500"); - - ws.newRequest() - .setParam(PARAM_COMPONENT, project.getKey()) - .setParam(PARAM_METRIC_KEYS, "ncloc") - .setParam(Param.PAGE_SIZE, "2540") - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam(PARAM_COMPONENT, project.getKey()) + .setParam(PARAM_METRIC_KEYS, "ncloc") + .setParam(Param.PAGE_SIZE, "2540") + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("'ps' value (2540) must be less than 500"); } @Test @@ -908,28 +917,29 @@ public class ComponentTreeActionTest { db.components().insertSnapshot(project); insertNclocMetric(); - expectedException.expect(BadRequestException.class); - expectedException - .expectMessage("To filter components based on the sort metric, the 's' parameter must contain 'metric' or 'metricPeriod' and the 'metricSort' parameter must be provided"); - - ws.newRequest() - .setParam(PARAM_COMPONENT, project.getKey()) - .setParam(PARAM_METRIC_KEYS, "ncloc") - .setParam(PARAM_METRIC_SORT_FILTER, WITH_MEASURES_ONLY_METRIC_SORT_FILTER) - .executeProtobuf(ComponentTreeWsResponse.class); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam(PARAM_COMPONENT, project.getKey()) + .setParam(PARAM_METRIC_KEYS, "ncloc") + .setParam(PARAM_METRIC_SORT_FILTER, WITH_MEASURES_ONLY_METRIC_SORT_FILTER) + .executeProtobuf(ComponentTreeWsResponse.class); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("To filter components based on the sort metric, the 's' parameter must contain 'metric' or 'metricPeriod' and the 'metricSort' parameter must be provided"); } @Test public void fail_when_component_does_not_exist() { insertNclocMetric(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Component key 'project-key' not found"); - - ws.newRequest() - .setParam(PARAM_COMPONENT, "project-key") - .setParam(PARAM_METRIC_KEYS, "ncloc") - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam(PARAM_COMPONENT, "project-key") + .setParam(PARAM_METRIC_KEYS, "ncloc") + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("Component key 'project-key' not found"); } @Test @@ -940,13 +950,14 @@ public class ComponentTreeActionTest { userSession.anonymous().addProjectPermission(UserRole.USER, project); insertNclocMetric(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(format("Component key '%s' not found", file.getKey())); - - ws.newRequest() - .setParam(PARAM_COMPONENT, file.getKey()) - .setParam(PARAM_METRIC_KEYS, "ncloc") - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam(PARAM_COMPONENT, file.getKey()) + .setParam(PARAM_METRIC_KEYS, "ncloc") + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage(format("Component key '%s' not found", file.getKey())); } @Test @@ -956,14 +967,15 @@ public class ComponentTreeActionTest { userSession.addProjectPermission(UserRole.USER, project); db.components().insertProjectBranch(project, b -> b.setKey("my_branch")); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(String.format("Component '%s' on branch '%s' not found", file.getKey(), "another_branch")); - - ws.newRequest() - .setParam(PARAM_COMPONENT, file.getKey()) - .setParam(PARAM_BRANCH, "another_branch") - .setParam(PARAM_METRIC_KEYS, "ncloc") - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam(PARAM_COMPONENT, file.getKey()) + .setParam(PARAM_BRANCH, "another_branch") + .setParam(PARAM_METRIC_KEYS, "ncloc") + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage(String.format("Component '%s' on branch '%s' not found", file.getKey(), "another_branch")); } @Test @@ -973,13 +985,14 @@ public class ComponentTreeActionTest { ComponentDto branch = db.components().insertProjectBranch(project); insertNclocMetric(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(format("Component key '%s' not found", branch.getDbKey())); - - ws.newRequest() - .setParam(PARAM_COMPONENT, branch.getDbKey()) - .setParam(PARAM_METRIC_KEYS, "ncloc") - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam(PARAM_COMPONENT, branch.getDbKey()) + .setParam(PARAM_METRIC_KEYS, "ncloc") + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage(format("Component key '%s' not found", branch.getDbKey())); } private static MetricDto newMetricDto() { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/ws/MeasureValueFormatterTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/ws/MeasureValueFormatterTest.java index 46c6a52c550..a9c98a5d7eb 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/ws/MeasureValueFormatterTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/ws/MeasureValueFormatterTest.java @@ -19,14 +19,13 @@ */ package org.sonar.server.measure.ws; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.measures.Metric; import org.sonar.db.measure.MeasureDto; import org.sonar.db.metric.MetricDto; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.measures.Metric.ValueType.BOOL; import static org.sonar.api.measures.Metric.ValueType.DATA; import static org.sonar.api.measures.Metric.ValueType.FLOAT; @@ -40,8 +39,6 @@ import static org.sonar.server.measure.ws.MeasureValueFormatter.formatNumericalV public class MeasureValueFormatterTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void test_formatNumericalValue() { @@ -65,10 +62,9 @@ public class MeasureValueFormatterTest { @Test public void fail_if_text_value_type_for_numeric_formatter() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Unsupported metric type 'DATA' for numerical value"); - - formatNumericalValue(42.0d, newMetric(DATA)); + assertThatThrownBy(() -> formatNumericalValue(42.0d, newMetric(DATA))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Unsupported metric type 'DATA' for numerical value"); } private static MetricDto newMetric(Metric.ValueType valueType) { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/ws/SearchActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/ws/SearchActionTest.java index e57992781b0..9d4a42e08b9 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/ws/SearchActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/ws/SearchActionTest.java @@ -27,7 +27,6 @@ import java.util.stream.IntStream; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.api.web.UserRole; @@ -47,6 +46,7 @@ import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.api.measures.Metric.ValueType.FLOAT; import static org.sonar.api.measures.Metric.ValueType.INT; @@ -60,8 +60,6 @@ import static org.sonar.test.JsonAssert.assertJson; public class SearchActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone().logIn(); @@ -286,10 +284,9 @@ public class SearchActionTest { ComponentDto project = db.components().insertPrivateProject(); userSession.addProjectPermission(UserRole.USER, project); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The 'metricKeys' parameter is missing"); - - call(singletonList(project.uuid()), null); + assertThatThrownBy(() -> call(singletonList(project.uuid()), null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("The 'metricKeys' parameter is missing"); } @Test @@ -297,10 +294,9 @@ public class SearchActionTest { ComponentDto project = db.components().insertPrivateProject(); userSession.addProjectPermission(UserRole.USER, project); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Metric keys must be provided"); - - call(singletonList(project.uuid()), emptyList()); + assertThatThrownBy(() -> call(singletonList(project.uuid()), emptyList())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Metric keys must be provided"); } @Test @@ -309,30 +305,27 @@ public class SearchActionTest { userSession.addProjectPermission(UserRole.USER, project); MetricDto metric = db.measures().insertMetric(); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("The following metrics are not found: ncloc, violations"); - - call(singletonList(project.getDbKey()), newArrayList("violations", metric.getKey(), "ncloc")); + assertThatThrownBy(() -> call(singletonList(project.getDbKey()), newArrayList("violations", metric.getKey(), "ncloc"))) + .isInstanceOf(BadRequestException.class) + .hasMessage("The following metrics are not found: ncloc, violations"); } @Test public void fail_if_no_project() { MetricDto metric = db.measures().insertMetric(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Project keys must be provided"); - - call(null, singletonList(metric.getKey())); + assertThatThrownBy(() -> call(null, singletonList(metric.getKey()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Project keys must be provided"); } @Test public void fail_if_empty_project_key() { MetricDto metric = db.measures().insertMetric(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Project keys must be provided"); - - call(emptyList(), singletonList(metric.getKey())); + assertThatThrownBy(() -> call(emptyList(), singletonList(metric.getKey()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Project keys must be provided"); } @Test @@ -343,10 +336,9 @@ public class SearchActionTest { .collect(Collectors.toList()); MetricDto metric = db.measures().insertMetric(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("101 projects provided, more than maximum authorized (100)"); - - call(keys, singletonList(metric.getKey())); + assertThatThrownBy(() -> call(keys, singletonList(metric.getKey()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("101 projects provided, more than maximum authorized (100)"); } @Test @@ -367,10 +359,9 @@ public class SearchActionTest { userSession.addProjectPermission(UserRole.USER, project); MetricDto metric = db.measures().insertMetric(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Only component of qualifiers [TRK, APP, VW, SVW] are allowed"); - - call(singletonList(module.getDbKey()), singletonList(metric.getKey())); + assertThatThrownBy(() -> call(singletonList(module.getDbKey()), singletonList(metric.getKey()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Only component of qualifiers [TRK, APP, VW, SVW] are allowed"); } @Test @@ -380,10 +371,9 @@ public class SearchActionTest { userSession.addProjectPermission(UserRole.USER, project); MetricDto metric = db.measures().insertMetric(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Only component of qualifiers [TRK, APP, VW, SVW] are allowed"); - - call(singletonList(dir.getDbKey()), singletonList(metric.getKey())); + assertThatThrownBy(() -> call(singletonList(dir.getDbKey()), singletonList(metric.getKey()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Only component of qualifiers [TRK, APP, VW, SVW] are allowed"); } @Test @@ -393,10 +383,9 @@ public class SearchActionTest { userSession.addProjectPermission(UserRole.USER, project); MetricDto metric = db.measures().insertMetric(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Only component of qualifiers [TRK, APP, VW, SVW] are allowed"); - - call(singletonList(file.getDbKey()), singletonList(metric.getKey())); + assertThatThrownBy(() -> call(singletonList(file.getDbKey()), singletonList(metric.getKey()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Only component of qualifiers [TRK, APP, VW, SVW] are allowed"); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/ws/SearchHistoryActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/ws/SearchHistoryActionTest.java index e3e9a8a791c..97706e532ef 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/ws/SearchHistoryActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/measure/ws/SearchHistoryActionTest.java @@ -24,7 +24,6 @@ import java.util.stream.LongStream; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.measures.Metric.ValueType; import org.sonar.api.server.ws.WebService; import org.sonar.api.server.ws.WebService.Param; @@ -56,6 +55,7 @@ import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static java.util.Optional.ofNullable; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.api.utils.DateUtils.formatDateTime; import static org.sonar.api.utils.DateUtils.parseDateTime; @@ -79,8 +79,6 @@ public class SearchHistoryActionTest { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Rule public DbTester db = DbTester.create(); private final DbClient dbClient = db.getDbClient(); @@ -345,13 +343,12 @@ public class SearchHistoryActionTest { userSession.logIn().addProjectPermission(UserRole.USER, project); ComponentDto branch = db.components().insertProjectBranch(project); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(format("Component key '%s' not found", branch.getDbKey())); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_COMPONENT, branch.getDbKey()) .setParam(PARAM_METRICS, "ncloc") - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining(format("Component key '%s' not found", branch.getDbKey())); } @Test @@ -361,10 +358,9 @@ public class SearchHistoryActionTest { .setMetrics(asList(complexityMetric.getKey(), nclocMetric.getKey(), "METRIC_42", "42_METRIC")) .build(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Metrics 42_METRIC, METRIC_42 are not found"); - - call(request); + assertThatThrownBy(() -> call(request)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Metrics 42_METRIC, METRIC_42 are not found"); } @Test @@ -375,9 +371,8 @@ public class SearchHistoryActionTest { .setMetrics(singletonList(complexityMetric.getKey())) .build(); - expectedException.expect(ForbiddenException.class); - - call(request); + assertThatThrownBy(() -> call(request)) + .isInstanceOf(ForbiddenException.class); } @Test @@ -387,9 +382,8 @@ public class SearchHistoryActionTest { .setMetrics(singletonList(complexityMetric.getKey())) .build(); - expectedException.expect(NotFoundException.class); - - call(request); + assertThatThrownBy(() -> call(request)) + .isInstanceOf(NotFoundException.class); } @Test @@ -398,13 +392,12 @@ public class SearchHistoryActionTest { db.components().insertComponent(newFileDto(project).setDbKey("file-key").setEnabled(false)); userSession.addProjectPermission(UserRole.USER, project); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Component key 'file-key' not found"); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_COMPONENT, "file-key") .setParam(PARAM_METRICS, "ncloc") - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("Component key 'file-key' not found"); } @Test @@ -414,14 +407,13 @@ public class SearchHistoryActionTest { userSession.addProjectPermission(UserRole.USER, project); db.components().insertProjectBranch(project, b -> b.setKey("my_branch")); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(String.format("Component '%s' on branch '%s' not found", file.getKey(), "another_branch")); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_COMPONENT, file.getKey()) .setParam(PARAM_BRANCH, "another_branch") .setParam(PARAM_METRICS, "ncloc") - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining(String.format("Component '%s' on branch '%s' not found", file.getKey(), "another_branch")); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/metric/ws/MetricKeyValidatorTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/metric/ws/MetricKeyValidatorTest.java index 2a76a8c9970..2aa9a6fd31b 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/metric/ws/MetricKeyValidatorTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/metric/ws/MetricKeyValidatorTest.java @@ -19,16 +19,13 @@ */ package org.sonar.server.metric.ws; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class MetricKeyValidatorTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void isMetricKeyValid() { @@ -41,9 +38,8 @@ public class MetricKeyValidatorTest { @Test public void checkMetricKeyFormat() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Malformed metric key '123456'. Allowed characters are alphanumeric, '-', '_', with at least one non-digit."); - - MetricKeyValidator.checkMetricKeyFormat("123456"); + assertThatThrownBy(() -> MetricKeyValidator.checkMetricKeyFormat("123456")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Malformed metric key '123456'. Allowed characters are alphanumeric, '-', '_', with at least one non-digit."); } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/newcodeperiod/ws/ListActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/newcodeperiod/ws/ListActionTest.java index 7a3aee18e00..393da42626b 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/newcodeperiod/ws/ListActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/newcodeperiod/ws/ListActionTest.java @@ -23,7 +23,6 @@ import java.time.Instant; import java.util.Optional; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.DateUtils; import org.sonar.api.utils.System2; @@ -50,11 +49,10 @@ import org.sonarqube.ws.NewCodePeriods.ListWSResponse; import org.sonarqube.ws.NewCodePeriods.ShowWSResponse; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.db.component.SnapshotTesting.newAnalysis; public class ListActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -83,23 +81,22 @@ public class ListActionTest { @Test public void throw_NFE_if_project_not_found() { - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Project 'unknown' not found"); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("project", "unknown") - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("Project 'unknown' not found"); } @Test public void throw_FE_if_no_project_permission() { ComponentDto project = componentDb.insertPublicProject(); - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("project", project.getKey()) - .execute(); + .execute()) + .isInstanceOf(ForbiddenException.class) + .hasMessageContaining("Insufficient privileges"); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/newcodeperiod/ws/SetActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/newcodeperiod/ws/SetActionTest.java index 20a5d107554..a82e1f475f7 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/newcodeperiod/ws/SetActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/newcodeperiod/ws/SetActionTest.java @@ -26,7 +26,6 @@ import java.util.Optional; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; @@ -51,14 +50,13 @@ import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.entry; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @RunWith(DataProviderRunner.class) public class SetActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -93,31 +91,23 @@ public class SetActionTest { // validation of type @Test public void throw_IAE_if_no_type_specified() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The 'type' parameter is missing"); - - ws.newRequest() - .execute(); + assertThatThrownBy(() -> ws.newRequest().execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("The 'type' parameter is missing"); } @Test public void throw_IAE_if_type_is_invalid() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Invalid type: unknown"); - - ws.newRequest() - .setParam("type", "unknown") - .execute(); + assertThatThrownBy(() -> ws.newRequest().setParam("type", "unknown").execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Invalid type: unknown"); } @Test public void throw_IAE_if_type_is_invalid_for_global() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Invalid type 'SPECIFIC_ANALYSIS'. Overall setting can only be set with types: [PREVIOUS_VERSION, NUMBER_OF_DAYS]"); - - ws.newRequest() - .setParam("type", "specific_analysis") - .execute(); + assertThatThrownBy(() -> ws.newRequest().setParam("type", "specific_analysis").execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Invalid type 'SPECIFIC_ANALYSIS'. Overall setting can only be set with types: [PREVIOUS_VERSION, NUMBER_OF_DAYS]"); } @Test @@ -125,71 +115,70 @@ public class SetActionTest { ComponentDto project = componentDb.insertPublicProject(); logInAsProjectAdministrator(project); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Invalid type 'SPECIFIC_ANALYSIS'. Projects can only be set with types: [PREVIOUS_VERSION, NUMBER_OF_DAYS, REFERENCE_BRANCH]"); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("project", project.getKey()) .setParam("type", "specific_analysis") - .execute(); + .execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Invalid type 'SPECIFIC_ANALYSIS'. Projects can only be set with types: [PREVIOUS_VERSION, NUMBER_OF_DAYS, REFERENCE_BRANCH]"); } @Test public void throw_IAE_if_no_value_for_days() { ComponentDto project = componentDb.insertPublicProject(); logInAsProjectAdministrator(project); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("New Code Period type 'NUMBER_OF_DAYS' requires a value"); - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("project", project.getKey()) .setParam("branch", "master") .setParam("type", "number_of_days") - .execute(); + .execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("New Code Period type 'NUMBER_OF_DAYS' requires a value"); } @Test public void throw_IAE_if_no_value_for_analysis() { ComponentDto project = componentDb.insertPublicProject(); logInAsProjectAdministrator(project); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("New Code Period type 'SPECIFIC_ANALYSIS' requires a value"); - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("project", project.getKey()) .setParam("type", "specific_analysis") .setParam("branch", "master") - .execute(); + .execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("New Code Period type 'SPECIFIC_ANALYSIS' requires a value"); } @Test public void throw_IAE_if_days_is_invalid() { ComponentDto project = componentDb.insertPublicProject(); logInAsProjectAdministrator(project); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Failed to parse number of days: unknown"); - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("project", project.getKey()) .setParam("type", "number_of_days") .setParam("branch", "master") .setParam("value", "unknown") - .execute(); + .execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Failed to parse number of days: unknown"); } @Test public void throw_IAE_if_analysis_is_not_found() { ComponentDto project = componentDb.insertPublicProject(); logInAsProjectAdministrator(project); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Analysis 'unknown' is not found"); - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("project", project.getKey()) .setParam("type", "specific_analysis") .setParam("branch", "master") .setParam("value", "unknown") - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("Analysis 'unknown' is not found"); } @Test @@ -201,74 +190,71 @@ public class SetActionTest { SnapshotDto analysisBranch = db.components().insertSnapshot(branch); logInAsProjectAdministrator(project); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Analysis '" + analysisBranch.getUuid() + "' does not belong to branch 'master' of project '" + project.getKey() + "'"); - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("project", project.getKey()) .setParam("type", "specific_analysis") .setParam("branch", "master") .setParam("value", analysisBranch.getUuid()) - .execute(); + .execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Analysis '" + analysisBranch.getUuid() + "' does not belong to branch 'master' of project '" + project.getKey() + "'"); } // validation of project/branch @Test public void throw_IAE_if_branch_is_specified_without_project() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("If branch key is specified, project key needs to be specified too"); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("branch", "branch") - .execute(); + .execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("If branch key is specified, project key needs to be specified too"); } @Test public void throw_NFE_if_project_not_found() { - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Project 'unknown' not found"); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("type", "previous_version") .setParam("project", "unknown") - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("Project 'unknown' not found"); } @Test public void throw_NFE_if_branch_not_found() { ComponentDto project = componentDb.insertPublicProject(); logInAsProjectAdministrator(project); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Branch 'unknown' in project '" + project.getKey() + "' not found"); - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("project", project.getKey()) .setParam("type", "previous_version") .setParam("branch", "unknown") - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("Branch 'unknown' in project '" + project.getKey() + "' not found"); } // permission @Test public void throw_NFE_if_no_project_permission() { ComponentDto project = componentDb.insertPublicProject(); - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("project", project.getKey()) .setParam("type", "previous_version") - .execute(); + .execute()) + .isInstanceOf(ForbiddenException.class) + .hasMessageContaining("Insufficient privileges"); } @Test public void throw_NFE_if_no_system_permission() { - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("type", "previous_version") - .execute(); + .execute()) + .isInstanceOf(ForbiddenException.class) + .hasMessageContaining("Insufficient privileges"); } // success cases diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/newcodeperiod/ws/ShowActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/newcodeperiod/ws/ShowActionTest.java index 1ab7ed1bb5c..24ee87bee71 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/newcodeperiod/ws/ShowActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/newcodeperiod/ws/ShowActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.newcodeperiod.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.api.web.UserRole; @@ -44,10 +43,9 @@ import org.sonarqube.ws.NewCodePeriods; import org.sonarqube.ws.NewCodePeriods.ShowWSResponse; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class ShowActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -78,23 +76,22 @@ public class ShowActionTest { @Test public void throw_IAE_if_branch_is_specified_without_project() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("If branch key is specified, project key needs to be specified too"); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("branch", "branch") - .execute(); + .execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("If branch key is specified, project key needs to be specified too"); } @Test public void throw_FE_if_no_project_permission() { ComponentDto project = componentDb.insertPublicProject(); - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("project", project.getKey()) - .execute(); + .execute()) + .isInstanceOf(ForbiddenException.class) + .hasMessageContaining("Insufficient privileges"); } @Test @@ -102,12 +99,11 @@ public class ShowActionTest { ComponentDto project = componentDb.insertPublicProject(); logInAsProjectIssueAdmin(project); - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("project", project.getKey()) - .execute(); + .execute()) + .isInstanceOf(ForbiddenException.class) + .hasMessageContaining("Insufficient privileges"); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/newcodeperiod/ws/UnsetActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/newcodeperiod/ws/UnsetActionTest.java index e457716d1c6..80163bf66af 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/newcodeperiod/ws/UnsetActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/newcodeperiod/ws/UnsetActionTest.java @@ -23,7 +23,6 @@ import java.util.Optional; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.api.web.UserRole; @@ -45,13 +44,12 @@ import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.entry; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class UnsetActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -84,60 +82,57 @@ public class UnsetActionTest { // validation of project/branch @Test public void throw_IAE_if_branch_is_specified_without_project() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("If branch key is specified, project key needs to be specified too"); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("branch", "branch") - .execute(); + .execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("If branch key is specified, project key needs to be specified too"); } @Test public void throw_NFE_if_project_not_found() { - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Project 'unknown' not found"); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("type", "previous_version") .setParam("project", "unknown") - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("Project 'unknown' not found"); } @Test public void throw_NFE_if_branch_not_found() { ComponentDto project = componentDb.insertPublicProject(); logInAsProjectAdministrator(project); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Branch 'unknown' in project '" + project.getKey() + "' not found"); - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("project", project.getKey()) .setParam("type", "previous_version") .setParam("branch", "unknown") - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("Branch 'unknown' in project '" + project.getKey() + "' not found"); } // permission @Test public void throw_NFE_if_no_project_permission() { ComponentDto project = componentDb.insertPublicProject(); - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("project", project.getKey()) .setParam("type", "previous_version") - .execute(); + .execute()) + .isInstanceOf(ForbiddenException.class) + .hasMessageContaining("Insufficient privileges"); } @Test public void throw_NFE_if_no_system_permission() { - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("type", "previous_version") - .execute(); + .execute()) + .isInstanceOf(ForbiddenException.class) + .hasMessageContaining("Insufficient privileges"); } // success cases diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/notification/ws/AddActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/notification/ws/AddActionTest.java index a9eb0e0e65f..8fa2320dc85 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/notification/ws/AddActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/notification/ws/AddActionTest.java @@ -22,7 +22,6 @@ package org.sonar.server.notification.ws; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.notifications.Notification; import org.sonar.api.notifications.NotificationChannel; import org.sonar.db.DbClient; @@ -46,6 +45,7 @@ import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static java.util.Optional.ofNullable; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.api.web.UserRole.USER; @@ -60,8 +60,6 @@ public class AddActionTest { private static final String NOTIF_NEW_ISSUES = "Dispatcher2"; private static final String NOTIF_NEW_QUALITY_GATE_STATUS = "Dispatcher3"; - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -77,8 +75,8 @@ public class AddActionTest { private Dispatchers dispatchers = mock(Dispatchers.class); private WsActionTester ws = new WsActionTester(new AddAction(new NotificationCenter( - new NotificationDispatcherMetadata[] {}, - new NotificationChannel[] {emailChannel, twitterChannel, defaultChannel}), + new NotificationDispatcherMetadata[]{}, + new NotificationChannel[]{emailChannel, twitterChannel, defaultChannel}), new NotificationUpdater(dbClient), dispatchers, dbClient, TestComponentFinder.from(db), userSession)); @Test @@ -207,21 +205,19 @@ public class AddActionTest { userSession.logIn(user).setSystemAdministrator(); when(dispatchers.getGlobalDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("User 'LOGIN 404' not found"); - - call(NOTIF_MY_NEW_ISSUES, null, null, "LOGIN 404"); + assertThatThrownBy(() -> call(NOTIF_MY_NEW_ISSUES, null, null, "LOGIN 404")) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("User 'LOGIN 404' not found"); } @Test - public void fail_if_login_provided_and_not_system_administrator() { + public void fail_if_login_provided_and_not_system_administrsator() { UserDto user = db.users().insertUser(); userSession.logIn(user).setNonSystemAdministrator(); when(dispatchers.getGlobalDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); - expectedException.expect(ForbiddenException.class); - - call(NOTIF_MY_NEW_ISSUES, null, null, user.getLogin()); + assertThatThrownBy(() -> call(NOTIF_MY_NEW_ISSUES, null, null, user.getLogin())) + .isInstanceOf(ForbiddenException.class); } @Test @@ -231,17 +227,15 @@ public class AddActionTest { when(dispatchers.getGlobalDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); call(NOTIF_MY_NEW_ISSUES, null, null, null); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Notification already added"); - - call(NOTIF_MY_NEW_ISSUES, null, null, null); + assertThatThrownBy(() -> call(NOTIF_MY_NEW_ISSUES, null, null, null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Notification already added"); } @Test public void fail_when_unknown_channel() { - expectedException.expect(IllegalArgumentException.class); - - call(NOTIF_MY_NEW_ISSUES, "Channel42", null, null); + assertThatThrownBy(() -> call(NOTIF_MY_NEW_ISSUES, "Channel42", null, null)) + .isInstanceOf(IllegalArgumentException.class); } @Test @@ -250,10 +244,9 @@ public class AddActionTest { userSession.logIn(user); when(dispatchers.getGlobalDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Value of parameter 'type' (Dispatcher42) must be one of: [Dispatcher1]"); - - call("Dispatcher42", null, null, null); + assertThatThrownBy(() -> call("Dispatcher42", null, null, null)) + .isInstanceOf(BadRequestException.class) + .hasMessageContaining("Value of parameter 'type' (Dispatcher42) must be one of: [Dispatcher1]"); } @Test @@ -263,10 +256,9 @@ public class AddActionTest { when(dispatchers.getGlobalDispatchers()).thenReturn(asList(NOTIF_MY_NEW_ISSUES, NOTIF_NEW_ISSUES)); when(dispatchers.getProjectDispatchers()).thenReturn(asList(NOTIF_MY_NEW_ISSUES, NOTIF_NEW_ISSUES)); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Value of parameter 'type' (Dispatcher42) must be one of: [Dispatcher1, Dispatcher2]"); - - call("Dispatcher42", null, project.getKey(), null); + assertThatThrownBy(() -> call("Dispatcher42", null, project.getKey(), null)) + .isInstanceOf(BadRequestException.class) + .hasMessageContaining("Value of parameter 'type' (Dispatcher42) must be one of: [Dispatcher1, Dispatcher2]"); } @Test @@ -277,17 +269,15 @@ public class AddActionTest { when(dispatchers.getGlobalDispatchers()).thenReturn(asList(NOTIF_MY_NEW_ISSUES, NOTIF_NEW_ISSUES)); when(dispatchers.getProjectDispatchers()).thenReturn(asList(NOTIF_MY_NEW_ISSUES, NOTIF_NEW_ISSUES)); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Value of parameter 'type' (Dispatcher42) must be one of: [Dispatcher1, Dispatcher2]"); - - call("Dispatcher42", null, project.getKey(), null); + assertThatThrownBy(() -> call("Dispatcher42", null, project.getKey(), null)) + .isInstanceOf(BadRequestException.class) + .hasMessageContaining("Value of parameter 'type' (Dispatcher42) must be one of: [Dispatcher1, Dispatcher2]"); } @Test public void fail_when_no_dispatcher() { - expectedException.expect(IllegalArgumentException.class); - - ws.newRequest().execute(); + assertThatThrownBy(() -> ws.newRequest().execute()) + .isInstanceOf(IllegalArgumentException.class); } @Test @@ -297,9 +287,8 @@ public class AddActionTest { when(dispatchers.getGlobalDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); when(dispatchers.getProjectDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); - expectedException.expect(NotFoundException.class); - - call(NOTIF_MY_NEW_ISSUES, null, "Project-42", null); + assertThatThrownBy(() -> call(NOTIF_MY_NEW_ISSUES, null, "Project-42", null)) + .isInstanceOf(NotFoundException.class); } @Test @@ -310,10 +299,9 @@ public class AddActionTest { when(dispatchers.getGlobalDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); when(dispatchers.getProjectDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Component 'VIEW_1' must be a project"); - - call(NOTIF_MY_NEW_ISSUES, null, "VIEW_1", null); + assertThatThrownBy(() -> call(NOTIF_MY_NEW_ISSUES, null, "VIEW_1", null)) + .isInstanceOf(BadRequestException.class) + .hasMessageContaining("Component 'VIEW_1' must be a project"); } @Test @@ -321,9 +309,8 @@ public class AddActionTest { userSession.anonymous(); when(dispatchers.getGlobalDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); - expectedException.expect(UnauthorizedException.class); - - call(NOTIF_MY_NEW_ISSUES, null, null, null); + assertThatThrownBy(() -> call(NOTIF_MY_NEW_ISSUES, null, null, null)) + .isInstanceOf(UnauthorizedException.class); } @Test @@ -334,10 +321,9 @@ public class AddActionTest { ComponentDto project = db.components().insertPublicProject(); ComponentDto branch = db.components().insertProjectBranch(project); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(format("Component key '%s' not found", branch.getDbKey())); - - call(NOTIF_MY_NEW_ISSUES, null, branch.getDbKey(), null); + assertThatThrownBy(() -> call(NOTIF_MY_NEW_ISSUES, null, branch.getDbKey(), null)) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining(format("Component key '%s' not found", branch.getDbKey())); } @Test @@ -347,9 +333,8 @@ public class AddActionTest { when(dispatchers.getGlobalDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); when(dispatchers.getProjectDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); - expectedException.expect(ForbiddenException.class); - - call(NOTIF_MY_NEW_ISSUES, null, project.getDbKey(), userSession.getLogin()); + assertThatThrownBy(() -> call(NOTIF_MY_NEW_ISSUES, null, project.getDbKey(), userSession.getLogin())) + .isInstanceOf(ForbiddenException.class); } private TestResponse call(String type, @Nullable String channel, @Nullable String project, @Nullable String login) { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ApplyPermissionTemplateQueryTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ApplyPermissionTemplateQueryTest.java index 94549e6b1be..add687c61d2 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ApplyPermissionTemplateQueryTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ApplyPermissionTemplateQueryTest.java @@ -20,19 +20,16 @@ package org.sonar.server.permission; import java.util.Collections; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.server.exceptions.BadRequestException; import static com.google.common.collect.Lists.newArrayList; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.server.permission.ApplyPermissionTemplateQuery.create; public class ApplyPermissionTemplateQueryTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void should_populate_with_params() { @@ -44,17 +41,15 @@ public class ApplyPermissionTemplateQueryTest { @Test public void should_invalidate_query_with_empty_name() { - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Permission template is mandatory"); - - create("", newArrayList("1", "2", "3")); + assertThatThrownBy(() -> create("", newArrayList("1", "2", "3"))) + .isInstanceOf(BadRequestException.class) + .hasMessage("Permission template is mandatory"); } @Test public void should_invalidate_query_with_no_components() { - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("No project provided. Please provide at least one project."); - - create("my_template_key", Collections.emptyList()); + assertThatThrownBy(() -> create("my_template_key", Collections.emptyList())) + .isInstanceOf(BadRequestException.class) + .hasMessage("No project provided. Please provide at least one project."); } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/GroupPermissionChangerTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/GroupPermissionChangerTest.java index 6f85ad3d499..575e68a74a4 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/GroupPermissionChangerTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/GroupPermissionChangerTest.java @@ -23,7 +23,6 @@ import org.apache.commons.lang.StringUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.resources.Qualifiers; import org.sonar.api.resources.ResourceTypes; import org.sonar.api.utils.System2; @@ -41,6 +40,7 @@ import org.sonar.db.user.UserDto; import org.sonar.server.exceptions.BadRequestException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.fail; import static org.sonar.db.permission.GlobalPermission.ADMINISTER; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_GATES; @@ -50,8 +50,6 @@ public class GroupPermissionChangerTest { @Rule public DbTester db = DbTester.create(System2.INSTANCE); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private final ResourceTypes resourceTypes = new ResourceTypesRule().setRootQualifiers(Qualifiers.PROJECT); private final PermissionService permissionService = new PermissionServiceImpl(resourceTypes); @@ -204,10 +202,9 @@ public class GroupPermissionChangerTest { public void apply_fails_with_BadRequestException_when_adding_permission_ADMIN_to_group_AnyOne_on_a_public_project() { GroupUuidOrAnyone groupUuid = GroupUuidOrAnyone.forAnyone(); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("It is not possible to add the 'admin' permission to group 'Anyone'"); - - apply(new GroupPermissionChange(PermissionChange.Operation.ADD, UserRole.ADMIN, publicProject, groupUuid, permissionService)); + assertThatThrownBy(() -> apply(new GroupPermissionChange(PermissionChange.Operation.ADD, UserRole.ADMIN, publicProject, groupUuid, permissionService))) + .isInstanceOf(BadRequestException.class) + .hasMessage("It is not possible to add the 'admin' permission to group 'Anyone'."); } @Test @@ -232,20 +229,18 @@ public class GroupPermissionChangerTest { public void apply_fails_with_BadRequestException_when_removing_USER_permission_from_group_AnyOne_on_a_public_project() { GroupUuidOrAnyone groupUuid = GroupUuidOrAnyone.forAnyone(); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Permission user can't be removed from a public component"); - - apply(new GroupPermissionChange(PermissionChange.Operation.REMOVE, UserRole.USER, publicProject, groupUuid, permissionService)); + assertThatThrownBy(() -> apply(new GroupPermissionChange(PermissionChange.Operation.REMOVE, UserRole.USER, publicProject, groupUuid, permissionService))) + .isInstanceOf(BadRequestException.class) + .hasMessage("Permission user can't be removed from a public component"); } @Test public void apply_fails_with_BadRequestException_when_removing_CODEVIEWER_permission_from_group_AnyOne_on_a_public_project() { GroupUuidOrAnyone groupUuid = GroupUuidOrAnyone.forAnyone(); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Permission codeviewer can't be removed from a public component"); - - apply(new GroupPermissionChange(PermissionChange.Operation.REMOVE, UserRole.CODEVIEWER, publicProject, groupUuid, permissionService)); + assertThatThrownBy(() -> apply(new GroupPermissionChange(PermissionChange.Operation.REMOVE, UserRole.CODEVIEWER, publicProject, groupUuid, permissionService))) + .isInstanceOf(BadRequestException.class) + .hasMessage("Permission codeviewer can't be removed from a public component"); } @Test @@ -276,20 +271,18 @@ public class GroupPermissionChangerTest { public void apply_fails_with_BadRequestException_when_removing_USER_permission_from_a_group_on_a_public_project() { GroupUuidOrAnyone groupUuid = GroupUuidOrAnyone.from(group); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Permission user can't be removed from a public component"); - - apply(new GroupPermissionChange(PermissionChange.Operation.REMOVE, UserRole.USER, publicProject, groupUuid, permissionService)); + assertThatThrownBy(() -> apply(new GroupPermissionChange(PermissionChange.Operation.REMOVE, UserRole.USER, publicProject, groupUuid, permissionService))) + .isInstanceOf(BadRequestException.class) + .hasMessage("Permission user can't be removed from a public component"); } @Test public void apply_fails_with_BadRequestException_when_removing_CODEVIEWER_permission_from_a_group_on_a_public_project() { GroupUuidOrAnyone groupUuid = GroupUuidOrAnyone.from(group); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Permission codeviewer can't be removed from a public component"); - - apply(new GroupPermissionChange(PermissionChange.Operation.REMOVE, UserRole.CODEVIEWER, publicProject, groupUuid, permissionService)); + assertThatThrownBy(() -> apply(new GroupPermissionChange(PermissionChange.Operation.REMOVE, UserRole.CODEVIEWER, publicProject, groupUuid, permissionService))) + .isInstanceOf(BadRequestException.class) + .hasMessage("Permission codeviewer can't be removed from a public component"); } @Test @@ -404,10 +397,9 @@ public class GroupPermissionChangerTest { GroupUuidOrAnyone groupUuid = GroupUuidOrAnyone.from(group); db.users().insertPermissionOnGroup(group, ADMINISTER); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Last group with permission 'admin'. Permission cannot be removed."); - - underTest.apply(db.getSession(), new GroupPermissionChange(PermissionChange.Operation.REMOVE, ADMINISTER.getKey(), null, groupUuid, permissionService)); + assertThatThrownBy(() -> underTest.apply(db.getSession(), new GroupPermissionChange(PermissionChange.Operation.REMOVE, ADMINISTER.getKey(), null, groupUuid, permissionService))) + .isInstanceOf(BadRequestException.class) + .hasMessage("Last group with permission 'admin'. Permission cannot be removed."); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/PermissionTemplateServiceTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/PermissionTemplateServiceTest.java index b8e68cfd14d..764ea993e85 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/PermissionTemplateServiceTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/PermissionTemplateServiceTest.java @@ -25,7 +25,6 @@ import java.util.stream.Stream; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.web.UserRole; import org.sonar.core.util.SequenceUuidFactory; import org.sonar.db.DbSession; @@ -53,8 +52,6 @@ import static org.sonar.db.permission.GlobalPermission.SCAN; public class PermissionTemplateServiceTest { - @Rule - public ExpectedException throwable = ExpectedException.none(); @Rule public DbTester dbTester = DbTester.create(); diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/UserPermissionChangerTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/UserPermissionChangerTest.java index b0822e0a7d8..2b462b3fceb 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/UserPermissionChangerTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/UserPermissionChangerTest.java @@ -23,7 +23,6 @@ import org.apache.commons.lang.StringUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.resources.Qualifiers; import org.sonar.api.resources.ResourceTypes; import org.sonar.api.utils.System2; @@ -38,6 +37,7 @@ import org.sonar.db.user.UserIdDto; import org.sonar.server.exceptions.BadRequestException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.web.UserRole.ADMIN; import static org.sonar.api.web.UserRole.CODEVIEWER; import static org.sonar.api.web.UserRole.ISSUE_ADMIN; @@ -55,8 +55,6 @@ public class UserPermissionChangerTest { @Rule public DbTester db = DbTester.create(System2.INSTANCE); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private final ResourceTypes resourceTypes = new ResourceTypesRule().setRootQualifiers(Qualifiers.PROJECT); private final PermissionService permissionService = new PermissionServiceImpl(resourceTypes); @@ -150,20 +148,18 @@ public class UserPermissionChangerTest { public void apply_fails_with_BadRequestException_when_removing_permission_USER_from_a_public_project() { UserPermissionChange change = new UserPermissionChange(REMOVE, USER, publicProject, UserIdDto.from(user1), permissionService); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Permission user can't be removed from a public component"); - - apply(change); + assertThatThrownBy(() -> apply(change)) + .isInstanceOf(BadRequestException.class) + .hasMessage("Permission user can't be removed from a public component"); } @Test public void apply_fails_with_BadRequestException_when_removing_permission_CODEVIEWER_from_a_public_project() { UserPermissionChange change = new UserPermissionChange(REMOVE, CODEVIEWER, publicProject, UserIdDto.from(user1), permissionService); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Permission codeviewer can't be removed from a public component"); - - apply(change); + assertThatThrownBy(() -> apply(change)) + .isInstanceOf(BadRequestException.class) + .hasMessage("Permission codeviewer can't be removed from a public component"); } @Test @@ -252,20 +248,22 @@ public class UserPermissionChangerTest { @Test public void fail_to_add_global_permission_on_project() { - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Invalid project permission 'gateadmin'. Valid values are [" + StringUtils.join(permissionService.getAllProjectPermissions(), ", ") + "]"); - - UserPermissionChange change = new UserPermissionChange(ADD, QUALITY_GATE_ADMIN, privateProject, UserIdDto.from(user1), permissionService); - apply(change); + assertThatThrownBy(() -> { + UserPermissionChange change = new UserPermissionChange(ADD, QUALITY_GATE_ADMIN, privateProject, UserIdDto.from(user1), permissionService); + apply(change); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Invalid project permission 'gateadmin'. Valid values are [" + StringUtils.join(permissionService.getAllProjectPermissions(), ", ") + "]"); } @Test public void fail_to_add_project_permission() { - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Invalid global permission 'issueadmin'. Valid values are [admin, gateadmin, profileadmin, provisioning, scan]"); - - UserPermissionChange change = new UserPermissionChange(ADD, ISSUE_ADMIN, null, UserIdDto.from(user1), permissionService); - apply(change); + assertThatThrownBy(() -> { + UserPermissionChange change = new UserPermissionChange(ADD, ISSUE_ADMIN, null, UserIdDto.from(user1), permissionService); + apply(change); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Invalid global permission 'issueadmin'. Valid values are [admin, gateadmin, profileadmin, provisioning, scan]"); } @Test @@ -320,11 +318,12 @@ public class UserPermissionChangerTest { public void fail_to_remove_admin_global_permission_if_no_more_admins() { db.users().insertPermissionOnUser(user1, SYSTEM_ADMIN); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Last user with permission 'admin'. Permission cannot be removed."); - - UserPermissionChange change = new UserPermissionChange(REMOVE, SYSTEM_ADMIN, null, UserIdDto.from(user1), permissionService); - underTest.apply(db.getSession(), change); + assertThatThrownBy(() -> { + UserPermissionChange change = new UserPermissionChange(REMOVE, SYSTEM_ADMIN, null, UserIdDto.from(user1), permissionService); + underTest.apply(db.getSession(), change); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Last user with permission 'admin'. Permission cannot be removed."); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/AddGroupActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/AddGroupActionTest.java index e3e42c9ea4f..6d8a920bc5c 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/AddGroupActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/AddGroupActionTest.java @@ -38,6 +38,7 @@ import org.sonar.server.permission.PermissionServiceImpl; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.api.web.UserRole.CODEVIEWER; @@ -175,12 +176,14 @@ public class AddGroupActionTest extends BasePermissionWsTest { GroupDto group = db.users().insertGroup("sonar-administrators"); loginAsAdmin(); - expectedException.expect(NotFoundException.class); - newRequest() - .setParam(PARAM_GROUP_NAME, group.getName()) - .setParam(PARAM_PROJECT_ID, "not-found") - .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_GROUP_NAME, group.getName()) + .setParam(PARAM_PROJECT_ID, "not-found") + .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) + .execute(); + }) + .isInstanceOf(NotFoundException.class); } @Test @@ -219,14 +222,15 @@ public class AddGroupActionTest extends BasePermissionWsTest { GroupDto group = db.users().insertGroup("sonar-administrators"); loginAsAdmin(); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Component '" + file.getDbKey() + "' (id: " + file.uuid() + ") must be a project or a view."); - - newRequest() - .setParam(PARAM_GROUP_NAME, group.getName()) - .setParam(PARAM_PROJECT_ID, file.uuid()) - .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_GROUP_NAME, group.getName()) + .setParam(PARAM_PROJECT_ID, file.uuid()) + .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) + .execute(); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Component '" + file.getDbKey() + "' (id: " + file.uuid() + ") must be a project or a view."); } @Test @@ -234,9 +238,10 @@ public class AddGroupActionTest extends BasePermissionWsTest { GroupDto group = db.users().insertGroup("sonar-administrators"); loginAsAdmin(); - expectedException.expect(BadRequestException.class); - - executeRequest(group, UserRole.ISSUE_ADMIN); + assertThatThrownBy(() -> { + executeRequest(group, UserRole.ISSUE_ADMIN); + }) + .isInstanceOf(BadRequestException.class); } @Test @@ -246,38 +251,41 @@ public class AddGroupActionTest extends BasePermissionWsTest { ComponentDto file = db.components().insertComponent(ComponentTesting.newFileDto(project, null, "file-uuid")); loginAsAdmin(); - expectedException.expect(BadRequestException.class); - - newRequest() - .setParam(PARAM_GROUP_NAME, group.getName()) - .setParam(PARAM_PROJECT_ID, file.uuid()) - .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_GROUP_NAME, group.getName()) + .setParam(PARAM_PROJECT_ID, file.uuid()) + .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) + .execute(); + }) + .isInstanceOf(BadRequestException.class); } @Test public void fail_when_get_request() { loginAsAdmin(); - expectedException.expect(ServerException.class); - - newRequest() - .setMethod("GET") - .setParam(PARAM_GROUP_NAME, "sonar-administrators") - .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setMethod("GET") + .setParam(PARAM_GROUP_NAME, "sonar-administrators") + .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) + .execute(); + }) + .isInstanceOf(ServerException.class); } @Test public void fail_when_group_name_and_group_id_are_missing() { loginAsAdmin(); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Group name or group id must be provided"); - - newRequest() - .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) + .execute(); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Group name or group id must be provided"); } @Test @@ -285,11 +293,12 @@ public class AddGroupActionTest extends BasePermissionWsTest { GroupDto group = db.users().insertGroup("sonar-administrators"); loginAsAdmin(); - expectedException.expect(IllegalArgumentException.class); - - newRequest() - .setParam(PARAM_GROUP_NAME, group.getName()) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_GROUP_NAME, group.getName()) + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class); } @Test @@ -297,11 +306,12 @@ public class AddGroupActionTest extends BasePermissionWsTest { GroupDto group = db.users().insertGroup(); loginAsAdmin(); - expectedException.expect(IllegalArgumentException.class); - - newRequest() - .setParam(PARAM_GROUP_NAME, group.getName()) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_GROUP_NAME, group.getName()) + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class); } @Test @@ -310,15 +320,16 @@ public class AddGroupActionTest extends BasePermissionWsTest { ComponentDto project = db.components().insertPrivateProject(); loginAsAdmin(); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Project id or project key can be provided, not both."); - - newRequest() - .setParam(PARAM_GROUP_NAME, group.getName()) - .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) - .setParam(PARAM_PROJECT_ID, project.uuid()) - .setParam(PARAM_PROJECT_KEY, project.getDbKey()) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_GROUP_NAME, group.getName()) + .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) + .setParam(PARAM_PROJECT_ID, project.uuid()) + .setParam(PARAM_PROJECT_KEY, project.getDbKey()) + .execute(); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Project id or project key can be provided, not both."); } @Test @@ -326,12 +337,13 @@ public class AddGroupActionTest extends BasePermissionWsTest { GroupDto group = db.users().insertGroup("sonar-administrators"); userSession.logIn().addPermission(SCAN); - expectedException.expect(ForbiddenException.class); - - newRequest() - .setParam(PARAM_GROUP_NAME, group.getName()) - .setParam(PARAM_PERMISSION, PROVISION_PROJECTS.getKey()) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_GROUP_NAME, group.getName()) + .setParam(PARAM_PERMISSION, PROVISION_PROJECTS.getKey()) + .execute(); + }) + .isInstanceOf(ForbiddenException.class); } @Test @@ -340,13 +352,14 @@ public class AddGroupActionTest extends BasePermissionWsTest { ComponentDto project = db.components().insertPrivateProject(); userSession.logIn(); - expectedException.expect(ForbiddenException.class); - - newRequest() - .setParam(PARAM_GROUP_NAME, group.getName()) - .setParam(PARAM_PERMISSION, PROVISION_PROJECTS.getKey()) - .setParam(PARAM_PROJECT_KEY, project.getDbKey()) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_GROUP_NAME, group.getName()) + .setParam(PARAM_PERMISSION, PROVISION_PROJECTS.getKey()) + .setParam(PARAM_PROJECT_KEY, project.getDbKey()) + .execute(); + }) + .isInstanceOf(ForbiddenException.class); } /** @@ -452,14 +465,15 @@ public class AddGroupActionTest extends BasePermissionWsTest { userSession.logIn().addProjectPermission(UserRole.ADMIN, project); ComponentDto branch = db.components().insertProjectBranch(project); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(format("Project key '%s' not found", branch.getDbKey())); - - newRequest() - .setParam(PARAM_PROJECT_KEY, branch.getDbKey()) - .setParam(PARAM_GROUP_NAME, group.getName()) - .setParam(PARAM_PERMISSION, ISSUE_ADMIN) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_PROJECT_KEY, branch.getDbKey()) + .setParam(PARAM_GROUP_NAME, group.getName()) + .setParam(PARAM_PERMISSION, ISSUE_ADMIN) + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage(format("Project key '%s' not found", branch.getDbKey())); } @Test @@ -469,14 +483,15 @@ public class AddGroupActionTest extends BasePermissionWsTest { userSession.logIn().addProjectPermission(UserRole.ADMIN, project); ComponentDto branch = db.components().insertProjectBranch(project); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(format("Project id '%s' not found", branch.uuid())); - - newRequest() - .setParam(PARAM_PROJECT_ID, branch.uuid()) - .setParam(PARAM_GROUP_NAME, group.getName()) - .setParam(PARAM_PERMISSION, ISSUE_ADMIN) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_PROJECT_ID, branch.uuid()) + .setParam(PARAM_GROUP_NAME, group.getName()) + .setParam(PARAM_PERMISSION, ISSUE_ADMIN) + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage(format("Project id '%s' not found", branch.uuid())); } private void executeRequest(GroupDto groupDto, String permission) { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/AddUserActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/AddUserActionTest.java index 848c1039516..12f1928e44c 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/AddUserActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/AddUserActionTest.java @@ -38,6 +38,7 @@ import org.sonar.server.permission.PermissionServiceImpl; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.sonar.api.web.UserRole.CODEVIEWER; import static org.sonar.api.web.UserRole.ISSUE_ADMIN; @@ -47,7 +48,6 @@ import static org.sonar.db.component.ComponentTesting.newDirectory; import static org.sonar.db.component.ComponentTesting.newFileDto; import static org.sonar.db.component.ComponentTesting.newModuleDto; import static org.sonar.db.component.ComponentTesting.newSubPortfolio; -import static org.sonar.db.component.ComponentTesting.newPortfolio; import static org.sonar.db.permission.GlobalPermission.ADMINISTER; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PERMISSION; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PROJECT_ID; @@ -133,13 +133,14 @@ public class AddUserActionTest extends BasePermissionWsTest { public void fail_when_project_uuid_is_unknown() { loginAsAdmin(); - expectedException.expect(NotFoundException.class); - - newRequest() - .setParam(PARAM_USER_LOGIN, user.getLogin()) - .setParam(PARAM_PROJECT_ID, "unknown-project-uuid") - .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_USER_LOGIN, user.getLogin()) + .setParam(PARAM_PROJECT_ID, "unknown-project-uuid") + .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) + .execute(); + }) + .isInstanceOf(NotFoundException.class); } @Test @@ -177,26 +178,28 @@ public class AddUserActionTest extends BasePermissionWsTest { private void failIfComponentIsNotAProjectOrView(ComponentDto file) { loginAsAdmin(); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Component '" + file.getDbKey() + "' (id: " + file.uuid() + ") must be a project or a view."); - - newRequest() - .setParam(PARAM_USER_LOGIN, user.getLogin()) - .setParam(PARAM_PROJECT_ID, file.uuid()) - .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_USER_LOGIN, user.getLogin()) + .setParam(PARAM_PROJECT_ID, file.uuid()) + .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) + .execute(); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Component '" + file.getDbKey() + "' (id: " + file.uuid() + ") must be a project or a view."); } @Test public void fail_when_project_permission_without_project() { loginAsAdmin(); - expectedException.expect(BadRequestException.class); - - newRequest() - .setParam(PARAM_USER_LOGIN, user.getLogin()) - .setParam(PARAM_PERMISSION, UserRole.ISSUE_ADMIN) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_USER_LOGIN, user.getLogin()) + .setParam(PARAM_PERMISSION, UserRole.ISSUE_ADMIN) + .execute(); + }) + .isInstanceOf(BadRequestException.class); } @Test @@ -205,48 +208,52 @@ public class AddUserActionTest extends BasePermissionWsTest { db.components().insertComponent(newFileDto(project, null, "file-uuid")); loginAsAdmin(); - expectedException.expect(BadRequestException.class); - - newRequest() - .setParam(PARAM_USER_LOGIN, user.getLogin()) - .setParam(PARAM_PROJECT_ID, "file-uuid") - .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_USER_LOGIN, user.getLogin()) + .setParam(PARAM_PROJECT_ID, "file-uuid") + .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) + .execute(); + }) + .isInstanceOf(BadRequestException.class); } @Test public void fail_when_get_request() { loginAsAdmin(); - expectedException.expect(ServerException.class); - - newRequest() - .setMethod("GET") - .setParam(PARAM_USER_LOGIN, "george.orwell") - .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setMethod("GET") + .setParam(PARAM_USER_LOGIN, "george.orwell") + .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) + .execute(); + }) + .isInstanceOf(ServerException.class); } @Test public void fail_when_user_login_is_missing() { loginAsAdmin(); - expectedException.expect(IllegalArgumentException.class); - - newRequest() - .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_when_permission_is_missing() { loginAsAdmin(); - expectedException.expect(NotFoundException.class); - - newRequest() - .setParam(PARAM_USER_LOGIN, "jrr.tolkien") - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_USER_LOGIN, "jrr.tolkien") + .execute(); + }) + .isInstanceOf(NotFoundException.class); } @Test @@ -254,27 +261,29 @@ public class AddUserActionTest extends BasePermissionWsTest { db.components().insertPrivateProject(); loginAsAdmin(); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Project id or project key can be provided, not both."); - - newRequest() - .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) - .setParam(PARAM_USER_LOGIN, user.getLogin()) - .setParam(PARAM_PROJECT_ID, "project-uuid") - .setParam(PARAM_PROJECT_KEY, "project-key") - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) + .setParam(PARAM_USER_LOGIN, user.getLogin()) + .setParam(PARAM_PROJECT_ID, "project-uuid") + .setParam(PARAM_PROJECT_KEY, "project-key") + .execute(); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Project id or project key can be provided, not both."); } @Test public void adding_global_permission_fails_if_not_system_administrator() { userSession.logIn(); - expectedException.expect(ForbiddenException.class); - - newRequest() - .setParam(PARAM_USER_LOGIN, user.getLogin()) - .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_USER_LOGIN, user.getLogin()) + .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) + .execute(); + }) + .isInstanceOf(ForbiddenException.class); } @Test @@ -282,13 +291,14 @@ public class AddUserActionTest extends BasePermissionWsTest { ComponentDto project = db.components().insertPrivateProject(); userSession.logIn(); - expectedException.expect(ForbiddenException.class); - - newRequest() - .setParam(PARAM_USER_LOGIN, user.getLogin()) - .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) - .setParam(PARAM_PROJECT_KEY, project.getDbKey()) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_USER_LOGIN, user.getLogin()) + .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) + .setParam(PARAM_PROJECT_KEY, project.getDbKey()) + .execute(); + }) + .isInstanceOf(ForbiddenException.class); } /** @@ -343,14 +353,15 @@ public class AddUserActionTest extends BasePermissionWsTest { userSession.logIn().addProjectPermission(UserRole.ADMIN, project); ComponentDto branch = db.components().insertProjectBranch(project); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(format("Project key '%s' not found", branch.getDbKey())); - - newRequest() - .setParam(PARAM_PROJECT_KEY, branch.getDbKey()) - .setParam(PARAM_USER_LOGIN, user.getLogin()) - .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_PROJECT_KEY, branch.getDbKey()) + .setParam(PARAM_USER_LOGIN, user.getLogin()) + .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage(format("Project key '%s' not found", branch.getDbKey())); } @Test @@ -359,13 +370,14 @@ public class AddUserActionTest extends BasePermissionWsTest { userSession.logIn().addProjectPermission(UserRole.ADMIN, project); ComponentDto branch = db.components().insertProjectBranch(project); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(format("Project id '%s' not found", branch.uuid())); - - newRequest() - .setParam(PARAM_PROJECT_ID, branch.uuid()) - .setParam(PARAM_USER_LOGIN, user.getLogin()) - .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_PROJECT_ID, branch.uuid()) + .setParam(PARAM_USER_LOGIN, user.getLogin()) + .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage(format("Project id '%s' not found", branch.uuid())); } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/BasePermissionWsTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/BasePermissionWsTest.java index 89114bd12d4..2061beea433 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/BasePermissionWsTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/BasePermissionWsTest.java @@ -21,7 +21,6 @@ package org.sonar.server.permission.ws; import org.junit.Before; import org.junit.Rule; -import org.junit.rules.ExpectedException; import org.sonar.api.config.Configuration; import org.sonar.api.impl.utils.AlwaysIncreasingSystem2; import org.sonar.api.resources.Qualifiers; @@ -56,8 +55,6 @@ public abstract class BasePermissionWsTest { @Rule public EsTester es = EsTester.createCustom(new FooIndexDefinition()); - @Rule - public ExpectedException expectedException = ExpectedException.none(); protected UserSessionRule userSession = UserSessionRule.standalone(); protected WsActionTester wsTester; diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/GroupsActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/GroupsActionTest.java index 8ae37ef6a59..bc5475c6f8b 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/GroupsActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/GroupsActionTest.java @@ -39,6 +39,7 @@ import org.sonar.server.permission.PermissionServiceImpl; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.api.server.ws.WebService.Param.PAGE; import static org.sonar.api.server.ws.WebService.Param.PAGE_SIZE; @@ -47,7 +48,6 @@ import static org.sonar.api.web.UserRole.ADMIN; import static org.sonar.api.web.UserRole.ISSUE_ADMIN; import static org.sonar.core.permission.GlobalPermissions.SCAN_EXECUTION; import static org.sonar.db.component.ComponentTesting.newPrivateProjectDto; -import static org.sonar.db.component.ComponentTesting.newPortfolio; import static org.sonar.db.permission.GlobalPermission.ADMINISTER; import static org.sonar.db.permission.GlobalPermission.SCAN; import static org.sonar.test.JsonAssert.assertJson; @@ -276,36 +276,40 @@ public class GroupsActionTest extends BasePermissionWsTest { @Test public void fail_if_not_logged_in() { - expectedException.expect(UnauthorizedException.class); - userSession.anonymous(); - - newRequest() - .setParam(PARAM_PERMISSION, SCAN.getKey()) - .execute(); + assertThatThrownBy(() -> { + userSession.anonymous(); + + newRequest() + .setParam(PARAM_PERMISSION, SCAN.getKey()) + .execute(); + }) + .isInstanceOf(UnauthorizedException.class); } @Test public void fail_if_insufficient_privileges() { - expectedException.expect(ForbiddenException.class); - - userSession.logIn("login"); - newRequest() - .setParam(PARAM_PERMISSION, SCAN.getKey()) - .execute(); + assertThatThrownBy(() -> { + userSession.logIn("login"); + newRequest() + .setParam(PARAM_PERMISSION, SCAN.getKey()) + .execute(); + }) + .isInstanceOf(ForbiddenException.class); } @Test public void fail_if_project_uuid_and_project_key_are_provided() { ComponentDto project = db.components().insertPrivateProject(); - expectedException.expect(BadRequestException.class); - - loginAsAdmin(); - newRequest() - .setParam(PARAM_PERMISSION, SCAN_EXECUTION) - .setParam(PARAM_PROJECT_ID, project.uuid()) - .setParam(PARAM_PROJECT_KEY, project.getKey()) - .execute(); + assertThatThrownBy(() -> { + loginAsAdmin(); + newRequest() + .setParam(PARAM_PERMISSION, SCAN_EXECUTION) + .setParam(PARAM_PROJECT_ID, project.uuid()) + .setParam(PARAM_PROJECT_KEY, project.getKey()) + .execute(); + }) + .isInstanceOf(BadRequestException.class); } @Test @@ -316,13 +320,14 @@ public class GroupsActionTest extends BasePermissionWsTest { db.users().insertProjectPermissionOnGroup(group, ISSUE_ADMIN, project); loginAsAdmin(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(format("Project id '%s' not found", branch.uuid())); - - newRequest() - .setParam(PARAM_PERMISSION, ISSUE_ADMIN) - .setParam(PARAM_PROJECT_ID, branch.uuid()) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_PERMISSION, ISSUE_ADMIN) + .setParam(PARAM_PROJECT_ID, branch.uuid()) + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage(format("Project id '%s' not found", branch.uuid())); } @Test @@ -333,13 +338,14 @@ public class GroupsActionTest extends BasePermissionWsTest { db.users().insertProjectPermissionOnGroup(group, ISSUE_ADMIN, project); loginAsAdmin(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(format("Project key '%s' not found", branch.getDbKey())); - - newRequest() - .setParam(PARAM_PERMISSION, ISSUE_ADMIN) - .setParam(PARAM_PROJECT_KEY, branch.getDbKey()) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_PERMISSION, ISSUE_ADMIN) + .setParam(PARAM_PROJECT_KEY, branch.getDbKey()) + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage(format("Project key '%s' not found", branch.getDbKey())); } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/RemoveGroupActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/RemoveGroupActionTest.java index 849ae91eb73..b3cc6cfd5f6 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/RemoveGroupActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/RemoveGroupActionTest.java @@ -39,6 +39,7 @@ import org.sonar.server.permission.PermissionServiceImpl; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.api.web.UserRole.ADMIN; import static org.sonar.api.web.UserRole.CODEVIEWER; @@ -174,34 +175,35 @@ public class RemoveGroupActionTest extends BasePermissionWsTest { + executeRequest(aGroup, SYSTEM_ADMIN); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Last group with permission 'admin'. Permission cannot be removed."); } @Test public void fail_when_project_does_not_exist() { loginAsAdmin(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Project id 'unknown-project-uuid' not found"); - - newRequest() - .setParam(PARAM_GROUP_NAME, aGroup.getName()) - .setParam(PARAM_PROJECT_ID, "unknown-project-uuid") - .setParam(PARAM_PERMISSION, ADMINISTER.getKey()) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_GROUP_NAME, aGroup.getName()) + .setParam(PARAM_PROJECT_ID, "unknown-project-uuid") + .setParam(PARAM_PERMISSION, ADMINISTER.getKey()) + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("Project id 'unknown-project-uuid' not found"); } @Test public void fail_when_project_project_permission_without_project() { loginAsAdmin(); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Invalid global permission 'issueadmin'. Valid values are [admin, gateadmin, profileadmin, provisioning, scan]"); - - executeRequest(aGroup, ISSUE_ADMIN); + assertThatThrownBy(() -> executeRequest(aGroup, ISSUE_ADMIN)) + .isInstanceOf(BadRequestException.class) + .hasMessage("Invalid global permission 'issueadmin'. Valid values are [admin, gateadmin, profileadmin, provisioning, scan]"); } @Test @@ -239,51 +241,55 @@ public class RemoveGroupActionTest extends BasePermissionWsTest { + newRequest() + .setParam(PARAM_GROUP_NAME, aGroup.getName()) + .setParam(PARAM_PROJECT_ID, file.uuid()) + .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) + .execute(); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Component '" + file.getDbKey() + "' (id: " + file.uuid() + ") must be a project or a view."); } @Test public void fail_when_group_name_is_missing() { loginAsAdmin(); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Group name or group id must be provided"); - - newRequest() - .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) + .execute(); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Group name or group id must be provided"); } @Test public void fail_when_permission_name_and_id_are_missing() { loginAsAdmin(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The 'permission' parameter is missing"); - - newRequest() - .setParam(PARAM_GROUP_NAME, aGroup.getName()) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_GROUP_NAME, aGroup.getName()) + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("The 'permission' parameter is missing"); } @Test public void fail_when_group_id_does_not_exist() { loginAsAdmin(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("No group with id '999999'"); - - newRequest() - .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) - .setParam(PARAM_GROUP_ID, "999999") - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) + .setParam(PARAM_GROUP_ID, "999999") + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("No group with id '999999'"); } @Test @@ -291,15 +297,16 @@ public class RemoveGroupActionTest extends BasePermissionWsTest { + newRequest() + .setParam(PARAM_GROUP_NAME, aGroup.getName()) + .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) + .setParam(PARAM_PROJECT_ID, project.uuid()) + .setParam(PARAM_PROJECT_KEY, project.getDbKey()) + .execute(); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Project id or project key can be provided, not both."); } private void executeRequest(GroupDto groupDto, String permission) { @@ -313,12 +320,13 @@ public class RemoveGroupActionTest extends BasePermissionWsTest { + newRequest() + .setParam(PARAM_GROUP_NAME, aGroup.getName()) + .setParam(PARAM_PERMISSION, PROVISIONING) + .execute(); + }) + .isInstanceOf(ForbiddenException.class); } @Test @@ -326,13 +334,14 @@ public class RemoveGroupActionTest extends BasePermissionWsTest { + newRequest() + .setParam(PARAM_GROUP_NAME, aGroup.getName()) + .setParam(PARAM_PERMISSION, PROVISIONING) + .setParam(PARAM_PROJECT_KEY, project.getDbKey()) + .execute(); + }) + .isInstanceOf(ForbiddenException.class); } /** @@ -378,14 +387,15 @@ public class RemoveGroupActionTest extends BasePermissionWsTest { + newRequest() + .setParam(PARAM_GROUP_NAME, "anyone") + .setParam(PARAM_PROJECT_ID, project.uuid()) + .setParam(PARAM_PERMISSION, USER) + .execute(); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Permission user can't be removed from a public component"); } @Test @@ -393,14 +403,15 @@ public class RemoveGroupActionTest extends BasePermissionWsTest { + newRequest() + .setParam(PARAM_GROUP_NAME, "anyone") + .setParam(PARAM_PROJECT_ID, project.uuid()) + .setParam(PARAM_PERMISSION, CODEVIEWER) + .execute(); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Permission codeviewer can't be removed from a public component"); } @Test @@ -409,14 +420,15 @@ public class RemoveGroupActionTest extends BasePermissionWsTest { + newRequest() + .setParam(PARAM_GROUP_NAME, group.getName()) + .setParam(PARAM_PROJECT_ID, project.uuid()) + .setParam(PARAM_PERMISSION, USER) + .execute(); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Permission user can't be removed from a public component"); } @Test @@ -425,14 +437,15 @@ public class RemoveGroupActionTest extends BasePermissionWsTest { + newRequest() + .setParam(PARAM_GROUP_NAME, group.getName()) + .setParam(PARAM_PROJECT_ID, project.uuid()) + .setParam(PARAM_PERMISSION, CODEVIEWER) + .execute(); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Permission codeviewer can't be removed from a public component"); } @Test @@ -442,14 +455,15 @@ public class RemoveGroupActionTest extends BasePermissionWsTest { + newRequest() + .setParam(PARAM_PROJECT_KEY, branch.getDbKey()) + .setParam(PARAM_GROUP_NAME, group.getName()) + .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage(format("Project key '%s' not found", branch.getDbKey())); } @Test @@ -459,14 +473,15 @@ public class RemoveGroupActionTest extends BasePermissionWsTest { + newRequest() + .setParam(PARAM_PROJECT_ID, branch.uuid()) + .setParam(PARAM_GROUP_NAME, group.getName()) + .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage(format("Project id '%s' not found", branch.uuid())); } private void unsafeInsertProjectPermissionOnAnyone(String perm, ComponentDto project) { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/RemoveUserActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/RemoveUserActionTest.java index 6d5ee8af51a..05583a7a3ea 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/RemoveUserActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/RemoveUserActionTest.java @@ -130,13 +130,14 @@ public class RemoveUserActionTest extends BasePermissionWsTest db.users().insertPermissionOnUser(user, ADMINISTER); loginAsAdmin(); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Last user with permission 'admin'. Permission cannot be removed."); - - newRequest() - .setParam(PARAM_USER_LOGIN, user.getLogin()) - .setParam(PARAM_PERMISSION, ADMIN) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_USER_LOGIN, user.getLogin()) + .setParam(PARAM_PERMISSION, ADMIN) + .execute(); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Last user with permission 'admin'. Permission cannot be removed."); } @Test @@ -191,25 +192,27 @@ public class RemoveUserActionTest extends BasePermissionWsTest public void fail_when_project_does_not_exist() { loginAsAdmin(); - expectedException.expect(NotFoundException.class); - - newRequest() - .setParam(PARAM_USER_LOGIN, user.getLogin()) - .setParam(PARAM_PROJECT_ID, "unknown-project-uuid") - .setParam(PARAM_PERMISSION, ISSUE_ADMIN) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_USER_LOGIN, user.getLogin()) + .setParam(PARAM_PROJECT_ID, "unknown-project-uuid") + .setParam(PARAM_PERMISSION, ISSUE_ADMIN) + .execute(); + }) + .isInstanceOf(NotFoundException.class); } @Test public void fail_when_project_permission_without_permission() { loginAsAdmin(); - expectedException.expect(BadRequestException.class); - - newRequest() - .setParam(PARAM_USER_LOGIN, user.getLogin()) - .setParam(PARAM_PERMISSION, ISSUE_ADMIN) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_USER_LOGIN, user.getLogin()) + .setParam(PARAM_PERMISSION, ISSUE_ADMIN) + .execute(); + }) + .isInstanceOf(BadRequestException.class); } @Test @@ -247,49 +250,53 @@ public class RemoveUserActionTest extends BasePermissionWsTest private void failIfComponentIsNotAProjectOrView(ComponentDto file) { loginAsAdmin(); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Component '" + file.getDbKey() + "' (id: " + file.uuid() + ") must be a project or a view."); - - newRequest() - .setParam(PARAM_USER_LOGIN, user.getLogin()) - .setParam(PARAM_PROJECT_ID, file.uuid()) - .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_USER_LOGIN, user.getLogin()) + .setParam(PARAM_PROJECT_ID, file.uuid()) + .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) + .execute(); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Component '" + file.getDbKey() + "' (id: " + file.uuid() + ") must be a project or a view."); } @Test public void fail_when_get_request() { loginAsAdmin(); - expectedException.expect(ServerException.class); - - newRequest() - .setMethod("GET") - .setParam(PARAM_USER_LOGIN, "george.orwell") - .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setMethod("GET") + .setParam(PARAM_USER_LOGIN, "george.orwell") + .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) + .execute(); + }) + .isInstanceOf(ServerException.class); } @Test public void fail_when_user_login_is_missing() { loginAsAdmin(); - expectedException.expect(IllegalArgumentException.class); - - newRequest() - .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_when_permission_is_missing() { loginAsAdmin(); - expectedException.expect(IllegalArgumentException.class); - - newRequest() - .setParam(PARAM_USER_LOGIN, user.getLogin()) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_USER_LOGIN, user.getLogin()) + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class); } @Test @@ -297,27 +304,29 @@ public class RemoveUserActionTest extends BasePermissionWsTest ComponentDto project = db.components().insertPrivateProject(); loginAsAdmin(); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Project id or project key can be provided, not both."); - - newRequest() - .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) - .setParam(PARAM_USER_LOGIN, user.getLogin()) - .setParam(PARAM_PROJECT_ID, project.uuid()) - .setParam(PARAM_PROJECT_KEY, project.getDbKey()) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) + .setParam(PARAM_USER_LOGIN, user.getLogin()) + .setParam(PARAM_PROJECT_ID, project.uuid()) + .setParam(PARAM_PROJECT_KEY, project.getDbKey()) + .execute(); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Project id or project key can be provided, not both."); } @Test public void removing_global_permission_fails_if_not_system_administrator() { userSession.logIn(); - expectedException.expect(ForbiddenException.class); - - newRequest() - .setParam(PARAM_USER_LOGIN, user.getLogin()) - .setParam(PARAM_PERMISSION, PROVISIONING) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_USER_LOGIN, user.getLogin()) + .setParam(PARAM_PERMISSION, PROVISIONING) + .execute(); + }) + .isInstanceOf(ForbiddenException.class); } @Test @@ -325,13 +334,14 @@ public class RemoveUserActionTest extends BasePermissionWsTest ComponentDto project = db.components().insertPrivateProject(); userSession.logIn(); - expectedException.expect(ForbiddenException.class); - - newRequest() - .setParam(PARAM_USER_LOGIN, user.getLogin()) - .setParam(PARAM_PERMISSION, ISSUE_ADMIN) - .setParam(PARAM_PROJECT_KEY, project.getDbKey()) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_USER_LOGIN, user.getLogin()) + .setParam(PARAM_PERMISSION, ISSUE_ADMIN) + .setParam(PARAM_PROJECT_KEY, project.getDbKey()) + .execute(); + }) + .isInstanceOf(ForbiddenException.class); } /** @@ -358,14 +368,16 @@ public class RemoveUserActionTest extends BasePermissionWsTest ComponentDto project = db.components().insertPublicProject(); userSession.logIn().addProjectPermission(UserRole.ADMIN, project); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Permission user can't be removed from a public component"); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_USER_LOGIN, user.getLogin()) + .setParam(PARAM_PROJECT_ID, project.uuid()) + .setParam(PARAM_PERMISSION, USER) + .execute(); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Permission user can't be removed from a public component"); - newRequest() - .setParam(PARAM_USER_LOGIN, user.getLogin()) - .setParam(PARAM_PROJECT_ID, project.uuid()) - .setParam(PARAM_PERMISSION, USER) - .execute(); } @Test @@ -373,14 +385,15 @@ public class RemoveUserActionTest extends BasePermissionWsTest ComponentDto project = db.components().insertPublicProject(); userSession.logIn().addProjectPermission(UserRole.ADMIN, project); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Permission codeviewer can't be removed from a public component"); - - newRequest() - .setParam(PARAM_USER_LOGIN, user.getLogin()) - .setParam(PARAM_PROJECT_ID, project.uuid()) - .setParam(PARAM_PERMISSION, CODEVIEWER) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_USER_LOGIN, user.getLogin()) + .setParam(PARAM_PROJECT_ID, project.uuid()) + .setParam(PARAM_PERMISSION, CODEVIEWER) + .execute(); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Permission codeviewer can't be removed from a public component"); } @Test @@ -389,14 +402,15 @@ public class RemoveUserActionTest extends BasePermissionWsTest userSession.logIn().addProjectPermission(UserRole.ADMIN, project); ComponentDto branch = db.components().insertProjectBranch(project); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(format("Project key '%s' not found", branch.getDbKey())); - - newRequest() - .setParam(PARAM_PROJECT_KEY, branch.getDbKey()) - .setParam(PARAM_USER_LOGIN, user.getLogin()) - .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_PROJECT_KEY, branch.getDbKey()) + .setParam(PARAM_USER_LOGIN, user.getLogin()) + .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage(format("Project key '%s' not found", branch.getDbKey())); } @Test @@ -405,14 +419,15 @@ public class RemoveUserActionTest extends BasePermissionWsTest userSession.logIn().addProjectPermission(UserRole.ADMIN, project); ComponentDto branch = db.components().insertProjectBranch(project); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(format("Project id '%s' not found", branch.uuid())); - - newRequest() - .setParam(PARAM_PROJECT_ID, branch.uuid()) - .setParam(PARAM_USER_LOGIN, user.getLogin()) - .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_PROJECT_ID, branch.uuid()) + .setParam(PARAM_USER_LOGIN, user.getLogin()) + .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage(format("Project id '%s' not found", branch.uuid())); } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/UsersActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/UsersActionTest.java index 4f45a4efe6b..58b5332aed4 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/UsersActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/UsersActionTest.java @@ -40,6 +40,7 @@ import org.sonar.server.permission.RequestValidator; import static java.lang.String.format; import static org.apache.commons.lang.StringUtils.countMatches; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.server.ws.WebService.Param.PAGE; import static org.sonar.api.server.ws.WebService.Param.PAGE_SIZE; import static org.sonar.api.server.ws.WebService.Param.TEXT_QUERY; @@ -267,34 +268,37 @@ public class UsersActionTest extends BasePermissionWsTest { public void fail_if_project_permission_without_project() { loginAsAdmin(); - expectedException.expect(BadRequestException.class); - - newRequest() - .setParam(PARAM_PERMISSION, UserRole.ISSUE_ADMIN) - .setParam(Param.SELECTED, SelectionMode.ALL.value()) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_PERMISSION, UserRole.ISSUE_ADMIN) + .setParam(Param.SELECTED, SelectionMode.ALL.value()) + .execute(); + }) + .isInstanceOf(BadRequestException.class); } @Test public void fail_if_insufficient_privileges() { userSession.logIn("login"); - expectedException.expect(ForbiddenException.class); - - newRequest() - .setParam("permission", SYSTEM_ADMIN) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam("permission", SYSTEM_ADMIN) + .execute(); + }) + .isInstanceOf(ForbiddenException.class); } @Test public void fail_if_not_logged_in() { userSession.anonymous(); - expectedException.expect(UnauthorizedException.class); - - newRequest() - .setParam("permission", SYSTEM_ADMIN) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam("permission", SYSTEM_ADMIN) + .execute(); + }) + .isInstanceOf(UnauthorizedException.class); } @Test @@ -302,24 +306,24 @@ public class UsersActionTest extends BasePermissionWsTest { ComponentDto project = db.components().insertPrivateProject(); loginAsAdmin(); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Project id or project key can be provided, not both."); - - newRequest() - .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) - .setParam(PARAM_PROJECT_ID, project.uuid()) - .setParam(PARAM_PROJECT_KEY, project.getKey()) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) + .setParam(PARAM_PROJECT_ID, project.uuid()) + .setParam(PARAM_PROJECT_KEY, project.getKey()) + .execute(); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Project id or project key can be provided, not both."); } @Test public void fail_if_search_query_is_too_short() { loginAsAdmin(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("'q' length (2) is shorter than the minimum authorized (3)"); - - newRequest().setParam(TEXT_QUERY, "ab").execute(); + assertThatThrownBy(() -> newRequest().setParam(TEXT_QUERY, "ab").execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("'q' length (2) is shorter than the minimum authorized (3)"); } @Test @@ -330,14 +334,15 @@ public class UsersActionTest extends BasePermissionWsTest { db.users().insertProjectPermissionOnUser(user, ISSUE_ADMIN, project); userSession.logIn().addProjectPermission(UserRole.ADMIN, project); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(format("Project key '%s' not found", branch.getDbKey())); - - newRequest() - .setParam(PARAM_PROJECT_KEY, branch.getDbKey()) - .setParam(PARAM_USER_LOGIN, user.getLogin()) - .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_PROJECT_KEY, branch.getDbKey()) + .setParam(PARAM_USER_LOGIN, user.getLogin()) + .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage(format("Project key '%s' not found", branch.getDbKey())); } @Test @@ -348,14 +353,15 @@ public class UsersActionTest extends BasePermissionWsTest { db.users().insertProjectPermissionOnUser(user, ISSUE_ADMIN, project); userSession.logIn().addProjectPermission(UserRole.ADMIN, project); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(format("Project id '%s' not found", branch.uuid())); - - newRequest() - .setParam(PARAM_PROJECT_ID, branch.uuid()) - .setParam(PARAM_USER_LOGIN, user.getLogin()) - .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_PROJECT_ID, branch.uuid()) + .setParam(PARAM_USER_LOGIN, user.getLogin()) + .setParam(PARAM_PERMISSION, SYSTEM_ADMIN) + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage(format("Project id '%s' not found", branch.uuid())); } private void insertUsersHavingGlobalPermissions() { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/AddGroupToTemplateActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/AddGroupToTemplateActionTest.java index 08f2d1a911b..223ca9444e7 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/AddGroupToTemplateActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/AddGroupToTemplateActionTest.java @@ -43,6 +43,7 @@ import org.sonar.server.permission.ws.WsParameters; import org.sonar.server.ws.TestRequest; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.api.security.DefaultGroups.ANYONE; import static org.sonar.api.web.UserRole.ADMIN; @@ -142,75 +143,67 @@ public class AddGroupToTemplateActionTest extends BasePermissionWsTest newRequest(ANYONE, template.getUuid(), ADMIN)) + .isInstanceOf(BadRequestException.class) + .hasMessage(String.format("It is not possible to add the '%s' permission to the group 'Anyone'.", UserRole.ADMIN)); } @Test public void fail_if_not_a_project_permission() { loginAsAdmin(); - expectedException.expect(IllegalArgumentException.class); - - newRequest(group.getName(), template.getUuid(), GlobalPermissions.PROVISIONING); + assertThatThrownBy(() -> newRequest(group.getName(), template.getUuid(), GlobalPermissions.PROVISIONING)) + .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_if_not_admin() { userSession.logIn(); - expectedException.expect(ForbiddenException.class); - - newRequest(group.getName(), template.getUuid(), CODEVIEWER); + assertThatThrownBy(() -> newRequest(group.getName(), template.getUuid(), CODEVIEWER)) + .isInstanceOf(ForbiddenException.class); } @Test public void fail_if_group_params_missing() { loginAsAdmin(); - expectedException.expect(BadRequestException.class); - - newRequest(null, template.getUuid(), CODEVIEWER); + assertThatThrownBy(() -> newRequest(null, template.getUuid(), CODEVIEWER)) + .isInstanceOf(BadRequestException.class); } @Test public void fail_if_permission_missing() { loginAsAdmin(); - expectedException.expect(IllegalArgumentException.class); - - newRequest(group.getName(), template.getUuid(), null); + assertThatThrownBy(() -> newRequest(group.getName(), template.getUuid(), null)) + .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_if_template_uuid_and_name_missing() { loginAsAdmin(); - expectedException.expect(BadRequestException.class); - - newRequest(group.getName(), null, CODEVIEWER); + assertThatThrownBy(() -> newRequest(group.getName(), null, CODEVIEWER)) + .isInstanceOf(BadRequestException.class); } @Test public void fail_if_group_does_not_exist() { loginAsAdmin(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("No group with name 'unknown-group-name'"); - - newRequest("unknown-group-name", template.getUuid(), CODEVIEWER); + assertThatThrownBy(() -> newRequest("unknown-group-name", template.getUuid(), CODEVIEWER)) + .isInstanceOf(NotFoundException.class) + .hasMessage("No group with name 'unknown-group-name'"); } @Test public void fail_if_template_key_does_not_exist() { loginAsAdmin(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Permission template with id 'unknown-key' is not found"); - - newRequest(group.getName(), "unknown-key", CODEVIEWER); + assertThatThrownBy(() -> newRequest(group.getName(), "unknown-key", CODEVIEWER)) + .isInstanceOf(NotFoundException.class) + .hasMessage("Permission template with id 'unknown-key' is not found"); } private void newRequest(@Nullable String groupName, @Nullable String templateKey, @Nullable String permission) { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/AddProjectCreatorToTemplateActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/AddProjectCreatorToTemplateActionTest.java index ae5b0f76724..698a1223e55 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/AddProjectCreatorToTemplateActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/AddProjectCreatorToTemplateActionTest.java @@ -39,6 +39,7 @@ import org.sonar.server.permission.ws.BasePermissionWsTest; import org.sonar.server.permission.ws.WsParameters; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; import static org.sonar.core.permission.GlobalPermissions.QUALITY_GATE_ADMIN; @@ -109,36 +110,39 @@ public class AddProjectCreatorToTemplateActionTest extends BasePermissionWsTest< public void fail_when_template_does_not_exist() { loginAsAdmin(); - expectedException.expect(NotFoundException.class); - - newRequest() - .setParam(PARAM_PERMISSION, UserRole.ADMIN) - .setParam(PARAM_TEMPLATE_ID, "42") - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_PERMISSION, UserRole.ADMIN) + .setParam(PARAM_TEMPLATE_ID, "42") + .execute(); + }) + .isInstanceOf(NotFoundException.class); } @Test public void fail_if_permission_is_not_a_project_permission() { loginAsAdmin(); - expectedException.expect(IllegalArgumentException.class); - - newRequest() - .setParam(PARAM_PERMISSION, QUALITY_GATE_ADMIN) - .setParam(PARAM_TEMPLATE_ID, template.getUuid()) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_PERMISSION, QUALITY_GATE_ADMIN) + .setParam(PARAM_TEMPLATE_ID, template.getUuid()) + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_if_not_admin() { userSession.logIn().addPermission(ADMINISTER_QUALITY_GATES); - expectedException.expect(ForbiddenException.class); - - newRequest() - .setParam(PARAM_PERMISSION, UserRole.ADMIN) - .setParam(PARAM_TEMPLATE_ID, template.getUuid()) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_PERMISSION, UserRole.ADMIN) + .setParam(PARAM_TEMPLATE_ID, template.getUuid()) + .execute(); + }) + .isInstanceOf(ForbiddenException.class); } private void assertThatProjectCreatorIsPresentFor(String permission, String templateUuid) { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/AddUserToTemplateActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/AddUserToTemplateActionTest.java index 490a2bf5955..4fa060c96e2 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/AddUserToTemplateActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/AddUserToTemplateActionTest.java @@ -40,6 +40,7 @@ import org.sonar.server.permission.ws.WsParameters; import org.sonar.server.ws.TestRequest; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.web.UserRole.CODEVIEWER; import static org.sonar.api.web.UserRole.ISSUE_ADMIN; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES; @@ -103,65 +104,71 @@ public class AddUserToTemplateActionTest extends BasePermissionWsTest { + newRequest(user.getLogin(), permissionTemplate.getUuid(), GlobalPermissions.PROVISIONING); + }) + .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_if_not_admin() { userSession.logIn().addPermission(ADMINISTER_QUALITY_PROFILES); - expectedException.expect(ForbiddenException.class); - - newRequest(user.getLogin(), permissionTemplate.getUuid(), CODEVIEWER); + assertThatThrownBy(() -> { + newRequest(user.getLogin(), permissionTemplate.getUuid(), CODEVIEWER); + }) + .isInstanceOf(ForbiddenException.class); } @Test public void fail_if_user_missing() { loginAsAdmin(); - expectedException.expect(IllegalArgumentException.class); - - newRequest(null, permissionTemplate.getUuid(), CODEVIEWER); + assertThatThrownBy(() -> { + newRequest(null, permissionTemplate.getUuid(), CODEVIEWER); + }) + .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_if_permission_missing() { loginAsAdmin(); - expectedException.expect(IllegalArgumentException.class); - - newRequest(user.getLogin(), permissionTemplate.getUuid(), null); + assertThatThrownBy(() -> { + newRequest(user.getLogin(), permissionTemplate.getUuid(), null); + }) + .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_if_template_uuid_and_name_are_missing() { loginAsAdmin(); - expectedException.expect(BadRequestException.class); - - newRequest(user.getLogin(), null, CODEVIEWER); + assertThatThrownBy(() -> { + newRequest(user.getLogin(), null, CODEVIEWER); + }) + .isInstanceOf(BadRequestException.class); } @Test public void fail_if_user_does_not_exist() { loginAsAdmin(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("User with login 'unknown-login' is not found"); + assertThatThrownBy(() -> newRequest("unknown-login", permissionTemplate.getUuid(), CODEVIEWER)) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("User with login 'unknown-login' is not found"); - newRequest("unknown-login", permissionTemplate.getUuid(), CODEVIEWER); } @Test public void fail_if_template_key_does_not_exist() { loginAsAdmin(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Permission template with id 'unknown-key' is not found"); - - newRequest(user.getLogin(), "unknown-key", CODEVIEWER); + assertThatThrownBy(() -> { + newRequest(user.getLogin(), "unknown-key", CODEVIEWER); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("Permission template with id 'unknown-key' is not found"); } private void newRequest(@Nullable String userLogin, @Nullable String templateKey, @Nullable String permission) { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/ApplyTemplateActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/ApplyTemplateActionTest.java index 7449404ba26..e5578ff7a0e 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/ApplyTemplateActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/ApplyTemplateActionTest.java @@ -44,9 +44,11 @@ import org.sonar.server.permission.ws.BasePermissionWsTest; import org.sonar.server.ws.TestRequest; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.resources.Qualifiers.APP; import static org.sonar.api.resources.Qualifiers.PROJECT; import static org.sonar.api.resources.Qualifiers.VIEW; +import static org.sonar.api.web.UserRole.CODEVIEWER; import static org.sonar.db.permission.GlobalPermission.SCAN; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PROJECT_ID; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PROJECT_KEY; @@ -137,58 +139,64 @@ public class ApplyTemplateActionTest extends BasePermissionWsTest { + newRequest("unknown-template-uuid", project.uuid(), null); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("Permission template with id 'unknown-template-uuid' is not found"); } @Test public void fail_when_unknown_project_uuid() { loginAsAdmin(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Project id 'unknown-project-uuid' not found"); - - newRequest(template1.getUuid(), "unknown-project-uuid", null); + assertThatThrownBy(() -> { + newRequest(template1.getUuid(), "unknown-project-uuid", null); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("Project id 'unknown-project-uuid' not found"); } @Test public void fail_when_unknown_project_key() { loginAsAdmin(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Project key 'unknown-project-key' not found"); - - newRequest(template1.getUuid(), null, "unknown-project-key"); + assertThatThrownBy(() -> { + newRequest(template1.getUuid(), null, "unknown-project-key"); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("Project key 'unknown-project-key' not found"); } @Test public void fail_when_template_is_not_provided() { loginAsAdmin(); - expectedException.expect(BadRequestException.class); - - newRequest(null, project.uuid(), null); + assertThatThrownBy(() -> { + newRequest(null, project.uuid(), null); + }) + .isInstanceOf(BadRequestException.class); } @Test public void fail_when_project_uuid_and_key_not_provided() { loginAsAdmin(); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Project id or project key can be provided, not both."); - - newRequest(template1.getUuid(), null, null); + assertThatThrownBy(() -> { + newRequest(template1.getUuid(), null, null); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Project id or project key can be provided, not both."); } @Test public void fail_when_not_admin() { userSession.logIn().addPermission(SCAN); - expectedException.expect(ForbiddenException.class); - - newRequest(template1.getUuid(), project.uuid(), null); + assertThatThrownBy(() -> { + newRequest(template1.getUuid(), project.uuid(), null); + }) + .isInstanceOf(ForbiddenException.class); } private void assertTemplate1AppliedToProject() { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/BulkApplyTemplateActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/BulkApplyTemplateActionTest.java index 382a669331e..0b040155898 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/BulkApplyTemplateActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/BulkApplyTemplateActionTest.java @@ -46,6 +46,7 @@ import org.sonar.server.permission.PermissionTemplateService; import org.sonar.server.permission.ws.BasePermissionWsTest; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.resources.Qualifiers.APP; import static org.sonar.api.resources.Qualifiers.PROJECT; import static org.sonar.api.resources.Qualifiers.VIEW; @@ -121,23 +122,25 @@ public class BulkApplyTemplateActionTest extends BasePermissionWsTest { + newRequest() + .setParam(PARAM_TEMPLATE_NAME, "unknown") + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("Permission template with name 'unknown' is not found (case insensitive)"); } @Test public void request_throws_IAE_if_more_than_1000_projects() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("'projects' can contains only 1000 values, got 1001"); - - newRequest() - .setParam(PARAM_TEMPLATE_NAME, template1.getName()) - .setParam(PARAM_PROJECTS, StringUtils.join(Collections.nCopies(1_001, "foo"), ",")) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_TEMPLATE_NAME, template1.getName()) + .setParam(PARAM_PROJECTS, StringUtils.join(Collections.nCopies(1_001, "foo"), ",")) + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("'projects' can contains only 1000 values, got 1001"); } @Test @@ -290,20 +293,18 @@ public class BulkApplyTemplateActionTest extends BasePermissionWsTest newRequest().execute()) + .isInstanceOf(BadRequestException.class) + .hasMessage("Template name or template id must be provided, not both."); } @Test public void fail_if_template_name_is_incorrect() { loginAsAdmin(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Permission template with id 'unknown-template-uuid' is not found"); - - newRequest().setParam(PARAM_TEMPLATE_ID, "unknown-template-uuid").execute(); + assertThatThrownBy(() -> newRequest().setParam(PARAM_TEMPLATE_ID, "unknown-template-uuid").execute()) + .isInstanceOf(NotFoundException.class) + .hasMessage("Permission template with id 'unknown-template-uuid' is not found"); } private void assertTemplate1AppliedToPublicProject(ComponentDto project) { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/CreateTemplateActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/CreateTemplateActionTest.java index 5720d3f6d51..5099f53a017 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/CreateTemplateActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/CreateTemplateActionTest.java @@ -31,6 +31,7 @@ import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.TestResponse; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES; import static org.sonar.test.JsonAssert.assertJson; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_DESCRIPTION; @@ -84,29 +85,26 @@ public class CreateTemplateActionTest extends BasePermissionWsTest newRequest(null, null, null)) + .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_if_name_empty() { loginAsAdmin(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The 'name' parameter is missing"); - - newRequest("", null, null); + assertThatThrownBy(() -> newRequest("", null, null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("The 'name' parameter is missing"); } @Test public void fail_if_regexp_if_not_valid() { loginAsAdmin(); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("The 'projectKeyPattern' parameter must be a valid Java regular expression. '[azerty' was passed"); - - newRequest("Finance", null, "[azerty"); + assertThatThrownBy(() -> newRequest("Finance", null, "[azerty")) + .isInstanceOf(BadRequestException.class) + .hasMessage("The 'projectKeyPattern' parameter must be a valid Java regular expression. '[azerty' was passed"); } @Test @@ -114,19 +112,17 @@ public class CreateTemplateActionTest extends BasePermissionWsTest newRequest(template.getName(), null, null)) + .isInstanceOf(BadRequestException.class) + .hasMessage("A template with the name '" + template.getName() + "' already exists (case insensitive)."); } @Test public void fail_if_not_admin() { userSession.logIn().addPermission(ADMINISTER_QUALITY_PROFILES); - expectedException.expect(ForbiddenException.class); - - newRequest("Finance", null, null); + assertThatThrownBy(() -> newRequest("Finance", null, null)) + .isInstanceOf(ForbiddenException.class); } private TestResponse newRequest(@Nullable String name, @Nullable String description, @Nullable String projectPattern) { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/DeleteTemplateActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/DeleteTemplateActionTest.java index bf7dc90294c..f234a71ec57 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/DeleteTemplateActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/DeleteTemplateActionTest.java @@ -23,7 +23,6 @@ import javax.annotation.Nullable; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.config.Configuration; import org.sonar.api.impl.utils.AlwaysIncreasingSystem2; import org.sonar.api.web.UserRole; @@ -51,6 +50,7 @@ import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.sonar.api.resources.Qualifiers.APP; import static org.sonar.api.resources.Qualifiers.PROJECT; @@ -63,8 +63,6 @@ public class DeleteTemplateActionTest { @Rule public DbTester db = DbTester.create(new AlwaysIncreasingSystem2()); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private final UserSessionRule userSession = UserSessionRule.standalone(); private final DbClient dbClient = db.getDbClient(); @@ -112,9 +110,8 @@ public class DeleteTemplateActionTest { public void fail_if_uuid_is_not_known() { userSession.logIn(); - expectedException.expect(NotFoundException.class); - - newRequestByUuid(underTest, "unknown-template-uuid"); + assertThatThrownBy(() -> newRequestByUuid(underTest, "unknown-template-uuid")) + .isInstanceOf(NotFoundException.class); } @Test @@ -124,10 +121,9 @@ public class DeleteTemplateActionTest { null, db.permissionTemplates().insertTemplate()); loginAsAdmin(); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("It is not possible to delete the default permission template for projects"); - - newRequestByUuid(underTest, projectTemplate.getUuid()); + assertThatThrownBy(() -> newRequestByUuid(underTest, projectTemplate.getUuid())) + .isInstanceOf(BadRequestException.class) + .hasMessage("It is not possible to delete the default permission template for projects"); } @Test @@ -136,10 +132,9 @@ public class DeleteTemplateActionTest { db.permissionTemplates().setDefaultTemplates(projectTemplate, null, db.permissionTemplates().insertTemplate()); loginAsAdmin(); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("It is not possible to delete the default permission template for projects"); - - newRequestByName(underTest, projectTemplate.getName()); + assertThatThrownBy(() -> newRequestByName(underTest, projectTemplate.getName())) + .isInstanceOf(BadRequestException.class) + .hasMessage("It is not possible to delete the default permission template for projects"); } @Test @@ -148,10 +143,9 @@ public class DeleteTemplateActionTest { db.permissionTemplates().setDefaultTemplates(db.permissionTemplates().insertTemplate(), null, template); loginAsAdmin(); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("It is not possible to delete the default permission template for portfolios"); - - newRequestByUuid(this.underTest, template.getUuid()); + assertThatThrownBy(() -> newRequestByUuid(this.underTest, template.getUuid())) + .isInstanceOf(BadRequestException.class) + .hasMessage("It is not possible to delete the default permission template for portfolios"); } @Test @@ -160,23 +154,21 @@ public class DeleteTemplateActionTest { db.permissionTemplates().setDefaultTemplates(db.permissionTemplates().insertTemplate(), template, null); loginAsAdmin(); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("It is not possible to delete the default permission template for applications"); - - newRequestByUuid(this.underTest, template.getUuid()); + assertThatThrownBy(() -> newRequestByUuid(this.underTest, template.getUuid())) + .isInstanceOf(BadRequestException.class) + .hasMessage("It is not possible to delete the default permission template for applications"); } @Test public void fail_to_delete_by_uuid_if_not_logged_in() { - expectedException.expect(UnauthorizedException.class); - - newRequestByUuid(underTest, "uuid"); + assertThatThrownBy(() -> newRequestByUuid(underTest, "uuid")) + .isInstanceOf(UnauthorizedException.class); } @Test public void fail_to_delete_by_name_if_not_logged_in() { - expectedException.expect(UnauthorizedException.class); - newRequestByName(underTest, "name"); + assertThatThrownBy(() -> newRequestByName(underTest, "name")) + .isInstanceOf(UnauthorizedException.class); } @Test @@ -184,9 +176,8 @@ public class DeleteTemplateActionTest { PermissionTemplateDto template = insertTemplateAndAssociatedPermissions(); userSession.logIn(); - expectedException.expect(ForbiddenException.class); - - newRequestByUuid(underTest, template.getUuid()); + assertThatThrownBy(() -> newRequestByUuid(underTest, template.getUuid())) + .isInstanceOf(ForbiddenException.class); } @Test @@ -194,30 +185,29 @@ public class DeleteTemplateActionTest { PermissionTemplateDto template = db.permissionTemplates().insertTemplate(); userSession.logIn(); - expectedException.expect(ForbiddenException.class); - - newRequestByName(underTest, template.getName()); + assertThatThrownBy(() -> newRequestByName(underTest, template.getName())) + .isInstanceOf(ForbiddenException.class); } @Test public void fail_if_neither_uuid_nor_name_is_provided() { userSession.logIn(); - expectedException.expect(BadRequestException.class); - - newRequestByUuid(underTest, null); + assertThatThrownBy(() -> newRequestByUuid(underTest, null)) + .isInstanceOf(BadRequestException.class); } @Test public void fail_if_both_uuid_and_name_are_provided() { userSession.logIn(); - expectedException.expect(BadRequestException.class); - - underTest.newRequest().setMethod("POST") - .setParam(PARAM_TEMPLATE_ID, "uuid") - .setParam(PARAM_TEMPLATE_NAME, "name") - .execute(); + assertThatThrownBy(() -> { + underTest.newRequest().setMethod("POST") + .setParam(PARAM_TEMPLATE_ID, "uuid") + .setParam(PARAM_TEMPLATE_NAME, "name") + .execute(); + }) + .isInstanceOf(BadRequestException.class); } private UserSessionRule loginAsAdmin() { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/RemoveGroupFromTemplateActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/RemoveGroupFromTemplateActionTest.java index 771a13ba858..57ef872fb45 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/RemoveGroupFromTemplateActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/RemoveGroupFromTemplateActionTest.java @@ -43,6 +43,7 @@ import org.sonar.server.permission.ws.WsParameters; import org.sonar.server.ws.TestRequest; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.api.security.DefaultGroups.ANYONE; import static org.sonar.api.web.UserRole.CODEVIEWER; @@ -136,63 +137,67 @@ public class RemoveGroupFromTemplateActionTest extends BasePermissionWsTest newRequest(group.getName(), template.getUuid(), GlobalPermissions.PROVISIONING)) + .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_if_insufficient_privileges() { userSession.logIn().addPermission(SCAN); - expectedException.expect(ForbiddenException.class); - - newRequest(group.getName(), template.getUuid(), PERMISSION); + assertThatThrownBy(() -> newRequest(group.getName(), template.getUuid(), PERMISSION)) + .isInstanceOf(ForbiddenException.class); } @Test public void fail_if_not_logged_in() { - expectedException.expect(UnauthorizedException.class); - userSession.anonymous(); - - newRequest(group.getName(), template.getUuid(), PERMISSION); + assertThatThrownBy(() -> { + userSession.anonymous(); + newRequest(group.getName(), template.getUuid(), PERMISSION); + }) + .isInstanceOf(UnauthorizedException.class); } @Test public void fail_if_group_params_missing() { - expectedException.expect(BadRequestException.class); - - newRequest(null, template.getUuid(), PERMISSION); + assertThatThrownBy(() -> { + newRequest(null, template.getUuid(), PERMISSION); + }) + .isInstanceOf(BadRequestException.class); } @Test public void fail_if_permission_missing() { - expectedException.expect(IllegalArgumentException.class); - - newRequest(group.getName(), template.getUuid(), null); + assertThatThrownBy(() -> { + newRequest(group.getName(), template.getUuid(), null); + }) + .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_if_template_missing() { - expectedException.expect(BadRequestException.class); - - newRequest(group.getName(), null, PERMISSION); + assertThatThrownBy(() -> { + newRequest(group.getName(), null, PERMISSION); + }) + .isInstanceOf(BadRequestException.class); } @Test public void fail_if_group_does_not_exist() { - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("No group with name 'unknown-group-name'"); - - newRequest("unknown-group-name", template.getUuid(), PERMISSION); + assertThatThrownBy(() -> { + newRequest("unknown-group-name", template.getUuid(), PERMISSION); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("No group with name 'unknown-group-name'"); } @Test public void fail_if_template_key_does_not_exist() { - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Permission template with id 'unknown-key' is not found"); - - newRequest(group.getName(), "unknown-key", PERMISSION); + assertThatThrownBy(() -> { + newRequest(group.getName(), "unknown-key", PERMISSION); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("Permission template with id 'unknown-key' is not found"); } private void newRequest(@Nullable String groupName, @Nullable String templateKey, @Nullable String permission) { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/RemoveProjectCreatorFromTemplateActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/RemoveProjectCreatorFromTemplateActionTest.java index f05ebfebc9a..623298958eb 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/RemoveProjectCreatorFromTemplateActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/RemoveProjectCreatorFromTemplateActionTest.java @@ -41,6 +41,7 @@ import org.sonar.server.permission.ws.BasePermissionWsTest; import org.sonar.server.permission.ws.WsParameters; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PERMISSION; @@ -105,46 +106,50 @@ public class RemoveProjectCreatorFromTemplateActionTest extends BasePermissionWs @Test public void fail_when_template_does_not_exist() { - expectedException.expect(NotFoundException.class); - - newRequest() - .setParam(PARAM_PERMISSION, UserRole.ADMIN) - .setParam(PARAM_TEMPLATE_ID, "42") - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_PERMISSION, UserRole.ADMIN) + .setParam(PARAM_TEMPLATE_ID, "42") + .execute(); + }) + .isInstanceOf(NotFoundException.class); } @Test public void fail_if_permission_is_not_a_project_permission() { - expectedException.expect(IllegalArgumentException.class); - - newRequest() - .setParam(PARAM_PERMISSION, GlobalPermissions.QUALITY_GATE_ADMIN) - .setParam(PARAM_TEMPLATE_ID, template.getUuid()) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_PERMISSION, GlobalPermissions.QUALITY_GATE_ADMIN) + .setParam(PARAM_TEMPLATE_ID, template.getUuid()) + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_if_not_authenticated() { userSession.anonymous(); - expectedException.expect(UnauthorizedException.class); - - newRequest() - .setParam(PARAM_PERMISSION, UserRole.ADMIN) - .setParam(PARAM_TEMPLATE_ID, template.getUuid()) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_PERMISSION, UserRole.ADMIN) + .setParam(PARAM_TEMPLATE_ID, template.getUuid()) + .execute(); + }) + .isInstanceOf(UnauthorizedException.class); } @Test public void fail_if_insufficient_privileges() { userSession.logIn(); - expectedException.expect(ForbiddenException.class); - - newRequest() - .setParam(PARAM_PERMISSION, UserRole.ADMIN) - .setParam(PARAM_TEMPLATE_ID, template.getUuid()) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_PERMISSION, UserRole.ADMIN) + .setParam(PARAM_TEMPLATE_ID, template.getUuid()) + .execute(); + }) + .isInstanceOf(ForbiddenException.class); } private void assertWithoutProjectCreatorFor(String permission) { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/RemoveUserFromTemplateActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/RemoveUserFromTemplateActionTest.java index 6f6148157e9..226805c79d4 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/RemoveUserFromTemplateActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/RemoveUserFromTemplateActionTest.java @@ -42,6 +42,7 @@ import org.sonar.server.permission.ws.WsParameters; import org.sonar.server.ws.TestRequest; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.web.UserRole.CODEVIEWER; import static org.sonar.api.web.UserRole.ISSUE_ADMIN; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PERMISSION; @@ -127,74 +128,80 @@ public class RemoveUserFromTemplateActionTest extends BasePermissionWsTest { + newRequest(user.getLogin(), template.getUuid(), GlobalPermissions.PROVISIONING); + }) + .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_if_insufficient_privileges() { userSession.logIn(); - expectedException.expect(ForbiddenException.class); - - newRequest(user.getLogin(), template.getUuid(), DEFAULT_PERMISSION); + assertThatThrownBy(() -> { + newRequest(user.getLogin(), template.getUuid(), DEFAULT_PERMISSION); + }) + .isInstanceOf(ForbiddenException.class); } @Test public void fail_if_not_logged_in() { userSession.anonymous(); - expectedException.expect(UnauthorizedException.class); - - newRequest(user.getLogin(), template.getUuid(), DEFAULT_PERMISSION); + assertThatThrownBy(() -> { + newRequest(user.getLogin(), template.getUuid(), DEFAULT_PERMISSION); + }) + .isInstanceOf(UnauthorizedException.class); } @Test public void fail_if_user_missing() { loginAsAdmin(); - expectedException.expect(IllegalArgumentException.class); - - newRequest(null, template.getUuid(), DEFAULT_PERMISSION); + assertThatThrownBy(() -> { + newRequest(null, template.getUuid(), DEFAULT_PERMISSION); + }) + .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_if_permission_missing() { loginAsAdmin(); - expectedException.expect(IllegalArgumentException.class); - - newRequest(user.getLogin(), template.getUuid(), null); + assertThatThrownBy(() -> { + newRequest(user.getLogin(), template.getUuid(), null); + }) + .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_if_template_missing() { loginAsAdmin(); - expectedException.expect(BadRequestException.class); - - newRequest(user.getLogin(), null, DEFAULT_PERMISSION); + assertThatThrownBy(() -> { + newRequest(user.getLogin(), null, DEFAULT_PERMISSION); + }) + .isInstanceOf(BadRequestException.class); } @Test public void fail_if_user_does_not_exist() { loginAsAdmin(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("User with login 'unknown-login' is not found"); - - newRequest("unknown-login", template.getUuid(), DEFAULT_PERMISSION); + assertThatThrownBy(() -> newRequest("unknown-login", template.getUuid(), DEFAULT_PERMISSION)) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("User with login 'unknown-login' is not found"); } @Test public void fail_if_template_key_does_not_exist() { loginAsAdmin(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Permission template with id 'unknown-key' is not found"); - - newRequest(user.getLogin(), "unknown-key", DEFAULT_PERMISSION); + assertThatThrownBy(() -> { + newRequest(user.getLogin(), "unknown-key", DEFAULT_PERMISSION); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("Permission template with id 'unknown-key' is not found"); } private void newRequest(@Nullable String userLogin, @Nullable String templateKey, @Nullable String permission) { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/SearchTemplatesActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/SearchTemplatesActionTest.java index b7c6f360a6a..4e5699c96a4 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/SearchTemplatesActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/SearchTemplatesActionTest.java @@ -44,6 +44,7 @@ import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.server.ws.WebService.Param.TEXT_QUERY; import static org.sonar.core.util.Uuids.UUID_EXAMPLE_01; import static org.sonar.core.util.Uuids.UUID_EXAMPLE_02; @@ -208,10 +209,11 @@ public class SearchTemplatesActionTest extends BasePermissionWsTest { + userSession.anonymous(); + newRequest().execute(); + }) + .isInstanceOf(UnauthorizedException.class); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/SearchTemplatesDataTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/SearchTemplatesDataTest.java index c6375347bcd..a77efc95de2 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/SearchTemplatesDataTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/SearchTemplatesDataTest.java @@ -20,17 +20,14 @@ package org.sonar.server.permission.ws.template; import com.google.common.collect.HashBasedTable; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.server.permission.DefaultTemplatesResolverImpl; import static java.util.Collections.singletonList; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.db.permission.template.PermissionTemplateTesting.newPermissionTemplateDto; public class SearchTemplatesDataTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); SearchTemplatesData.Builder underTest = SearchTemplatesData.builder() .defaultTemplates(new DefaultTemplatesResolverImpl.ResolvedDefaultTemplates("template_uuid", null, null)) @@ -41,41 +38,51 @@ public class SearchTemplatesDataTest { @Test public void fail_if_templates_is_null() { - expectedException.expect(IllegalStateException.class); - underTest.templates(null); + assertThatThrownBy(() -> { + underTest.templates(null); - underTest.build(); + underTest.build(); + }) + .isInstanceOf(IllegalStateException.class); } @Test public void fail_if_default_templates_are_null() { - expectedException.expect(IllegalStateException.class); - underTest.defaultTemplates(null); + assertThatThrownBy(() -> { + underTest.defaultTemplates(null); - underTest.build(); + underTest.build(); + }) + .isInstanceOf(IllegalStateException.class); } @Test public void fail_if_user_count_is_null() { - expectedException.expect(IllegalStateException.class); - underTest.userCountByTemplateUuidAndPermission(null); + assertThatThrownBy(() -> { + underTest.userCountByTemplateUuidAndPermission(null); - underTest.build(); + underTest.build(); + }) + .isInstanceOf(IllegalStateException.class); } @Test public void fail_if_group_count_is_null() { - expectedException.expect(IllegalStateException.class); - underTest.groupCountByTemplateUuidAndPermission(null); + assertThatThrownBy(() -> { + underTest.groupCountByTemplateUuidAndPermission(null); - underTest.build(); + underTest.build(); + }) + .isInstanceOf(IllegalStateException.class); } @Test public void fail_if_with_project_creators_is_null() { - expectedException.expect(IllegalStateException.class); - underTest.withProjectCreatorByTemplateUuidAndPermission(null); + assertThatThrownBy(() -> { + underTest.withProjectCreatorByTemplateUuidAndPermission(null); - underTest.build(); + underTest.build(); + }) + .isInstanceOf(IllegalStateException.class); } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/SetDefaultTemplateActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/SetDefaultTemplateActionTest.java index e3507238a08..3b9e9ebf433 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/SetDefaultTemplateActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/SetDefaultTemplateActionTest.java @@ -34,6 +34,7 @@ import org.sonar.server.property.InternalProperties; import org.sonar.server.ws.TestRequest; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.resources.Qualifiers.APP; import static org.sonar.api.resources.Qualifiers.PROJECT; import static org.sonar.api.resources.Qualifiers.VIEW; @@ -122,9 +123,10 @@ public class SetDefaultTemplateActionTest extends BasePermissionWsTest { + newRequest(template.getUuid(), PROJECT); + }) + .isInstanceOf(UnauthorizedException.class); } @Test @@ -132,23 +134,26 @@ public class SetDefaultTemplateActionTest extends BasePermissionWsTest { + newRequest(template.getUuid(), null); + }) + .isInstanceOf(ForbiddenException.class); } @Test public void fail_if_template_not_provided() { - expectedException.expect(BadRequestException.class); - - newRequest(null, PROJECT); + assertThatThrownBy(() -> { + newRequest(null, PROJECT); + }) + .isInstanceOf(BadRequestException.class); } @Test public void fail_if_template_does_not_exist() { - expectedException.expect(NotFoundException.class); - - newRequest("unknown-template-uuid", PROJECT); + assertThatThrownBy(() -> { + newRequest("unknown-template-uuid", PROJECT); + }) + .isInstanceOf(NotFoundException.class); } @Test @@ -156,10 +161,11 @@ public class SetDefaultTemplateActionTest extends BasePermissionWsTest { + newRequest(template.getUuid(), Qualifiers.FILE); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Value of parameter 'qualifier' (FIL) must be one of: [APP, TRK, VW]"); } private void newRequest(@Nullable String templateUuid, @Nullable String qualifier) { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/TemplateGroupsActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/TemplateGroupsActionTest.java index 75d640e20fe..8a8f9a1981a 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/TemplateGroupsActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/TemplateGroupsActionTest.java @@ -43,6 +43,7 @@ import org.sonar.server.permission.ws.WsParameters; import org.sonarqube.ws.Permissions.WsGroupsResponse; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.server.ws.WebService.Param.PAGE; import static org.sonar.api.server.ws.WebService.Param.PAGE_SIZE; import static org.sonar.api.server.ws.WebService.Param.TEXT_QUERY; @@ -291,12 +292,13 @@ public class TemplateGroupsActionTest extends BasePermissionWsTest { + newRequest() + .setParam(PARAM_PERMISSION, USER) + .setParam(PARAM_TEMPLATE_ID, template1.getUuid()) + .execute(); + }) + .isInstanceOf(UnauthorizedException.class); } @Test @@ -304,12 +306,13 @@ public class TemplateGroupsActionTest extends BasePermissionWsTest { + newRequest() + .setParam(PARAM_PERMISSION, USER) + .setParam(PARAM_TEMPLATE_ID, template1.getUuid()) + .execute(); + }) + .isInstanceOf(ForbiddenException.class); } @Test @@ -317,36 +320,39 @@ public class TemplateGroupsActionTest extends BasePermissionWsTest { + newRequest() + .setParam(PARAM_PERMISSION, USER) + .setParam(PARAM_TEMPLATE_ID, template1.getUuid()) + .setParam(PARAM_TEMPLATE_NAME, template1.getName()) + .execute(); + }) + .isInstanceOf(BadRequestException.class); } @Test public void fail_if_template_uuid_nor_name_provided() { loginAsAdmin(); - expectedException.expect(BadRequestException.class); - - newRequest() - .setParam(PARAM_PERMISSION, USER) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_PERMISSION, USER) + .execute(); + }) + .isInstanceOf(BadRequestException.class); } @Test public void fail_if_template_is_not_found() { loginAsAdmin(); - expectedException.expect(NotFoundException.class); - - newRequest() - .setParam(PARAM_PERMISSION, USER) - .setParam(PARAM_TEMPLATE_ID, "unknown-uuid") - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_PERMISSION, USER) + .setParam(PARAM_TEMPLATE_ID, "unknown-uuid") + .execute(); + }) + .isInstanceOf(NotFoundException.class); } @Test @@ -354,12 +360,13 @@ public class TemplateGroupsActionTest extends BasePermissionWsTest { + newRequest() + .setParam(PARAM_PERMISSION, GlobalPermissions.QUALITY_GATE_ADMIN) + .setParam(PARAM_TEMPLATE_ID, template1.getUuid()) + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class); } private GroupDto insertGroup(String name, String description) { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/TemplateUsersActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/TemplateUsersActionTest.java index 899a6cf6ac4..ddb4a875e94 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/TemplateUsersActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/TemplateUsersActionTest.java @@ -26,6 +26,7 @@ import org.sonar.api.resources.Qualifiers; import org.sonar.api.resources.ResourceTypes; import org.sonar.api.server.ws.WebService; import org.sonar.api.web.UserRole; +import org.sonar.core.permission.GlobalPermissions; import org.sonar.db.component.ResourceTypesRule; import org.sonar.db.permission.GlobalPermission; import org.sonar.db.permission.template.PermissionTemplateDto; @@ -45,6 +46,7 @@ import org.sonar.server.ws.TestRequest; import org.sonarqube.ws.Permissions; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.web.UserRole.ADMIN; import static org.sonar.api.web.UserRole.CODEVIEWER; import static org.sonar.api.web.UserRole.ISSUE_ADMIN; @@ -247,30 +249,33 @@ public class TemplateUsersActionTest extends BasePermissionWsTest { + newRequest(GlobalPermission.PROVISION_PROJECTS.getKey(), template.getUuid()) + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_if_no_template_param() { loginAsAdmin(); - expectedException.expect(BadRequestException.class); - - newRequest(null, null) - .execute(); + assertThatThrownBy(() -> { + newRequest(null, null) + .execute(); + }) + .isInstanceOf(BadRequestException.class); } @Test public void fail_if_template_does_not_exist() { loginAsAdmin(); - expectedException.expect(NotFoundException.class); - - newRequest(null, "unknown-template-uuid") - .execute(); + assertThatThrownBy(() -> { + newRequest(null, "unknown-template-uuid") + .execute(); + }) + .isInstanceOf(NotFoundException.class); } @Test @@ -278,11 +283,12 @@ public class TemplateUsersActionTest extends BasePermissionWsTest { + newRequest(null, template.getUuid()) + .setParam(PARAM_TEMPLATE_NAME, template.getName()) + .execute(); + }) + .isInstanceOf(BadRequestException.class); } @Test @@ -290,9 +296,10 @@ public class TemplateUsersActionTest extends BasePermissionWsTest { + newRequest(null, template.getUuid()).execute(); + }) + .isInstanceOf(UnauthorizedException.class); } @Test @@ -300,9 +307,10 @@ public class TemplateUsersActionTest extends BasePermissionWsTest { + newRequest(null, template.getUuid()).execute(); + }) + .isInstanceOf(ForbiddenException.class); } private UserDto insertUser(UserDto userDto) { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/UpdateTemplateActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/UpdateTemplateActionTest.java index d373115c36d..0c6acd185b8 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/UpdateTemplateActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/UpdateTemplateActionTest.java @@ -33,6 +33,7 @@ import org.sonar.server.permission.ws.BasePermissionWsTest; import org.sonar.server.ws.TestRequest; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; import static org.sonar.db.permission.GlobalPermission.SCAN; @@ -131,10 +132,11 @@ public class UpdateTemplateActionTest extends BasePermissionWsTest { + call("unknown-key", null, null, null); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("Permission template with id 'unknown-key' is not found"); } @Test @@ -142,49 +144,54 @@ public class UpdateTemplateActionTest extends BasePermissionWsTest { + call(this.template.getUuid(), anotherTemplate.getName(), null, null); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("A template with the name '" + anotherTemplate.getName() + "' already exists (case insensitive)."); } @Test public void fail_if_key_is_not_provided() { loginAsAdmin(); - expectedException.expect(IllegalArgumentException.class); - - call(null, "Finance", null, null); + assertThatThrownBy(() -> { + call(null, "Finance", null, null); + }) + .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_if_name_empty() { loginAsAdmin(); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("The template name must not be blank"); - - call(template.getUuid(), "", null, null); + assertThatThrownBy(() -> { + call(template.getUuid(), "", null, null); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("The template name must not be blank"); } @Test public void fail_if_name_has_just_whitespaces() { loginAsAdmin(); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("The template name must not be blank"); - - call(template.getUuid(), " \r\n", null, null); + assertThatThrownBy(() -> { + call(template.getUuid(), " \r\n", null, null); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("The template name must not be blank"); } @Test public void fail_if_regexp_if_not_valid() { loginAsAdmin(); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("The 'projectKeyPattern' parameter must be a valid Java regular expression. '[azerty' was passed"); - - call(template.getUuid(), "Finance", null, "[azerty"); + assertThatThrownBy(() -> { + call(template.getUuid(), "Finance", null, "[azerty"); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("The 'projectKeyPattern' parameter must be a valid Java regular expression. '[azerty' was passed"); } @Test @@ -193,27 +200,32 @@ public class UpdateTemplateActionTest extends BasePermissionWsTest { + call(this.template.getUuid(), nameCaseInsensitive, null, null); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("A template with the name '" + nameCaseInsensitive + "' already exists (case insensitive)."); } @Test public void fail_if_not_logged_in() { - expectedException.expect(UnauthorizedException.class); - userSession.anonymous(); + assertThatThrownBy(() -> { + userSession.anonymous(); - call(template.getUuid(), "Finance", null, null); + call(template.getUuid(), "Finance", null, null); + }) + .isInstanceOf(UnauthorizedException.class); } @Test public void fail_if_not_admin() { userSession.logIn().addPermission(SCAN); - expectedException.expect(ForbiddenException.class); - - call(template.getUuid(), "Finance", null, null); + assertThatThrownBy(() -> { + call(template.getUuid(), "Finance", null, null); + }) + .isInstanceOf(ForbiddenException.class); } private String call(@Nullable String key, @Nullable String name, @Nullable String description, @Nullable String projectPattern) { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/ChangeLogLevelActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/ChangeLogLevelActionTest.java index 45a886bd5dc..3dc66e9ef9c 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/ChangeLogLevelActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/ChangeLogLevelActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.platform.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.utils.log.LoggerLevel; import org.sonar.server.ce.http.CeHttpClient; import org.sonar.server.exceptions.ForbiddenException; @@ -29,6 +28,7 @@ import org.sonar.server.log.ServerLogging; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.WsActionTester; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -36,8 +36,6 @@ public class ChangeLogLevelActionTest { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private ServerLogging serverLogging = mock(ServerLogging.class); private CeHttpClient ceHttpClient = mock(CeHttpClient.class); @@ -46,18 +44,16 @@ public class ChangeLogLevelActionTest { @Test public void request_fails_with_ForbiddenException_when_user_is_not_logged_in() { - expectedException.expect(ForbiddenException.class); - - actionTester.newRequest().setMethod("POST").execute(); + assertThatThrownBy(() -> actionTester.newRequest().setMethod("POST").execute()) + .isInstanceOf(ForbiddenException.class); } @Test public void request_fails_with_ForbiddenException_when_user_is_not_system_administrator() { userSession.logIn().setNonSystemAdministrator(); - expectedException.expect(ForbiddenException.class); - - actionTester.newRequest().setMethod("POST").execute(); + assertThatThrownBy(() -> actionTester.newRequest().setMethod("POST").execute()) + .isInstanceOf(ForbiddenException.class); } @Test @@ -90,23 +86,21 @@ public class ChangeLogLevelActionTest { public void fail_if_unsupported_level() { logInAsSystemAdministrator(); - expectedException.expect(IllegalArgumentException.class); - - actionTester.newRequest() + assertThatThrownBy(() -> actionTester.newRequest() .setParam("level", "ERROR") .setMethod("POST") - .execute(); + .execute()) + .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_if_missing_level() { logInAsSystemAdministrator(); - expectedException.expect(IllegalArgumentException.class); - - actionTester.newRequest() + assertThatThrownBy(() -> actionTester.newRequest() .setMethod("POST") - .execute(); + .execute()) + .isInstanceOf(IllegalArgumentException.class); } private void logInAsSystemAdministrator() { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/DbMigrationStatusActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/DbMigrationStatusActionTest.java index 63196863acc..32448e1749c 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/DbMigrationStatusActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/DbMigrationStatusActionTest.java @@ -28,9 +28,7 @@ import java.util.Date; import java.util.Optional; import javax.annotation.Nullable; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.api.utils.DateUtils; import org.sonar.db.Database; @@ -44,6 +42,7 @@ import org.sonar.server.ws.WsActionTester; import static com.google.common.base.Predicates.in; import static com.google.common.base.Predicates.not; import static com.google.common.collect.Iterables.filter; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.when; @@ -66,8 +65,6 @@ import static org.sonar.test.JsonAssert.assertJson; @RunWith(DataProviderRunner.class) public class DbMigrationStatusActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private static final Date SOME_DATE = new Date(); private static final String SOME_THROWABLE_MSG = "blablabla pop !"; @@ -102,10 +99,9 @@ public class DbMigrationStatusActionTest { reset(database); when(databaseVersion.getVersion()).thenReturn(Optional.empty()); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Cannot connect to Database."); - - tester.newRequest().execute(); + assertThatThrownBy(() -> tester.newRequest().execute()) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Cannot connect to Database."); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/HealthActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/HealthActionTest.java index 71bb50131c2..78b9b31276e 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/HealthActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/HealthActionTest.java @@ -31,7 +31,6 @@ import java.util.stream.IntStream; import org.apache.commons.lang.RandomStringUtils; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.process.cluster.health.NodeDetails; import org.sonar.process.cluster.health.NodeHealth; @@ -52,6 +51,8 @@ import static java.util.Collections.singleton; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.ThrowableAssert.ThrowingCallable; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -64,8 +65,6 @@ import static org.sonar.server.health.Health.newHealthCheckBuilder; import static org.sonar.test.JsonAssert.assertJson; public class HealthActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSessionRule = UserSessionRule.standalone(); @@ -92,9 +91,8 @@ public class HealthActionTest { public void request_fails_with_ForbiddenException_when_anonymous() { TestRequest request = underTest.newRequest(); - expectForbiddenException(); + expectForbiddenException(() -> request.execute()); - request.execute(); } @Test @@ -102,9 +100,7 @@ public class HealthActionTest { when(systemPasscode.isValid(any())).thenReturn(false); TestRequest request = underTest.newRequest(); - expectForbiddenException(); - - request.execute(); + expectForbiddenException(() -> request.execute()); } @Test @@ -114,9 +110,7 @@ public class HealthActionTest { when(healthChecker.checkCluster()).thenReturn(randomStatusMinimalClusterHealth()); TestRequest request = underTest.newRequest(); - expectForbiddenException(); - - request.execute(); + expectForbiddenException(() -> request.execute()); } @Test @@ -310,13 +304,13 @@ public class HealthActionTest { .setStatus(NodeHealth.Status.values()[random.nextInt(NodeHealth.Status.values().length)]); IntStream.range(0, random.nextInt(4)).mapToObj(i -> randomAlphabetic(5)).forEach(builder::addCause); return builder.setDetails( - newNodeDetailsBuilder() - .setType(random.nextBoolean() ? NodeDetails.Type.APPLICATION : NodeDetails.Type.SEARCH) - .setName(randomAlphanumeric(3)) - .setHost(randomAlphanumeric(4)) - .setPort(1 + random.nextInt(3)) - .setStartedAt(1 + random.nextInt(23)) - .build()) + newNodeDetailsBuilder() + .setType(random.nextBoolean() ? NodeDetails.Type.APPLICATION : NodeDetails.Type.SEARCH) + .setName(randomAlphanumeric(3)) + .setHost(randomAlphanumeric(4)) + .setPort(1 + random.nextInt(3)) + .setStartedAt(1 + random.nextInt(23)) + .build()) .build(); } @@ -325,13 +319,13 @@ public class HealthActionTest { .setStatus(NodeHealth.Status.values()[random.nextInt(NodeHealth.Status.values().length)]); IntStream.range(0, random.nextInt(4)).mapToObj(i -> randomAlphabetic(5)).forEach(builder::addCause); return builder.setDetails( - newNodeDetailsBuilder() - .setType(type) - .setName(name) - .setHost(host) - .setPort(port) - .setStartedAt(started) - .build()) + newNodeDetailsBuilder() + .setType(type) + .setName(name) + .setHost(host) + .setPort(port) + .setStartedAt(started) + .build()) .build(); } @@ -341,9 +335,10 @@ public class HealthActionTest { .build(), emptySet()); } - private void expectForbiddenException() { - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); + private void expectForbiddenException(ThrowingCallable shouldRaiseThrowable) { + assertThatThrownBy(shouldRaiseThrowable) + .isInstanceOf(ForbiddenException.class) + .hasMessageContaining("Insufficient privileges"); } /** diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/IndexActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/IndexActionTest.java index 97dd63b8853..cf490b3c3d2 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/IndexActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/IndexActionTest.java @@ -23,9 +23,7 @@ import com.google.common.collect.ImmutableSet; import java.net.HttpURLConnection; import java.util.Date; import javax.annotation.Nullable; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.platform.Server; import org.sonar.api.utils.DateUtils; import org.sonar.core.i18n.DefaultI18n; @@ -37,6 +35,7 @@ import static java.util.Locale.ENGLISH; import static java.util.Locale.PRC; import static java.util.Locale.UK; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; @@ -49,8 +48,6 @@ public class IndexActionTest { private static final String KEY_2 = "key2"; private static final String KEY_3 = "key3"; - @Rule - public ExpectedException expectedException = ExpectedException.none(); private DefaultI18n i18n = mock(DefaultI18n.class); private Server server = mock(Server.class); @@ -133,9 +130,9 @@ public class IndexActionTest { when(i18n.message(UK, key1, key1)).thenReturn(key1); when(i18n.getEffectiveLocale(UK)).thenReturn(UK); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Locale cannot be parsed as a BCP47 language tag"); - call("en_GB", null); + assertThatThrownBy(() -> call("en_GB", null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Locale cannot be parsed as a BCP47 language tag"); } private TestResponse call(@Nullable String locale, @Nullable String timestamp) { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/InfoActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/InfoActionTest.java index aac66fa9109..fdee359da0a 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/InfoActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/InfoActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.platform.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.platform.SystemInfoWriter; import org.sonar.server.tester.UserSessionRule; @@ -29,14 +28,13 @@ import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class InfoActionTest { @Rule public UserSessionRule userSessionRule = UserSessionRule.standalone() .logIn("login") .setName("name"); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private SystemInfoWriter jsonWriter = json -> json.prop("key", "value"); private InfoAction underTest = new InfoAction(userSessionRule, jsonWriter); @@ -52,18 +50,16 @@ public class InfoActionTest { @Test public void request_fails_with_ForbiddenException_when_user_is_not_logged_in() { - expectedException.expect(ForbiddenException.class); - - ws.newRequest().execute(); + assertThatThrownBy(() -> ws.newRequest().execute()) + .isInstanceOf(ForbiddenException.class); } @Test public void request_fails_with_ForbiddenException_when_user_is_not_system_administrator() { userSessionRule.logIn().setNonSystemAdministrator(); - expectedException.expect(ForbiddenException.class); - - ws.newRequest().execute(); + assertThatThrownBy(() -> ws.newRequest().execute()) + .isInstanceOf(ForbiddenException.class); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/LogsActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/LogsActionTest.java index cc7630ad5c8..e89cb182e92 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/LogsActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/LogsActionTest.java @@ -25,7 +25,6 @@ import java.util.Set; import org.apache.commons.io.FileUtils; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.log.ServerLogging; @@ -36,6 +35,7 @@ import org.sonarqube.ws.MediaTypes; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -45,8 +45,6 @@ public class LogsActionTest { public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public TemporaryFolder temp = new TemporaryFolder(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private ServerLogging serverLogging = mock(ServerLogging.class); private LogsAction underTest = new LogsAction(userSession, serverLogging); @@ -61,18 +59,16 @@ public class LogsActionTest { @Test public void request_fails_with_ForbiddenException_when_user_is_not_logged_in() { - expectedException.expect(ForbiddenException.class); - - actionTester.newRequest().execute(); + assertThatThrownBy(() -> actionTester.newRequest().execute()) + .isInstanceOf(ForbiddenException.class); } @Test public void request_fails_with_ForbiddenException_when_user_is_not_system_administrator() { userSession.logIn(); - expectedException.expect(ForbiddenException.class); - - actionTester.newRequest().execute(); + assertThatThrownBy(() -> actionTester.newRequest().execute()) + .isInstanceOf(ForbiddenException.class); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/MigrateDbActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/MigrateDbActionTest.java index b4891a6b7ba..d76241d7856 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/MigrateDbActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/MigrateDbActionTest.java @@ -28,9 +28,7 @@ import java.util.Date; import java.util.Optional; import javax.annotation.Nullable; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.api.utils.DateUtils; import org.sonar.db.Database; @@ -45,6 +43,7 @@ import org.sonar.server.ws.WsActionTester; import static com.google.common.base.Predicates.in; import static com.google.common.base.Predicates.not; import static com.google.common.collect.Iterables.filter; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.verify; @@ -57,8 +56,6 @@ import static org.sonar.test.JsonAssert.assertJson; @RunWith(DataProviderRunner.class) public class MigrateDbActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private static final Date SOME_DATE = new Date(); private static final String SOME_THROWABLE_MSG = "blablabla pop !"; @@ -94,10 +91,9 @@ public class MigrateDbActionTest { reset(databaseVersion); when(databaseVersion.getVersion()).thenReturn(Optional.empty()); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Cannot connect to Database."); - - tester.newRequest().execute(); + assertThatThrownBy(() -> tester.newRequest().execute()) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Cannot connect to Database."); } @Test @@ -222,7 +218,7 @@ public class MigrateDbActionTest { @DataProvider public static Object[][] statusRequiringDbMigration() { - return new Object[][] { + return new Object[][]{ {DatabaseVersion.Status.FRESH_INSTALL}, {DatabaseVersion.Status.REQUIRES_UPGRADE}, }; diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/RestartActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/RestartActionTest.java index ff471e02ff4..2be28fe1397 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/RestartActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/RestartActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.platform.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.InOrder; import org.mockito.Mockito; import org.sonar.api.utils.log.LogTester; @@ -34,6 +33,7 @@ import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -41,8 +41,6 @@ public class RestartActionTest { @Rule public UserSessionRule userSessionRule = UserSessionRule.standalone(); @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Rule public LogTester logTester = new LogTester(); private ProcessCommandWrapper processCommandWrapper = mock(ProcessCommandWrapper.class); @@ -56,9 +54,9 @@ public class RestartActionTest { @Test public void request_fails_in_production_mode_with_ForbiddenException_when_user_is_not_logged_in() { when(webServer.isStandalone()).thenReturn(true); - expectedException.expect(ForbiddenException.class); - actionTester.newRequest().execute(); + assertThatThrownBy(() -> actionTester.newRequest().execute()) + .isInstanceOf(ForbiddenException.class); } @Test @@ -66,19 +64,17 @@ public class RestartActionTest { when(webServer.isStandalone()).thenReturn(true); userSessionRule.logIn().setNonSystemAdministrator(); - expectedException.expect(ForbiddenException.class); - - actionTester.newRequest().execute(); + assertThatThrownBy(() -> actionTester.newRequest().execute()) + .isInstanceOf(ForbiddenException.class); } @Test public void request_fails_in_cluster_mode_with_IllegalArgumentException() { when(webServer.isStandalone()).thenReturn(false); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Restart not allowed for cluster nodes"); - - actionTester.newRequest().execute(); + assertThatThrownBy(() -> actionTester.newRequest().execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Restart not allowed for cluster nodes"); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/SafeModeHealthActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/SafeModeHealthActionTest.java index 1518c8f8a45..73357da7ba5 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/SafeModeHealthActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/SafeModeHealthActionTest.java @@ -23,9 +23,8 @@ import java.util.Arrays; import java.util.Random; import java.util.stream.IntStream; import org.apache.commons.lang.RandomStringUtils; -import org.junit.Rule; +import org.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.health.Health; @@ -38,6 +37,7 @@ import org.sonarqube.ws.System; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -45,8 +45,6 @@ import static org.sonar.server.health.Health.newHealthCheckBuilder; import static org.sonar.test.JsonAssert.assertJson; public class SafeModeHealthActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private final Random random = new Random(); private HealthChecker healthChecker = mock(HealthChecker.class); @@ -71,9 +69,7 @@ public class SafeModeHealthActionTest { when(systemPasscode.isValid(any())).thenReturn(false); TestRequest request = underTest.newRequest(); - expectForbiddenException(); - - request.execute(); + expectForbiddenException(() -> request.execute()); } @Test @@ -137,9 +133,10 @@ public class SafeModeHealthActionTest { .containsOnly(causes); } - private void expectForbiddenException() { - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); + private void expectForbiddenException(ThrowingCallable shouldRaiseThrowable) { + assertThatThrownBy(shouldRaiseThrowable) + .isInstanceOf(ForbiddenException.class) + .hasMessageContaining("Insufficient privileges"); } private void authenticateWithPasscode() { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/AvailableActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/AvailableActionTest.java index bcc5183ea67..065e84322c4 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/AvailableActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/AvailableActionTest.java @@ -22,7 +22,6 @@ package org.sonar.server.plugins.ws; import java.util.Optional; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.DateUtils; import org.sonar.server.exceptions.ForbiddenException; @@ -35,6 +34,7 @@ import org.sonar.updatecenter.common.Release; import static com.google.common.collect.ImmutableList.of; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.Mockito.when; import static org.sonar.test.JsonAssert.assertJson; @@ -63,8 +63,6 @@ public class AvailableActionTest extends AbstractUpdateCenterBasedPluginsWsActio @Rule public UserSessionRule userSession = UserSessionRule.standalone(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private AvailableAction underTest = new AvailableAction(userSession, updateCenterFactory); private WsActionTester tester = new WsActionTester(underTest); @@ -83,24 +81,24 @@ public class AvailableActionTest extends AbstractUpdateCenterBasedPluginsWsActio logInAsSystemAdministrator(); when(updateCenter.findAvailablePlugins()).thenReturn(of( pluginUpdate(release(Plugin.factory("abap") - .setName("ABAP") - .setCategory("Languages") - .setDescription("Enable analysis and reporting on ABAP projects") - .setLicense("Commercial") - .setOrganization("SonarSource") - .setOrganizationUrl("http://www.sonarsource.com") - .setTermsConditionsUrl("http://dist.sonarsource.com/SonarSource_Terms_And_Conditions.pdf"), - "3.2") + .setName("ABAP") + .setCategory("Languages") + .setDescription("Enable analysis and reporting on ABAP projects") + .setLicense("Commercial") + .setOrganization("SonarSource") + .setOrganizationUrl("http://www.sonarsource.com") + .setTermsConditionsUrl("http://dist.sonarsource.com/SonarSource_Terms_And_Conditions.pdf"), + "3.2") .setDate(DateUtils.parseDate("2015-03-10")), COMPATIBLE), pluginUpdate(release(Plugin.factory("android") - .setName("Android") - .setCategory("Languages") - .setDescription("Import Android Lint reports.") - .setLicense("GNU LGPL 3") - .setOrganization("SonarSource and Jerome Van Der Linden, Stephane Nicolas, Florian Roncari, Thomas Bores") - .setOrganizationUrl("http://www.sonarsource.com"), - "1.0") + .setName("Android") + .setCategory("Languages") + .setDescription("Import Android Lint reports.") + .setLicense("GNU LGPL 3") + .setOrganization("SonarSource and Jerome Van Der Linden, Stephane Nicolas, Florian Roncari, Thomas Bores") + .setOrganizationUrl("http://www.sonarsource.com"), + "1.0") .setDate(DateUtils.parseDate("2014-03-31")) .addOutgoingDependency(release(Plugin.factory("java").setName("Java").setDescription("SonarQube rule engine."), "0.3.6")), COMPATIBLE))); @@ -112,18 +110,16 @@ public class AvailableActionTest extends AbstractUpdateCenterBasedPluginsWsActio @Test public void request_fails_with_ForbiddenException_when_user_is_not_logged_in() { - expectedException.expect(ForbiddenException.class); - - tester.newRequest().execute(); + assertThatThrownBy(() -> tester.newRequest().execute()) + .isInstanceOf(ForbiddenException.class); } @Test public void request_fails_with_ForbiddenException_when_user_is_not_system_administrator() { userSession.logIn().setNonSystemAdministrator(); - expectedException.expect(ForbiddenException.class); - - tester.newRequest().execute(); + assertThatThrownBy(() -> tester.newRequest().execute()) + .isInstanceOf(ForbiddenException.class); } @Test @@ -154,41 +150,41 @@ public class AvailableActionTest extends AbstractUpdateCenterBasedPluginsWsActio TestResponse response = tester.newRequest().execute(); response.assertJson( - "{" + - " \"plugins\": [" + - " {" + - " \"key\": \"pkey\"," + - " \"name\": \"p_name\"," + - " \"category\": \"p_category\"," + - " \"description\": \"p_description\"," + - " \"license\": \"p_license\"," + - " \"termsAndConditionsUrl\": \"p_t_and_c_url\"," + - " \"organizationName\": \"p_orga_name\"," + - " \"organizationUrl\": \"p_orga_url\"," + - " \"homepageUrl\": \"p_homepage_url\"," + - " \"issueTrackerUrl\": \"p_issue_url\"," + - " \"release\": {" + - " \"version\": \"1.12.1\"," + - " \"date\": \"2015-04-16\"" + - " }," + - " \"update\": {" + - " \"status\": \"COMPATIBLE\"," + - " \"requires\": [" + - " {" + - " \"key\": \"pkey1\"," + - " \"name\": \"p_name_1\"" + - " }," + - " {" + - " \"key\": \"pkey2\"," + - " \"name\": \"p_name_2\"," + - " \"description\": \"p_desc_2\"" + - " }" + - " ]" + - " }" + - " }" + - " ]," + - " \"updateCenterRefresh\": \"2015-04-24T16:08:36+0200\"" + - "}"); + "{" + + " \"plugins\": [" + + " {" + + " \"key\": \"pkey\"," + + " \"name\": \"p_name\"," + + " \"category\": \"p_category\"," + + " \"description\": \"p_description\"," + + " \"license\": \"p_license\"," + + " \"termsAndConditionsUrl\": \"p_t_and_c_url\"," + + " \"organizationName\": \"p_orga_name\"," + + " \"organizationUrl\": \"p_orga_url\"," + + " \"homepageUrl\": \"p_homepage_url\"," + + " \"issueTrackerUrl\": \"p_issue_url\"," + + " \"release\": {" + + " \"version\": \"1.12.1\"," + + " \"date\": \"2015-04-16\"" + + " }," + + " \"update\": {" + + " \"status\": \"COMPATIBLE\"," + + " \"requires\": [" + + " {" + + " \"key\": \"pkey1\"," + + " \"name\": \"p_name_1\"" + + " }," + + " {" + + " \"key\": \"pkey2\"," + + " \"name\": \"p_name_2\"," + + " \"description\": \"p_desc_2\"" + + " }" + + " ]" + + " }" + + " }" + + " ]," + + " \"updateCenterRefresh\": \"2015-04-24T16:08:36+0200\"" + + "}"); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/CancelAllActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/CancelAllActionTest.java index a0231778c63..284135f776c 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/CancelAllActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/CancelAllActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.plugins.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.plugins.PluginDownloader; @@ -31,6 +30,7 @@ import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -38,8 +38,6 @@ import static org.mockito.Mockito.verify; public class CancelAllActionTest { @Rule public UserSessionRule userSessionRule = UserSessionRule.standalone(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private PluginDownloader pluginDownloader = mock(PluginDownloader.class); private PluginUninstaller pluginUninstaller = mock(PluginUninstaller.class); @@ -59,20 +57,18 @@ public class CancelAllActionTest { @Test public void request_fails_with_ForbiddenException_when_user_is_not_logged_in() { - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - - tester.newRequest().execute(); + assertThatThrownBy(() -> tester.newRequest().execute()) + .isInstanceOf(ForbiddenException.class) + .hasMessageContaining("Insufficient privileges"); } @Test public void request_fails_with_ForbiddenException_when_user_is_not_system_administrator() { userSessionRule.logIn().setNonSystemAdministrator(); - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - - tester.newRequest().execute(); + assertThatThrownBy(() -> tester.newRequest().execute()) + .isInstanceOf(ForbiddenException.class) + .hasMessageContaining("Insufficient privileges"); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/DownloadActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/DownloadActionTest.java index 62e2e72ff14..2a97714c6f3 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/DownloadActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/DownloadActionTest.java @@ -26,7 +26,6 @@ import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.sonar.api.server.ws.WebService; import org.sonar.core.platform.PluginInfo; @@ -49,8 +48,6 @@ public class DownloadActionTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private final ServerPluginRepository serverPluginRepository = mock(ServerPluginRepository.class); private final WsAction underTest = new DownloadAction(serverPluginRepository); diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/InstalledActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/InstalledActionTest.java index 8735161771b..55685e1c95d 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/InstalledActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/InstalledActionTest.java @@ -33,7 +33,6 @@ import java.util.Optional; import java.util.Random; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.sonar.api.server.ws.WebService; @@ -68,8 +67,6 @@ public class InstalledActionTest { " \"plugins\":" + "[]" + "}"; - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public TemporaryFolder temp = new TemporaryFolder(); @Rule diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/PendingActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/PendingActionTest.java index 793829c8f79..3db6fafd2b6 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/PendingActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/PendingActionTest.java @@ -24,7 +24,6 @@ import java.util.List; import java.util.Optional; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.core.platform.PluginInfo; import org.sonar.server.exceptions.ForbiddenException; @@ -41,6 +40,7 @@ import org.sonar.updatecenter.common.Version; import static com.google.common.collect.ImmutableList.of; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -49,8 +49,6 @@ import static org.sonar.test.JsonAssert.assertJson; public class PendingActionTest { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private PluginDownloader pluginDownloader = mock(PluginDownloader.class); private PluginUninstaller pluginUninstaller = mock(PluginUninstaller.class); @@ -71,18 +69,16 @@ public class PendingActionTest { @Test public void request_fails_with_ForbiddenException_when_user_is_not_logged_in() { - expectedException.expect(ForbiddenException.class); - - tester.newRequest().execute(); + assertThatThrownBy(() -> tester.newRequest().execute()) + .isInstanceOf(ForbiddenException.class); } @Test public void request_fails_with_ForbiddenException_when_user_is_not_system_administrator() { userSession.logIn().setNonSystemAdministrator(); - expectedException.expect(ForbiddenException.class); - - tester.newRequest().execute(); + assertThatThrownBy(() -> tester.newRequest().execute()) + .isInstanceOf(ForbiddenException.class); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/PluginUpdateAggregateBuilderTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/PluginUpdateAggregateBuilderTest.java index 906186e0ab3..07d24ac0e44 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/PluginUpdateAggregateBuilderTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/PluginUpdateAggregateBuilderTest.java @@ -26,6 +26,8 @@ import org.sonar.updatecenter.common.PluginUpdate; import org.sonar.updatecenter.common.Release; import org.sonar.updatecenter.common.Version; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + public class PluginUpdateAggregateBuilderTest { private static final Plugin PLUGIN_1 = Plugin.factory("key1"); @@ -33,16 +35,18 @@ public class PluginUpdateAggregateBuilderTest { private static final Version SOME_VERSION = Version.create("1.0"); private static final PluginUpdate.Status SOME_STATUS = PluginUpdate.Status.COMPATIBLE; - @Test(expected = NullPointerException.class) + @Test public void plugin_can_not_be_null_and_builderFor_enforces_it_with_NPE() { - PluginUpdateAggregateBuilder.builderFor(null); + assertThatThrownBy(() -> PluginUpdateAggregateBuilder.builderFor(null)) + .isInstanceOf(NullPointerException.class); } - @Test(expected = IllegalArgumentException.class) + @Test public void add_throws_IAE_when_plugin_is_not_equal_to_the_one_of_the_builder() { PluginUpdateAggregateBuilder builder = PluginUpdateAggregateBuilder.builderFor(PLUGIN_1); - builder.add(createPluginUpdate(PLUGIN_2)); + assertThatThrownBy(() -> builder.add(createPluginUpdate(PLUGIN_2))) + .isInstanceOf(IllegalArgumentException.class); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/UpdateActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/UpdateActionTest.java index 2b6cf4dca43..fe7e11e6d5f 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/UpdateActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/UpdateActionTest.java @@ -24,7 +24,6 @@ import java.util.Optional; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.plugins.PluginDownloader; @@ -40,6 +39,7 @@ import org.sonar.updatecenter.common.UpdateCenter; import org.sonar.updatecenter.common.Version; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -59,8 +59,6 @@ public class UpdateActionTest { private UpdateAction underTest = new UpdateAction(updateCenterFactory, pluginDownloader, userSessionRule); private WsActionTester tester = new WsActionTester(underTest); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Before public void setUp() { @@ -69,20 +67,18 @@ public class UpdateActionTest { @Test public void request_fails_with_ForbiddenException_when_user_is_not_logged_in() { - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - - tester.newRequest().execute(); + assertThatThrownBy(() -> tester.newRequest().execute()) + .isInstanceOf(ForbiddenException.class) + .hasMessageContaining("Insufficient privileges"); } @Test public void request_fails_with_ForbiddenException_when_user_is_not_system_administrator() { userSessionRule.logIn().setNonSystemAdministrator(); - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - - tester.newRequest().execute(); + assertThatThrownBy(() -> tester.newRequest().execute()) + .isInstanceOf(ForbiddenException.class) + .hasMessageContaining("Insufficient privileges"); } @Test @@ -104,21 +100,17 @@ public class UpdateActionTest { public void IAE_is_raised_when_key_param_is_not_provided() { logInAsSystemAdministrator(); - expectedException.expect(IllegalArgumentException.class); - - tester.newRequest().execute(); + assertThatThrownBy(() -> tester.newRequest().execute()) + .isInstanceOf(IllegalArgumentException.class); } @Test public void IAE_is_raised_when_there_is_no_plugin_update_for_the_key() { logInAsSystemAdministrator(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("No plugin with key 'pluginKey'"); - - tester.newRequest() - .setParam(KEY_PARAM, PLUGIN_KEY) - .execute(); + assertThatThrownBy(() -> tester.newRequest().setParam(KEY_PARAM, PLUGIN_KEY).execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("No plugin with key 'pluginKey'"); } @Test @@ -126,12 +118,9 @@ public class UpdateActionTest { logInAsSystemAdministrator(); when(updateCenterFactory.getUpdateCenter(anyBoolean())).thenReturn(Optional.empty()); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("No plugin with key 'pluginKey'"); - - tester.newRequest() - .setParam(KEY_PARAM, PLUGIN_KEY) - .execute(); + assertThatThrownBy(() -> tester.newRequest().setParam(KEY_PARAM, PLUGIN_KEY).execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("No plugin with key 'pluginKey'"); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/UpdatesActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/UpdatesActionTest.java index 8b4b214803b..dd0a0f7bc1d 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/UpdatesActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/plugins/ws/UpdatesActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.plugins.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.DateUtils; import org.sonar.server.exceptions.ForbiddenException; @@ -33,6 +32,7 @@ import org.sonar.updatecenter.common.Release; import static com.google.common.collect.ImmutableList.of; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.when; import static org.sonar.test.JsonAssert.assertJson; import static org.sonar.updatecenter.common.PluginUpdate.Status.COMPATIBLE; @@ -77,8 +77,6 @@ public class UpdatesActionTest extends AbstractUpdateCenterBasedPluginsWsActionT @Rule public UserSessionRule userSession = UserSessionRule.standalone(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private UpdatesAction underTest = new UpdatesAction(userSession, updateCenterFactory, new PluginUpdateAggregator()); private WsActionTester tester = new WsActionTester(underTest); @@ -94,17 +92,16 @@ public class UpdatesActionTest extends AbstractUpdateCenterBasedPluginsWsActionT @Test public void request_fails_with_ForbiddenException_when_user_is_not_logged_in() { - expectedException.expect(ForbiddenException.class); - - tester.newRequest().execute(); + assertThatThrownBy(() -> tester.newRequest().execute()) + .isInstanceOf(ForbiddenException.class); } @Test public void request_fails_with_ForbiddenException_when_user_is_not_system_administrator() { userSession.logIn(); - expectedException.expect(ForbiddenException.class); - tester.newRequest().execute(); + assertThatThrownBy(() -> tester.newRequest().execute()) + .isInstanceOf(ForbiddenException.class); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projectanalysis/ws/CreateEventActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projectanalysis/ws/CreateEventActionTest.java index f89cbed299d..85af2f1f553 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projectanalysis/ws/CreateEventActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projectanalysis/ws/CreateEventActionTest.java @@ -24,7 +24,6 @@ import java.util.Optional; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.api.web.UserRole; @@ -46,6 +45,7 @@ import org.sonarqube.ws.ProjectAnalyses; import org.sonarqube.ws.ProjectAnalyses.CreateEventResponse; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.db.component.ComponentTesting.newPrivateProjectDto; @@ -60,8 +60,6 @@ import static org.sonarqube.ws.client.WsRequest.Method.POST; public class CreateEventActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -231,20 +229,18 @@ public class CreateEventActionTest { SnapshotDto analysis = db.components().insertSnapshot(project); logInAsProjectAdministrator(project); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The 'name' parameter is missing"); - - call(OTHER.name(), " ", analysis.getUuid()); + assertThatThrownBy(() -> call(OTHER.name(), " ", analysis.getUuid())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("The 'name' parameter is missing"); } @Test public void fail_if_analysis_is_not_found() { userSession.logIn(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Analysis 'A42' not found"); - - call(OTHER.name(), "Project Import", "A42"); + assertThatThrownBy(() -> call(OTHER.name(), "Project Import", "A42")) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("Analysis 'A42' not found"); } @Test @@ -254,10 +250,9 @@ public class CreateEventActionTest { logInAsProjectAdministrator(project); call(VERSION.name(), "5.6.3", analysis.getUuid()); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("A version event already exists on analysis '" + analysis.getUuid() + "'"); - - call(VERSION.name(), "6.3", analysis.getUuid()); + assertThatThrownBy(() -> call(VERSION.name(), "6.3", analysis.getUuid())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("A version event already exists on analysis '" + analysis.getUuid() + "'"); } @Test @@ -267,10 +262,9 @@ public class CreateEventActionTest { logInAsProjectAdministrator(project); call(OTHER.name(), "Project Import", analysis.getUuid()); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("An 'Other' event with the same name already exists on analysis '" + analysis.getUuid() + "'"); - - call(OTHER.name(), "Project Import", analysis.getUuid()); + assertThatThrownBy(() -> call(OTHER.name(), "Project Import", analysis.getUuid())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("An 'Other' event with the same name already exists on analysis '" + analysis.getUuid() + "'"); } @Test @@ -279,12 +273,12 @@ public class CreateEventActionTest { SnapshotDto analysis = db.components().insertSnapshot(project); logInAsProjectAdministrator(project); - expectedException.expect(IllegalArgumentException.class); - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_ANALYSIS, analysis.getUuid()) .setParam(PARAM_NAME, "Project Import") .setParam(PARAM_CATEGORY, "QP") - .execute(); + .execute()) + .isInstanceOf(IllegalArgumentException.class); } @Test @@ -293,10 +287,9 @@ public class CreateEventActionTest { SnapshotDto analysis = db.components().insertSnapshot(application); logInAsProjectAdministrator(application); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("A version event must be created on a project"); - - call(VERSION.name(), "5.6.3", analysis.getUuid()); + assertThatThrownBy(() -> call(VERSION.name(), "5.6.3", analysis.getUuid())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("A version event must be created on a project"); } @Test @@ -305,10 +298,9 @@ public class CreateEventActionTest { SnapshotDto analysis = dbClient.snapshotDao().insert(dbSession, newSnapshot().setUuid("A1")); db.commit(); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Project of analysis 'A1' not found"); - - call(VERSION.name(), "5.6.3", analysis.getUuid()); + assertThatThrownBy(() -> call(VERSION.name(), "5.6.3", analysis.getUuid())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Project of analysis 'A1' not found"); } @Test @@ -316,10 +308,9 @@ public class CreateEventActionTest { SnapshotDto analysis = db.components().insertProjectAndSnapshot(newPrivateProjectDto("P1")); userSession.logIn(); - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - - call(VERSION.name(), "5.6.3", analysis.getUuid()); + assertThatThrownBy(() -> call(VERSION.name(), "5.6.3", analysis.getUuid())) + .isInstanceOf(ForbiddenException.class) + .hasMessageContaining("Insufficient privileges"); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projectanalysis/ws/DeleteActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projectanalysis/ws/DeleteActionTest.java index 924f6c18eef..7417a87b49b 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projectanalysis/ws/DeleteActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projectanalysis/ws/DeleteActionTest.java @@ -22,13 +22,11 @@ package org.sonar.server.projectanalysis.ws; import org.apache.commons.lang.RandomStringUtils; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.api.web.UserRole; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.DbTester; -import org.sonar.db.component.BranchDto; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.SnapshotDto; import org.sonar.db.newcodeperiod.NewCodePeriodDto; @@ -40,17 +38,14 @@ import org.sonar.server.ws.WsActionTester; import static com.google.common.collect.Lists.newArrayList; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; -import static org.sonar.db.component.BranchType.BRANCH; -import static org.sonar.db.component.ComponentTesting.newBranchDto; import static org.sonar.db.component.SnapshotDto.STATUS_PROCESSED; import static org.sonar.db.component.SnapshotDto.STATUS_UNPROCESSED; import static org.sonar.db.component.SnapshotTesting.newAnalysis; import static org.sonar.server.projectanalysis.ws.ProjectAnalysesWsParameters.PARAM_ANALYSIS; public class DeleteActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -90,10 +85,9 @@ public class DeleteActionTest { db.components().insertSnapshot(newAnalysis(project).setUuid("A1").setLast(true)); logInAsProjectAdministrator(project); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The last analysis 'A1' cannot be deleted"); - - call("A1"); + assertThatThrownBy(() -> call("A1")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("The last analysis 'A1' cannot be deleted"); } @Test @@ -109,20 +103,18 @@ public class DeleteActionTest { db.commit(); logInAsProjectAdministrator(project); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The analysis '" + analysisUuid + "' can not be deleted because it is set as a new code period baseline"); - - call(analysisUuid); + assertThatThrownBy(() -> call(analysisUuid)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("The analysis '" + analysisUuid + "' can not be deleted because it is set as a new code period baseline"); } @Test public void fail_when_analysis_not_found() { userSession.logIn().setRoot(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Analysis 'A42' not found"); - - call("A42"); + assertThatThrownBy(() -> call("A42")) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("Analysis 'A42' not found"); } @Test @@ -131,10 +123,9 @@ public class DeleteActionTest { db.components().insertSnapshot(newAnalysis(project).setUuid("A1").setLast(false).setStatus(STATUS_UNPROCESSED)); logInAsProjectAdministrator(project); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Analysis 'A1' not found"); - - call("A1"); + assertThatThrownBy(() -> call("A1")) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("Analysis 'A1' not found"); } @Test @@ -143,9 +134,8 @@ public class DeleteActionTest { db.components().insertSnapshot(newAnalysis(project).setUuid("A1").setLast(false)); userSession.logIn(); - expectedException.expect(ForbiddenException.class); - - call("A1"); + assertThatThrownBy(() -> call("A1")) + .isInstanceOf(ForbiddenException.class); } private void call(String analysis) { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projectanalysis/ws/DeleteEventActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projectanalysis/ws/DeleteEventActionTest.java index 170cdfef02b..750a5d5838b 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projectanalysis/ws/DeleteEventActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projectanalysis/ws/DeleteEventActionTest.java @@ -23,7 +23,6 @@ import java.util.List; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.api.web.UserRole; @@ -41,6 +40,7 @@ import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.db.component.ComponentTesting.newPrivateProjectDto; import static org.sonar.db.component.SnapshotTesting.newAnalysis; import static org.sonar.db.event.EventTesting.newEvent; @@ -48,8 +48,6 @@ import static org.sonar.server.projectanalysis.ws.EventCategory.VERSION; import static org.sonar.server.projectanalysis.ws.ProjectAnalysesWsParameters.PARAM_EVENT; public class DeleteEventActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -93,10 +91,9 @@ public class DeleteEventActionTest { db.events().insertEvent(newEvent(analysis).setUuid("E1").setCategory(VERSION.getLabel())); logInAsProjectAdministrator(project); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Cannot delete the version event of last analysis"); - - call("E1"); + assertThatThrownBy(() -> call("E1")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Cannot delete the version event of last analysis"); } @Test @@ -106,18 +103,16 @@ public class DeleteEventActionTest { db.events().insertEvent(newEvent(analysis).setUuid("E1").setCategory("Profile")); logInAsProjectAdministrator(project); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Event of category 'QUALITY_PROFILE' cannot be modified. Authorized categories: VERSION, OTHER"); - - call("E1"); + assertThatThrownBy(() -> call("E1")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Event of category 'QUALITY_PROFILE' cannot be modified."); } @Test public void fail_if_event_does_not_exist() { - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("E42' not found"); - - call("E42"); + assertThatThrownBy(() -> call("E42")) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("E42' not found"); } @Test @@ -126,16 +121,14 @@ public class DeleteEventActionTest { db.events().insertEvent(newEvent(analysis).setUuid("E1")); userSession.logIn(); - expectedException.expect(ForbiddenException.class); - - call("E1"); + assertThatThrownBy(() -> call("E1")) + .isInstanceOf(ForbiddenException.class); } @Test public void fail_if_event_not_provided() { - expectedException.expect(IllegalArgumentException.class); - - call(null); + assertThatThrownBy(() -> call(null)) + .isInstanceOf(IllegalArgumentException.class); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projectanalysis/ws/EventValidatorTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projectanalysis/ws/EventValidatorTest.java index 2e39e565705..89d29b3fe7a 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projectanalysis/ws/EventValidatorTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projectanalysis/ws/EventValidatorTest.java @@ -19,26 +19,22 @@ */ package org.sonar.server.projectanalysis.ws; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.db.component.ComponentTesting; import org.sonar.db.event.EventDto; import org.sonar.db.event.EventTesting; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.db.component.SnapshotTesting.newAnalysis; import static org.sonar.server.projectanalysis.ws.EventCategory.QUALITY_GATE; public class EventValidatorTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void fail_with_WS_categories() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Event of category 'QUALITY_GATE' cannot be modified. Authorized categories: VERSION, OTHER"); - - EventValidator.checkModifiable().accept(newEvent().setCategory(QUALITY_GATE.getLabel())); + assertThatThrownBy(() -> EventValidator.checkModifiable().accept(newEvent().setCategory(QUALITY_GATE.getLabel()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Event of category 'QUALITY_GATE' cannot be modified."); } private EventDto newEvent() { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projectanalysis/ws/SetBaselineActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projectanalysis/ws/SetBaselineActionTest.java index e711d809661..246b6b4d7e6 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projectanalysis/ws/SetBaselineActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projectanalysis/ws/SetBaselineActionTest.java @@ -29,7 +29,6 @@ import java.util.Map; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; @@ -52,18 +51,16 @@ import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.db.newcodeperiod.NewCodePeriodType.SPECIFIC_ANALYSIS; import static org.sonar.server.projectanalysis.ws.ProjectAnalysesWsParameters.PARAM_ANALYSIS; import static org.sonar.server.projectanalysis.ws.ProjectAnalysesWsParameters.PARAM_BRANCH; import static org.sonar.server.projectanalysis.ws.ProjectAnalysesWsParameters.PARAM_PROJECT; -import static org.sonar.test.Matchers.regexMatcher; import static org.sonarqube.ws.client.WsRequest.Method.POST; @RunWith(DataProviderRunner.class) public class SetBaselineActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @@ -119,19 +116,17 @@ public class SetBaselineActionTest { ComponentDto project = tester.insertPrivateProject(); SnapshotDto analysis = db.components().insertSnapshot(project); - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - - call(project.getKey(), "master", analysis.getUuid()); + assertThatThrownBy(() -> call(project.getKey(), "master", analysis.getUuid())) + .isInstanceOf(ForbiddenException.class) + .hasMessage("Insufficient privileges"); } @Test @UseDataProvider("missingOrEmptyParamsAndFailureMessage") public void fail_with_IAE_when_required_param_missing_or_empty(Map params, String message) { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(message); - - call(params); + assertThatThrownBy(() -> call(params)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage(message); } @DataProvider @@ -162,10 +157,8 @@ public class SetBaselineActionTest { params.put(PARAM_ANALYSIS, analysis.getUuid()); params.putAll(nonexistentParams); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(regexMatcher(regex)); - - call(params); + assertThatThrownBy(() -> call(params)) + .isInstanceOf(NotFoundException.class); } @DataProvider @@ -188,10 +181,9 @@ public class SetBaselineActionTest { ComponentDto otherProject = tester.insertPrivateProjectWithCustomBranch("main"); BranchDto branchOfOtherProject = branchDao.selectByUuid(dbSession, otherProject.uuid()).get(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(String.format("Branch '%s' in project '%s' not found", branchOfOtherProject.getKey(), project.getKey())); - - call(project.getKey(), branchOfOtherProject.getKey(), analysis.getUuid()); + assertThatThrownBy(() -> call(project.getKey(), branchOfOtherProject.getKey(), analysis.getUuid())) + .isInstanceOf(NotFoundException.class) + .hasMessage(String.format("Branch '%s' in project '%s' not found", branchOfOtherProject.getKey(), project.getKey())); } @Test @@ -202,11 +194,10 @@ public class SetBaselineActionTest { ComponentDto otherProject = ComponentTesting.newPrivateProjectDto(); SnapshotDto otherAnalysis = db.components().insertProjectAndSnapshot(otherProject); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(String.format("Analysis '%s' does not belong to branch '%s' of project '%s'", - otherAnalysis.getUuid(), "branch1", project.getKey())); - - call(project.getKey(), "branch1", otherAnalysis.getUuid()); + assertThatThrownBy(() -> call(project.getKey(), "branch1", otherAnalysis.getUuid())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage(String.format("Analysis '%s' does not belong to branch '%s' of project '%s'", + otherAnalysis.getUuid(), "branch1", project.getKey())); } @Test @@ -218,11 +209,10 @@ public class SetBaselineActionTest { ComponentDto otherProject = ComponentTesting.newPrivateProjectDto(); SnapshotDto otherAnalysis = db.components().insertProjectAndSnapshot(otherProject); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(String.format("Analysis '%s' does not belong to branch '%s' of project '%s'", - otherAnalysis.getUuid(), "branch1", project.getKey())); - - call(project.getKey(), "branch1", otherAnalysis.getUuid()); + assertThatThrownBy(() -> call(project.getKey(), "branch1", otherAnalysis.getUuid())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage(String.format("Analysis '%s' does not belong to branch '%s' of project '%s'", + otherAnalysis.getUuid(), "branch1", project.getKey())); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projectanalysis/ws/UnsetBaselineActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projectanalysis/ws/UnsetBaselineActionTest.java index fd2c4dbd97c..ea02e9e1a53 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projectanalysis/ws/UnsetBaselineActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projectanalysis/ws/UnsetBaselineActionTest.java @@ -27,7 +27,6 @@ import java.util.Optional; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; @@ -52,6 +51,7 @@ import org.sonar.server.ws.WsActionTester; import static java.util.Optional.ofNullable; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.server.projectanalysis.ws.ProjectAnalysesWsParameters.PARAM_BRANCH; import static org.sonar.server.projectanalysis.ws.ProjectAnalysesWsParameters.PARAM_PROJECT; import static org.sonarqube.ws.client.WsRequest.Method.POST; @@ -59,8 +59,6 @@ import static org.sonarqube.ws.client.WsRequest.Method.POST; @RunWith(DataProviderRunner.class) public class UnsetBaselineActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @@ -131,10 +129,9 @@ public class UnsetBaselineActionTest { ComponentDto project = db.components().insertPublicProject(); db.components().insertProjectBranch(project); - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - - call(project.getKey(), null); + assertThatThrownBy(() -> call(project.getKey(), null)) + .isInstanceOf(ForbiddenException.class) + .hasMessage("Insufficient privileges"); } @Test @@ -142,10 +139,9 @@ public class UnsetBaselineActionTest { ComponentDto project = db.components().insertPublicProject(); ComponentDto branch = db.components().insertProjectBranch(project); - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - - call(project.getKey(), branch.getBranch()); + assertThatThrownBy(() -> call(project.getKey(), branch.getBranch())) + .isInstanceOf(ForbiddenException.class) + .hasMessage("Insufficient privileges"); } @Test @@ -155,10 +151,9 @@ public class UnsetBaselineActionTest { db.components().insertProjectBranch(project); logInAsProjectAdministrator(project); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The 'project' parameter is missing"); - - call(null, branchParam); + assertThatThrownBy(() -> call(null, branchParam)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("The 'project' parameter is missing"); } @Test @@ -168,10 +163,9 @@ public class UnsetBaselineActionTest { db.components().insertProjectBranch(project); logInAsProjectAdministrator(project); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The 'project' parameter is missing"); - - call("", branchParam); + assertThatThrownBy(() -> call("", branchParam)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("The 'project' parameter is missing"); } @DataProvider @@ -217,10 +211,9 @@ public class UnsetBaselineActionTest { ComponentDto otherBranch = db.components().insertProjectBranch(otherProject); logInAsProjectAdministrator(project); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(String.format("Branch '%s' in project '%s' not found", otherBranch.getKey(), project.getKey())); - - call(project.getKey(), otherBranch.getKey()); + assertThatThrownBy(() -> call(project.getKey(), otherBranch.getKey())) + .isInstanceOf(NotFoundException.class) + .hasMessage(String.format("Branch '%s' in project '%s' not found", otherBranch.getKey(), project.getKey())); } @Test @@ -229,10 +222,9 @@ public class UnsetBaselineActionTest { ComponentDto pullRequest = db.components().insertProjectBranch(project, b -> b.setBranchType(BranchType.PULL_REQUEST)); logInAsProjectAdministrator(project); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(String.format("Branch '%s' in project '%s' not found", pullRequest.getKey(), project.getKey())); - - call(project.getKey(), pullRequest.getKey()); + assertThatThrownBy(() -> call(project.getKey(), pullRequest.getKey())) + .isInstanceOf(NotFoundException.class) + .hasMessage(String.format("Branch '%s' in project '%s' not found", pullRequest.getKey(), project.getKey())); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projectanalysis/ws/UpdateEventActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projectanalysis/ws/UpdateEventActionTest.java index 2fc92bed1fd..8de27e05be4 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projectanalysis/ws/UpdateEventActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projectanalysis/ws/UpdateEventActionTest.java @@ -22,7 +22,6 @@ package org.sonar.server.projectanalysis.ws; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.api.web.UserRole; @@ -44,21 +43,20 @@ import org.sonarqube.ws.ProjectAnalyses.UpdateEventResponse; import static java.util.Optional.ofNullable; import static org.apache.commons.lang.StringUtils.repeat; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.db.component.SnapshotTesting.newAnalysis; import static org.sonar.db.event.EventTesting.newEvent; -import static org.sonar.test.JsonAssert.assertJson; -import static org.sonarqube.ws.client.WsRequest.Method.POST; import static org.sonar.server.projectanalysis.ws.EventCategory.OTHER; import static org.sonar.server.projectanalysis.ws.EventCategory.VERSION; import static org.sonar.server.projectanalysis.ws.ProjectAnalysesWsParameters.PARAM_EVENT; import static org.sonar.server.projectanalysis.ws.ProjectAnalysesWsParameters.PARAM_NAME; +import static org.sonar.test.JsonAssert.assertJson; +import static org.sonarqube.ws.client.WsRequest.Method.POST; public class UpdateEventActionTest { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Rule public DbTester db = DbTester.create(System2.INSTANCE); private final DbClient dbClient = db.getDbClient(); @@ -166,19 +164,17 @@ public class UpdateEventActionTest { db.events().insertEvent(newEvent(analysis).setUuid("E1")); userSession.logIn().addProjectPermission(UserRole.USER, project); - expectedException.expect(ForbiddenException.class); - - call("E1", "name"); + assertThatThrownBy(() -> call("E1", "name")) + .isInstanceOf(ForbiddenException.class); } @Test public void fail_if_event_is_not_found() { userSession.logIn().setSystemAdministrator(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Event 'E42' not found"); - - call("E42", "name"); + assertThatThrownBy(() -> call("E42", "name")) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("Event 'E42' not found"); } @Test @@ -186,9 +182,9 @@ public class UpdateEventActionTest { SnapshotDto analysis = createAnalysisAndLogInAsProjectAdministrator("5.6"); db.events().insertEvent(newEvent(analysis).setUuid("E1")); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The 'name' parameter is missing"); - call("E1", null); + assertThatThrownBy(() -> call("E1", null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("The 'name' parameter is missing"); } @Test @@ -196,10 +192,9 @@ public class UpdateEventActionTest { SnapshotDto analysis = createAnalysisAndLogInAsProjectAdministrator("5.6"); db.events().insertEvent(newEvent(analysis).setUuid("E1")); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("A non empty name is required"); - - call("E1", " "); + assertThatThrownBy(() -> call("E1", " ")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("A non empty name is required"); } @Test @@ -207,10 +202,9 @@ public class UpdateEventActionTest { SnapshotDto analysis = createAnalysisAndLogInAsProjectAdministrator("5.6"); db.events().insertEvent(newEvent(analysis).setUuid("E1").setCategory("Profile")); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Event of category 'QUALITY_PROFILE' cannot be modified. Authorized categories: VERSION, OTHER"); - - call("E1", "name"); + assertThatThrownBy(() -> call("E1", "name")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Event of category 'QUALITY_PROFILE' cannot be modified."); } @Test @@ -219,10 +213,9 @@ public class UpdateEventActionTest { db.events().insertEvent(newEvent(analysis).setUuid("E1").setCategory(OTHER.getLabel()).setName("E1 name")); db.events().insertEvent(newEvent(analysis).setUuid("E2").setCategory(OTHER.getLabel()).setName("E2 name")); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("An 'Other' event with the same name already exists on analysis '" + analysis.getUuid() + "'"); - - call("E2", "E1 name"); + assertThatThrownBy(() -> call("E2", "E1 name")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("An 'Other' event with the same name already exists on analysis '" + analysis.getUuid() + "'"); } @Test @@ -235,10 +228,11 @@ public class UpdateEventActionTest { call("E1", repeat("a", 101)); call("E2", repeat("a", 100)); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Event name length (101) is longer than the maximum authorized (100). 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' was provided"); - call("E2", repeat("a", 101)); + assertThatThrownBy(() -> call("E2", repeat("a", 101))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Event name length (101) is longer than the maximum authorized (100). " + + "'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' was provided"); } private UpdateEventResponse call(@Nullable String eventUuid, @Nullable String name) { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projectdump/ws/ExportActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projectdump/ws/ExportActionTest.java index 5fdd7ece8ee..87cac9b616e 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projectdump/ws/ExportActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projectdump/ws/ExportActionTest.java @@ -22,7 +22,6 @@ package org.sonar.server.projectdump.ws; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.resources.Qualifiers; import org.sonar.api.web.UserRole; import org.sonar.ce.task.CeTask; @@ -40,6 +39,7 @@ import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.db.component.ComponentTesting.newPrivateProjectDto; @@ -55,8 +55,6 @@ public class ExportActionTest { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Rule public DbTester db = DbTester.create(); private final ExportSubmitter exportSubmitter = mock(ExportSubmitter.class); @@ -80,19 +78,17 @@ public class ExportActionTest { public void fails_if_missing_project_key() { logInAsProjectAdministrator("foo"); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The 'key' parameter is missing"); - - actionTester.newRequest().setMethod("POST").execute(); + assertThatThrownBy(() -> actionTester.newRequest().setMethod("POST").execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("The 'key' parameter is missing"); } @Test public void fails_if_not_project_administrator() { userSession.logIn(); - expectedException.expect(ForbiddenException.class); - - actionTester.newRequest().setMethod("POST").setParam("key", project.getDbKey()).execute(); + assertThatThrownBy(() -> actionTester.newRequest().setMethod("POST").setParam("key", project.getDbKey()).execute()) + .isInstanceOf(ForbiddenException.class); } @Test @@ -110,10 +106,9 @@ public class ExportActionTest { public void fails_to_trigger_task_if_anonymous() { userSession.anonymous(); - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - - actionTester.newRequest().setMethod("POST").setParam("key", project.getDbKey()).execute(); + assertThatThrownBy(() -> actionTester.newRequest().setMethod("POST").setParam("key", project.getDbKey()).execute()) + .isInstanceOf(ForbiddenException.class) + .hasMessage("Insufficient privileges"); } @Test @@ -133,12 +128,13 @@ public class ExportActionTest { ComponentDto branch = db.components().insertProjectBranch(project); userSession.logIn().addProjectPermission(UserRole.ADMIN, project); - expectedException.expect(NotFoundException.class); - - actionTester.newRequest() - .setMethod("POST") - .setParam("key", branch.getDbKey()) - .execute(); + assertThatThrownBy(() -> { + actionTester.newRequest() + .setMethod("POST") + .setParam("key", branch.getDbKey()) + .execute(); + }) + .isInstanceOf(NotFoundException.class); } private void logInAsProjectAdministrator(String login) { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projectdump/ws/StatusActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projectdump/ws/StatusActionTest.java index b76c9562301..d023d95a10a 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projectdump/ws/StatusActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projectdump/ws/StatusActionTest.java @@ -29,7 +29,6 @@ import org.junit.AfterClass; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.config.Configuration; import org.sonar.api.utils.System2; import org.sonar.api.web.UserRole; @@ -49,6 +48,7 @@ import org.sonar.server.ws.WsActionTester; import static java.util.Comparator.reverseOrder; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.api.resources.Qualifiers.PROJECT; @@ -64,8 +64,6 @@ public class StatusActionTest { @Rule public DbTester db = DbTester.create(System2.INSTANCE); @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Rule public UserSessionRule userSession = UserSessionRule.standalone(); private final DbClient dbClient = db.getDbClient(); @@ -100,42 +98,46 @@ public class StatusActionTest { @Test public void fails_with_BRE_if_no_param_is_provided() { - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Project id or project key must be provided, not both."); - - underTest.newRequest().execute(); + assertThatThrownBy(() -> underTest.newRequest().execute()) + .isInstanceOf(BadRequestException.class) + .hasMessage("Project id or project key must be provided, not both."); } @Test public void fails_with_BRE_if_both_params_are_provided() { - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Project id or project key must be provided, not both."); - - underTest.newRequest() - .setParam(ID_PARAM, SOME_UUID).setParam(KEY_PARAM, SOME_KEY) - .execute(); + assertThatThrownBy(() -> { + underTest.newRequest() + .setParam(ID_PARAM, SOME_UUID).setParam(KEY_PARAM, SOME_KEY) + .execute(); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Project id or project key must be provided, not both."); } @Test public void fails_with_NFE_if_component_with_uuid_does_not_exist() { String UNKOWN_UUID = "UNKOWN_UUID"; - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Project '" + UNKOWN_UUID + "' not found"); - underTest.newRequest() - .setParam(ID_PARAM, UNKOWN_UUID) - .execute(); + assertThatThrownBy(() -> { + underTest.newRequest() + .setParam(ID_PARAM, UNKOWN_UUID) + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("Project '" + UNKOWN_UUID + "' not found"); } @Test public void fails_with_NFE_if_component_with_key_does_not_exist() { String UNKNOWN_KEY = "UNKNOWN_KEY"; - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Project '" + UNKNOWN_KEY + "' not found"); - underTest.newRequest() - .setParam(KEY_PARAM, UNKNOWN_KEY) - .execute(); + assertThatThrownBy(() -> { + underTest.newRequest() + .setParam(KEY_PARAM, UNKNOWN_KEY) + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("Project '" + UNKNOWN_KEY + "' not found"); } @Test @@ -261,11 +263,12 @@ public class StatusActionTest { ComponentDto project = db.components().insertPublicProject(); ComponentDto branch = db.components().insertProjectBranch(project); - expectedException.expect(NotFoundException.class); - - underTest.newRequest() - .setParam(KEY_PARAM, branch.getDbKey()) - .execute(); + assertThatThrownBy(() -> { + underTest.newRequest() + .setParam(KEY_PARAM, branch.getDbKey()) + .execute(); + }) + .isInstanceOf(NotFoundException.class); } @Test @@ -273,11 +276,12 @@ public class StatusActionTest { ComponentDto project = db.components().insertPublicProject(); ComponentDto branch = db.components().insertProjectBranch(project); - expectedException.expect(NotFoundException.class); - - underTest.newRequest() - .setParam(ID_PARAM, branch.uuid()) - .execute(); + assertThatThrownBy(() -> { + underTest.newRequest() + .setParam(ID_PARAM, branch.uuid()) + .execute(); + }) + .isInstanceOf(NotFoundException.class); } private ProjectDto insertProject(String uuid, String key) { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projectlink/ws/CreateActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projectlink/ws/CreateActionTest.java index e8e21d07261..3cb416fa1d8 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projectlink/ws/CreateActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projectlink/ws/CreateActionTest.java @@ -22,7 +22,6 @@ package org.sonar.server.projectlink.ws; import org.apache.commons.lang.StringUtils; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.api.web.UserRole; @@ -37,12 +36,12 @@ import org.sonar.server.component.TestComponentFinder; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.tester.UserSessionRule; -import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.ProjectLinks; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.server.projectlink.ws.ProjectLinksWsParameters.PARAM_NAME; import static org.sonar.server.projectlink.ws.ProjectLinksWsParameters.PARAM_PROJECT_ID; import static org.sonar.server.projectlink.ws.ProjectLinksWsParameters.PARAM_PROJECT_KEY; @@ -51,8 +50,6 @@ import static org.sonar.test.JsonAssert.assertJson; public class CreateActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -113,51 +110,50 @@ public class CreateActionTest { @Test public void fail_if_no_name() { - expectedException.expect(IllegalArgumentException.class); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_PROJECT_KEY, "unknown") .setParam(PARAM_URL, "http://example.org") - .execute(); + .execute()) + .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_if_long_name() { - expectedException.expect(IllegalArgumentException.class); - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_PROJECT_KEY, "unknown") .setParam(PARAM_NAME, StringUtils.leftPad("", 129, "*")) .setParam(PARAM_URL, "http://example.org") - .execute(); + .execute()) + .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_if_no_url() { - expectedException.expect(IllegalArgumentException.class); - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_PROJECT_KEY, "unknown") .setParam(PARAM_NAME, "Custom") - .execute(); + .execute()) + .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_if_long_url() { - expectedException.expect(IllegalArgumentException.class); - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_PROJECT_KEY, "unknown") .setParam(PARAM_NAME, "random") .setParam(PARAM_URL, StringUtils.leftPad("", 2049, "*")) - .execute(); + .execute()) + .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_when_no_project() { - expectedException.expect(NotFoundException.class); - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_PROJECT_KEY, "unknown") .setParam(PARAM_NAME, "Custom") .setParam(PARAM_URL, "http://example.org") - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class); } @Test @@ -166,13 +162,12 @@ public class CreateActionTest { ComponentDto project = db.components().insertPublicProject(); userSession.registerComponents(project); - expectedException.expect(ForbiddenException.class); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_PROJECT_KEY, project.getKey()) .setParam(PARAM_NAME, "Custom") .setParam(PARAM_URL, "http://example.org") - .execute(); + .execute()) + .isInstanceOf(ForbiddenException.class); } @Test @@ -180,13 +175,12 @@ public class CreateActionTest { userSession.logIn(); ComponentDto project = db.components().insertPrivateProject(); - expectedException.expect(ForbiddenException.class); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_PROJECT_KEY, project.getKey()) .setParam(PARAM_NAME, "Custom") .setParam(PARAM_URL, "http://example.org") - .execute(); + .execute()) + .isInstanceOf(ForbiddenException.class); } @Test @@ -227,14 +221,13 @@ public class CreateActionTest { userSession.logIn().addProjectPermission(UserRole.USER, project); ComponentDto branch = db.components().insertProjectBranch(project); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(format("Project '%s' not found", branch.getDbKey())); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_PROJECT_KEY, branch.getDbKey()) .setParam(PARAM_NAME, "Custom") .setParam(PARAM_URL, "http://example.org") - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining(format("Project '%s' not found", branch.getDbKey())); } @Test @@ -243,14 +236,13 @@ public class CreateActionTest { userSession.logIn().addProjectPermission(UserRole.USER, project); ComponentDto branch = db.components().insertProjectBranch(project); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(format("Project '%s' not found", branch.uuid())); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_PROJECT_ID, branch.uuid()) .setParam(PARAM_NAME, "Custom") .setParam(PARAM_URL, "http://example.org") - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining(format("Project '%s' not found", branch.uuid())); } @Test @@ -266,29 +258,25 @@ public class CreateActionTest { private void failIfNotAProjectWithKey(ComponentDto root, ComponentDto component) { userSession.logIn().addProjectPermission(UserRole.ADMIN, root); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Project '" + component.getDbKey() + "' not found"); - - TestRequest testRequest = ws.newRequest(); - testRequest.setParam(PARAM_PROJECT_KEY, component.getDbKey()); - testRequest + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_NAME, "Custom") .setParam(PARAM_URL, "http://example.org") - .execute(); + .setParam(PARAM_PROJECT_KEY, component.getDbKey()) + .execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("Project '" + component.getDbKey() + "' not found"); } private void failIfNotAProjectWithUuid(ComponentDto root, ComponentDto component) { userSession.logIn().addProjectPermission(UserRole.ADMIN, root); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Project '" + component.uuid() + "' not found"); - - TestRequest testRequest = ws.newRequest(); - testRequest.setParam(PARAM_PROJECT_ID, component.uuid()); - testRequest + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_NAME, "Custom") .setParam(PARAM_URL, "http://example.org") - .execute(); + .setParam(PARAM_PROJECT_ID, component.uuid()) + .execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("Project '" + component.uuid() + "' not found"); } private void createAndTest(ComponentDto project, String name, String url, String type) { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projectlink/ws/DeleteActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projectlink/ws/DeleteActionTest.java index 1876960e31d..bec997c7c26 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projectlink/ws/DeleteActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projectlink/ws/DeleteActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.projectlink.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.db.DbClient; @@ -37,13 +36,12 @@ import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.web.UserRole.ADMIN; import static org.sonar.server.projectlink.ws.ProjectLinksWsParameters.PARAM_ID; public class DeleteActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -97,20 +95,18 @@ public class DeleteActionTest { ProjectLinkDto link = db.componentLinks().insertProvidedLink(project); logInAsProjectAdministrator(project); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Provided link cannot be deleted"); - - deleteLink(link); + assertThatThrownBy(() -> deleteLink(link)) + .isInstanceOf(BadRequestException.class) + .hasMessageContaining("Provided link cannot be deleted"); } @Test public void fail_on_unknown_link() { - expectedException.expect(NotFoundException.class); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setMethod("POST") .setParam(PARAM_ID, "UNKNOWN") - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class); } @Test @@ -119,9 +115,8 @@ public class DeleteActionTest { ProjectLinkDto link = db.componentLinks().insertCustomLink(project); userSession.anonymous(); - expectedException.expect(ForbiddenException.class); - - deleteLink(link); + assertThatThrownBy(() -> deleteLink(link)) + .isInstanceOf(ForbiddenException.class); } @Test @@ -130,8 +125,8 @@ public class DeleteActionTest { ProjectLinkDto link = db.componentLinks().insertCustomLink(project); userSession.logIn(); - expectedException.expect(ForbiddenException.class); - deleteLink(link); + assertThatThrownBy(() -> deleteLink(link)) + .isInstanceOf(ForbiddenException.class); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projectlink/ws/SearchActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projectlink/ws/SearchActionTest.java index e5b33937d3a..616944e3220 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projectlink/ws/SearchActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projectlink/ws/SearchActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.projectlink.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.api.web.UserRole; @@ -34,13 +33,13 @@ import org.sonar.server.component.TestComponentFinder; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.tester.UserSessionRule; -import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.ProjectLinks.Link; import org.sonarqube.ws.ProjectLinks.SearchWsResponse; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.server.projectlink.ws.ProjectLinksWsParameters.PARAM_PROJECT_ID; import static org.sonar.server.projectlink.ws.ProjectLinksWsParameters.PARAM_PROJECT_KEY; @@ -48,8 +47,6 @@ import static org.sonar.test.JsonAssert.assertJson; public class SearchActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -170,8 +167,8 @@ public class SearchActionTest { @Test public void fail_when_no_project() { - expectedException.expect(NotFoundException.class); - callByKey("unknown"); + assertThatThrownBy(() -> callByKey("unknown")) + .isInstanceOf(NotFoundException.class); } @Test @@ -210,9 +207,8 @@ public class SearchActionTest { userSession.anonymous(); ComponentDto project = db.components().insertPrivateProject(); - expectedException.expect(ForbiddenException.class); - - callByKey(project.getKey()); + assertThatThrownBy(() -> callByKey(project.getKey())) + .isInstanceOf(ForbiddenException.class); } @Test @@ -220,22 +216,22 @@ public class SearchActionTest { ComponentDto project = db.components().insertPrivateProject(); logInAsProjectAdministrator(project); - expectedException.expect(IllegalArgumentException.class); - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_PROJECT_KEY, project.getKey()) .setParam(PARAM_PROJECT_ID, project.uuid()) - .execute(); + .execute()) + .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_when_no_id_nor_key_are_provided() { ComponentDto project = db.components().insertPrivateProject(); - expectedException.expect(IllegalArgumentException.class); - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_PROJECT_KEY, project.getKey()) .setParam(PARAM_PROJECT_ID, project.uuid()) - .execute(); + .execute()) + .isInstanceOf(IllegalArgumentException.class); } @Test @@ -244,12 +240,11 @@ public class SearchActionTest { userSession.logIn().addProjectPermission(UserRole.USER, project); ComponentDto branch = db.components().insertProjectBranch(project); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(format("Project '%s' not found", branch.getDbKey())); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_PROJECT_KEY, branch.getDbKey()) - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining(format("Project '%s' not found", branch.getDbKey())); } @Test @@ -258,12 +253,11 @@ public class SearchActionTest { userSession.logIn().addProjectPermission(UserRole.USER, project); ComponentDto branch = db.components().insertProjectBranch(project); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(format("Project '%s' not found", branch.uuid())); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_PROJECT_ID, branch.uuid()) - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining(format("Project '%s' not found", branch.uuid())); } @Test @@ -295,22 +289,20 @@ public class SearchActionTest { private void failIfNotAProjectWithKey(ComponentDto root, ComponentDto component) { userSession.logIn().addProjectPermission(UserRole.ADMIN, root); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Project '" + component.getKey() + "' not found"); - - TestRequest testRequest = ws.newRequest(); - testRequest.setParam(PARAM_PROJECT_KEY, component.getDbKey()); - testRequest.execute(); + assertThatThrownBy(() -> ws.newRequest() + .setParam(PARAM_PROJECT_KEY, component.getDbKey()) + .execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("Project '" + component.getKey() + "' not found"); } private void failIfNotAProjectWithUuid(ComponentDto root, ComponentDto component) { userSession.logIn().addProjectPermission(UserRole.ADMIN, root); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Project '" + component.uuid() + "' not found"); - - TestRequest testRequest = ws.newRequest(); - testRequest.setParam(PARAM_PROJECT_ID, component.uuid()); - testRequest.execute(); + assertThatThrownBy(() -> ws.newRequest() + .setParam(PARAM_PROJECT_ID, component.uuid()) + .execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("Project '" + component.uuid() + "' not found"); } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projecttag/ws/SearchActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projecttag/ws/SearchActionTest.java index 0e330309cef..0cd2856e163 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projecttag/ws/SearchActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/projecttag/ws/SearchActionTest.java @@ -22,7 +22,6 @@ package org.sonar.server.projecttag.ws; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.db.component.ComponentDto; @@ -52,8 +51,6 @@ public class SearchActionTest { @Rule public EsTester es = EsTester.create(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/QualityGateConditionsUpdaterTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/QualityGateConditionsUpdaterTest.java index 12d5c47b31b..bcb8177935d 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/QualityGateConditionsUpdaterTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/QualityGateConditionsUpdaterTest.java @@ -24,7 +24,6 @@ import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.api.measures.Metric; import org.sonar.api.utils.System2; @@ -36,6 +35,7 @@ import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.NotFoundException; import static java.lang.String.format; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; import static org.sonar.api.measures.CoreMetrics.ALERT_STATUS_KEY; import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_HOTSPOTS_KEY; @@ -55,9 +55,6 @@ import static org.sonar.api.measures.Metric.ValueType.WORK_DUR; @RunWith(DataProviderRunner.class) public class QualityGateConditionsUpdaterTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Rule public DbTester db = DbTester.create(System2.INSTANCE); @@ -89,10 +86,9 @@ public class QualityGateConditionsUpdaterTest { MetricDto metric = insertMetric(RATING, SQALE_RATING_KEY); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("errorThreshold can not be null"); - - underTest.createCondition(db.getSession(), qualityGate, metric.getKey(), "GT", null); + assertThatThrownBy(() -> underTest.createCondition(db.getSession(), qualityGate, metric.getKey(), "GT", null)) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("errorThreshold can not be null"); } @Test @@ -101,20 +97,18 @@ public class QualityGateConditionsUpdaterTest { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); db.qualityGates().addCondition(qualityGate, metric); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage(format("Condition on metric '%s' already exists.", metric.getShortName())); - - underTest.createCondition(db.getSession(), qualityGate, metric.getKey(), "LT", "80"); + assertThatThrownBy(() -> underTest.createCondition(db.getSession(), qualityGate, metric.getKey(), "LT", "80")) + .isInstanceOf(BadRequestException.class) + .hasMessageContaining(format("Condition on metric '%s' already exists.", metric.getShortName())); } @Test public void fail_to_create_condition_on_missing_metric() { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("There is no metric with key=new_coverage"); - - underTest.createCondition(db.getSession(), qualityGate, "new_coverage", "LT", "80"); + assertThatThrownBy(() -> underTest.createCondition(db.getSession(), qualityGate, "new_coverage", "LT", "80")) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("There is no metric with key=new_coverage"); } @Test @@ -123,10 +117,9 @@ public class QualityGateConditionsUpdaterTest { MetricDto metric = db.measures().insertMetric(m -> m.setKey(metricKey).setValueType(valueType.name()).setHidden(hidden).setDirection(0)); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage(format("Metric '%s' cannot be used to define a condition", metric.getKey())); - - underTest.createCondition(db.getSession(), qualityGate, metric.getKey(), "LT", "80"); + assertThatThrownBy(() -> underTest.createCondition(db.getSession(), qualityGate, metric.getKey(), "LT", "80")) + .isInstanceOf(BadRequestException.class) + .hasMessageContaining(format("Metric '%s' cannot be used to define a condition", metric.getKey())); } @Test @@ -135,10 +128,9 @@ public class QualityGateConditionsUpdaterTest { MetricDto metric = db.measures().insertMetric(m -> m.setKey("key").setValueType(INT.name()).setHidden(false).setDirection(direction)); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage(format("Operator %s is not allowed for this metric.", operator)); - - underTest.createCondition(db.getSession(), qualityGate, metric.getKey(), operator, "90"); + assertThatThrownBy(() -> underTest.createCondition(db.getSession(), qualityGate, metric.getKey(), operator, "90")) + .isInstanceOf(BadRequestException.class) + .hasMessageContaining(format("Operator %s is not allowed for this metric.", operator)); } @Test @@ -156,10 +148,9 @@ public class QualityGateConditionsUpdaterTest { MetricDto metric = insertMetric(RATING, SQALE_RATING_KEY); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("'80' is not a valid rating"); - - underTest.createCondition(db.getSession(), qualityGate, metric.getKey(), "GT", "80"); + assertThatThrownBy(() -> underTest.createCondition(db.getSession(), qualityGate, metric.getKey(), "GT", "80")) + .isInstanceOf(BadRequestException.class) + .hasMessageContaining("'80' is not a valid rating"); } @Test @@ -167,10 +158,9 @@ public class QualityGateConditionsUpdaterTest { MetricDto metric = insertMetric(RATING, SQALE_RATING_KEY); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("There's no worse rating than E (5)"); - - underTest.createCondition(db.getSession(), qualityGate, metric.getKey(), "GT", "5"); + assertThatThrownBy(() -> underTest.createCondition(db.getSession(), qualityGate, metric.getKey(), "GT", "5")) + .isInstanceOf(BadRequestException.class) + .hasMessageContaining("There's no worse rating than E (5)"); } @Test @@ -190,10 +180,9 @@ public class QualityGateConditionsUpdaterTest { MetricDto metric = db.measures().insertMetric(m -> m.setValueType(valueType.name()).setHidden(false).setDirection(0)); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage(format("Invalid value '%s' for metric '%s'", value, metric.getShortName())); - - underTest.createCondition(db.getSession(), qualityGate, metric.getKey(), "LT", value); + assertThatThrownBy(() -> underTest.createCondition(db.getSession(), qualityGate, metric.getKey(), "LT", value)) + .isInstanceOf(BadRequestException.class) + .hasMessageContaining(format("Invalid value '%s' for metric '%s'", value, metric.getShortName())); } @Test @@ -215,10 +204,9 @@ public class QualityGateConditionsUpdaterTest { QualityGateConditionDto condition = db.qualityGates().addCondition(qualityGate, metric, c -> c.setOperator("LT").setErrorThreshold("80")); - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("errorThreshold can not be null"); - - underTest.updateCondition(db.getSession(), condition, metric.getKey(), "GT", null); + assertThatThrownBy(() -> underTest.updateCondition(db.getSession(), condition, metric.getKey(), "GT", null)) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("errorThreshold can not be null"); } @Test @@ -241,10 +229,9 @@ public class QualityGateConditionsUpdaterTest { QualityGateConditionDto condition = db.qualityGates().addCondition(qualityGate, metric, c -> c.setOperator(validOperator).setErrorThreshold("80")); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage(format("Operator %s is not allowed for this metric", updatedOperator)); - - underTest.updateCondition(db.getSession(), condition, metric.getKey(), updatedOperator, "70"); + assertThatThrownBy(() -> underTest.updateCondition(db.getSession(), condition, metric.getKey(), updatedOperator, "70")) + .isInstanceOf(BadRequestException.class) + .hasMessageContaining(format("Operator %s is not allowed for this metric", updatedOperator)); } @Test @@ -266,10 +253,9 @@ public class QualityGateConditionsUpdaterTest { QualityGateConditionDto condition = db.qualityGates().addCondition(qualityGate, metric, c -> c.setOperator("LT").setErrorThreshold("3")); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage(format("The metric '%s' cannot be used", metric.getShortName())); - - underTest.updateCondition(db.getSession(), condition, metric.getKey(), "GT", "4"); + assertThatThrownBy(() -> underTest.updateCondition(db.getSession(), condition, metric.getKey(), "GT", "4")) + .isInstanceOf(BadRequestException.class) + .hasMessageContaining(format("The metric '%s' cannot be used", metric.getShortName())); } @Test @@ -280,10 +266,9 @@ public class QualityGateConditionsUpdaterTest { QualityGateConditionDto condition = db.qualityGates().addCondition(qualityGate, metric, c -> c.setOperator("LT").setErrorThreshold("80")); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage(format("Metric '%s' cannot be used to define a condition", metric.getKey())); - - underTest.updateCondition(db.getSession(), condition, metric.getKey(), "GT", "60"); + assertThatThrownBy(() -> underTest.updateCondition(db.getSession(), condition, metric.getKey(), "GT", "60")) + .isInstanceOf(BadRequestException.class) + .hasMessageContaining(format("Metric '%s' cannot be used to define a condition", metric.getKey())); } @Test @@ -307,10 +292,9 @@ public class QualityGateConditionsUpdaterTest { QualityGateConditionDto condition = db.qualityGates().addCondition(qualityGate, metric, c -> c.setOperator("LT").setErrorThreshold("80")); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage(format("Invalid value '%s' for metric '%s'", value, metric.getShortName())); - - underTest.updateCondition(db.getSession(), condition, metric.getKey(), "LT", value); + assertThatThrownBy(() -> underTest.updateCondition(db.getSession(), condition, metric.getKey(), "LT", value)) + .isInstanceOf(BadRequestException.class) + .hasMessageContaining(format("Invalid value '%s' for metric '%s'", value, metric.getShortName())); } @DataProvider diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/QualityGateUpdaterTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/QualityGateUpdaterTest.java index 8e6d89015b0..5503644c422 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/QualityGateUpdaterTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/QualityGateUpdaterTest.java @@ -21,7 +21,6 @@ package org.sonar.server.qualitygate; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.utils.System2; import org.sonar.core.util.UuidFactoryFast; import org.sonar.db.DbClient; @@ -30,13 +29,12 @@ import org.sonar.db.DbTester; import org.sonar.db.qualitygate.QualityGateDto; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class QualityGateUpdaterTest { static final String QGATE_NAME = "Default"; - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester db = DbTester.create(System2.INSTANCE); @@ -61,9 +59,8 @@ public class QualityGateUpdaterTest { public void fail_to_create_when_name_already_exists() { underTest.create(dbSession, QGATE_NAME); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Name has already been taken"); - - underTest.create(dbSession, QGATE_NAME); + assertThatThrownBy(() -> underTest.create(dbSession, QGATE_NAME)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Name has already been taken"); } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/CopyActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/CopyActionTest.java index d97ac4c3e26..76b5f9cc55e 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/CopyActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/CopyActionTest.java @@ -25,7 +25,6 @@ import com.tngtech.java.junit.dataprovider.UseDataProvider; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; @@ -47,6 +46,7 @@ import org.sonarqube.ws.Qualitygates.QualityGate; import static java.util.Optional.ofNullable; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.AssertionsForClassTypes.tuple; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_GATES; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES; @@ -56,8 +56,6 @@ import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_NAM @RunWith(DataProviderRunner.class) public class CopyActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public final UserSessionRule userSession = UserSessionRule.standalone(); @@ -149,37 +147,34 @@ public class CopyActionTest { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); - expectedException.expect(ForbiddenException.class); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_ID, qualityGate.getUuid()) .setParam(PARAM_NAME, "new-name") - .execute(); + .execute()) + .isInstanceOf(ForbiddenException.class); } @Test public void fail_when_id_parameter_is_missing() { userSession.addPermission(ADMINISTER_QUALITY_GATES); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Either 'id' or 'sourceName' must be provided, and not both"); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_NAME, "new-name") - .execute(); + .execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Either 'id' or 'sourceName' must be provided, and not both"); } @Test public void fail_when_quality_gate_id_is_not_found() { userSession.addPermission(ADMINISTER_QUALITY_GATES); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("No quality gate has been found for id 123"); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_ID, "123") .setParam(PARAM_NAME, "new-name") - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("No quality gate has been found for id 123"); } @Test @@ -192,15 +187,14 @@ public class CopyActionTest { .setParam(PARAM_ID, qualityGate.getUuid()); ofNullable(nameParameter).ifPresent(t -> request.setParam(PARAM_NAME, t)); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The 'name' parameter is missing"); - - request.execute(); + assertThatThrownBy(() -> request.execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("The 'name' parameter is missing"); } @DataProvider public static Object[][] nullOrEmpty() { - return new Object[][] { + return new Object[][]{ {null}, {""}, {" "} @@ -213,12 +207,11 @@ public class CopyActionTest { QualityGateDto existingQualityGate = db.qualityGates().insertQualityGate(); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Name has already been taken"); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_ID, qualityGate.getUuid()) .setParam(PARAM_NAME, existingQualityGate.getName()) - .execute(); + .execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Name has already been taken"); } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/CreateActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/CreateActionTest.java index 504daa37059..0ce6a43accc 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/CreateActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/CreateActionTest.java @@ -26,7 +26,6 @@ import java.util.Optional; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; @@ -43,14 +42,13 @@ import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.Qualitygates.CreateResponse; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_GATES; import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_NAME; @RunWith(DataProviderRunner.class) public class CreateActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @@ -107,10 +105,9 @@ public class CreateActionTest { public void throw_ForbiddenException_if_not_gate_administrator() { userSession.logIn(); - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - - executeRequest("Default"); + assertThatThrownBy(() -> executeRequest("Default")) + .isInstanceOf(ForbiddenException.class) + .hasMessageContaining("Insufficient privileges"); } @Test @@ -119,10 +116,9 @@ public class CreateActionTest { executeRequest("Default"); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Name has already been taken"); - - executeRequest("Default"); + assertThatThrownBy(() -> executeRequest("Default")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Name has already been taken"); } @Test @@ -133,15 +129,14 @@ public class CreateActionTest { TestRequest request = ws.newRequest(); Optional.ofNullable(nameParameter).ifPresent(t -> request.setParam(PARAM_NAME, "")); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The 'name' parameter is missing"); - - request.execute(); + assertThatThrownBy(() -> request.execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("The 'name' parameter is missing"); } @DataProvider public static Object[][] nullOrEmpty() { - return new Object[][] { + return new Object[][]{ {null}, {""}, {" "} diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/CreateConditionActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/CreateConditionActionTest.java index c160570de2d..0509172a63e 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/CreateConditionActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/CreateConditionActionTest.java @@ -25,7 +25,6 @@ import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.ArrayList; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbClient; @@ -47,6 +46,7 @@ import org.sonarqube.ws.Qualitygates.CreateConditionResponse; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.api.measures.Metric.ValueType.INT; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_GATES; @@ -58,8 +58,6 @@ import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_OPE @RunWith(DataProviderRunner.class) public class CreateConditionActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @@ -112,15 +110,14 @@ public class CreateConditionActionTest { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(qg -> qg.setBuiltIn(true)); MetricDto metric = insertMetric(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(format("Operation forbidden for built-in Quality Gate '%s'", qualityGate.getName())); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_GATE_ID, qualityGate.getUuid()) .setParam(PARAM_METRIC, metric.getKey()) .setParam(PARAM_OPERATOR, "LT") .setParam(PARAM_ERROR, "90") - .execute(); + .execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(format("Operation forbidden for built-in Quality Gate '%s'", qualityGate.getName())); } @Test @@ -129,15 +126,14 @@ public class CreateConditionActionTest { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); MetricDto metric = db.measures().insertMetric(m -> m.setValueType(INT.name()).setHidden(false).setDirection(0)); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Value of parameter 'op' (ABC) must be one of: [LT, GT]"); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_GATE_ID, qualityGate.getUuid()) .setParam(PARAM_METRIC, metric.getKey()) .setParam(PARAM_OPERATOR, "ABC") .setParam(PARAM_ERROR, "90") - .execute(); + .execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Value of parameter 'op' (ABC) must be one of: [LT, GT]"); } @Test @@ -147,15 +143,14 @@ public class CreateConditionActionTest { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); MetricDto metric = db.measures().insertMetric(m -> m.setValueType(INT.name()).setHidden(false).setDirection(direction)); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage(format("Operator %s is not allowed for this metric.", operator)); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_GATE_ID, qualityGate.getUuid()) .setParam(PARAM_METRIC, metric.getKey()) .setParam(PARAM_OPERATOR, operator) .setParam(PARAM_ERROR, "90") - .execute(); + .execute()) + .isInstanceOf(BadRequestException.class) + .hasMessageContaining(format("Operator %s is not allowed for this metric.", operator)); } @Test @@ -221,15 +216,14 @@ public class CreateConditionActionTest { MetricDto metric = insertMetric(); userSession.logIn(); - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_GATE_ID, qualityGate.getUuid()) .setParam(PARAM_METRIC, metric.getKey()) .setParam(PARAM_OPERATOR, "LT") .setParam(PARAM_ERROR, "90") - .execute(); + .execute()) + .isInstanceOf(ForbiddenException.class) + .hasMessageContaining("Insufficient privileges"); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/DeleteConditionActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/DeleteConditionActionTest.java index 30c972b60ac..ed90d4c4d1d 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/DeleteConditionActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/DeleteConditionActionTest.java @@ -22,7 +22,6 @@ package org.sonar.server.qualitygate.ws; import java.util.Collection; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbTester; import org.sonar.db.metric.MetricDto; @@ -40,6 +39,7 @@ import org.sonar.server.ws.WsActionTester; import static java.lang.String.format; import static java.net.HttpURLConnection.HTTP_NO_CONTENT; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_GATES; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES; @@ -51,8 +51,6 @@ public class DeleteConditionActionTest { public DbTester db = DbTester.create(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private final WsActionTester ws = new WsActionTester( new DeleteConditionAction(db.getDbClient(), new QualityGatesWsSupport(db.getDbClient(), userSession, TestComponentFinder.from(db)))); @@ -137,12 +135,11 @@ public class DeleteConditionActionTest { MetricDto metric = db.measures().insertMetric(); QualityGateConditionDto qualityGateCondition = db.qualityGates().addCondition(qualityGate, metric); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(format("Operation forbidden for built-in Quality Gate '%s'", qualityGate.getName())); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_ID, qualityGateCondition.getUuid()) - .execute(); + .execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(format("Operation forbidden for built-in Quality Gate '%s'", qualityGate.getName())); } @Test @@ -152,11 +149,10 @@ public class DeleteConditionActionTest { MetricDto metric = db.measures().insertMetric(); QualityGateConditionDto qualityGateCondition = db.qualityGates().addCondition(qualityGate, metric); - expectedException.expect(ForbiddenException.class); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_ID, qualityGateCondition.getUuid()) - .execute(); + .execute()) + .isInstanceOf(ForbiddenException.class); } @Test @@ -167,12 +163,11 @@ public class DeleteConditionActionTest { QualityGateConditionDto qualityGateCondition = db.qualityGates().addCondition(qualityGate, metric); String unknownConditionUuid = "unknown"; - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("No quality gate condition with uuid '" + unknownConditionUuid + "'"); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_ID, unknownConditionUuid) - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("No quality gate condition with uuid '" + unknownConditionUuid + "'"); } @Test @@ -182,12 +177,11 @@ public class DeleteConditionActionTest { db.getDbClient().gateConditionDao().insert(condition, db.getSession()); db.commit(); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage(format("Condition '%s' is linked to an unknown quality gate '%s'", condition.getUuid(), 123L)); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_ID, condition.getUuid()) - .execute(); + .execute()) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining(format("Condition '%s' is linked to an unknown quality gate '%s'", condition.getUuid(), 123L)); } private Collection searchConditionsOf(QualityGateDto qualityGate) { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/DeselectActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/DeselectActionTest.java index ed6f229cca0..6361821c363 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/DeselectActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/DeselectActionTest.java @@ -22,7 +22,6 @@ package org.sonar.server.qualitygate.ws; import java.util.Optional; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.Change; import org.sonar.api.server.ws.WebService; import org.sonar.api.web.UserRole; @@ -40,14 +39,13 @@ import org.sonar.server.ws.WsActionTester; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_GATES; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES; public class DeselectActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -122,11 +120,10 @@ public class DeselectActionTest { public void fail_when_no_project_key() { userSession.addPermission(ADMINISTER_QUALITY_GATES); - expectedException.expect(NotFoundException.class); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("projectKey", "unknown") - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class); } @Test @@ -134,10 +131,10 @@ public class DeselectActionTest { ComponentDto project = db.components().insertPrivateProject(); userSession.anonymous(); - expectedException.expect(ForbiddenException.class); - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("projectKey", project.getKey()) - .execute(); + .execute()) + .isInstanceOf(ForbiddenException.class); } @Test @@ -145,11 +142,10 @@ public class DeselectActionTest { ComponentDto project = db.components().insertPrivateProject(); userSession.logIn().addProjectPermission(UserRole.ISSUE_ADMIN, project); - expectedException.expect(ForbiddenException.class); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("projectKey", project.getKey()) - .execute(); + .execute()) + .isInstanceOf(ForbiddenException.class); } @Test @@ -158,12 +154,10 @@ public class DeselectActionTest { ComponentDto project = db.components().insertPrivateProject(); userSession.logIn().addPermission(ADMINISTER_QUALITY_PROFILES); - - expectedException.expect(ForbiddenException.class); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("projectKey", project.getKey()) - .execute(); + .execute()) + .isInstanceOf(ForbiddenException.class); } @Test @@ -172,12 +166,11 @@ public class DeselectActionTest { userSession.logIn().addProjectPermission(UserRole.ADMIN, project); ComponentDto branch = db.components().insertProjectBranch(project); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(format("Project '%s' not found", branch.getDbKey())); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("projectKey", branch.getDbKey()) - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining(format("Project '%s' not found", branch.getDbKey())); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/DestroyActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/DestroyActionTest.java index c79d034288a..d37f9882846 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/DestroyActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/DestroyActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.qualitygate.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.db.DbClient; @@ -43,6 +42,7 @@ import static java.lang.String.format; import static java.lang.String.valueOf; import static org.apache.commons.lang.StringUtils.EMPTY; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_GATES; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES; @@ -52,8 +52,6 @@ import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_ID; public class DestroyActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -169,23 +167,21 @@ public class DestroyActionTest { db.commit(); userSession.addPermission(ADMINISTER_QUALITY_GATES); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(format("Operation forbidden for built-in Quality Gate '%s'", builtInQualityGate.getName())); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_ID, valueOf(builtInQualityGate.getUuid())) - .execute(); + .execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(format("Operation forbidden for built-in Quality Gate '%s'", builtInQualityGate.getName())); } @Test public void fail_when_missing_id() { userSession.addPermission(ADMINISTER_QUALITY_GATES); - expectedException.expect(NotFoundException.class); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_ID, EMPTY) - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class); } @Test @@ -193,23 +189,21 @@ public class DestroyActionTest { QualityGateDto defaultQualityGate = db.qualityGates().createDefaultQualityGate(); userSession.addPermission(ADMINISTER_QUALITY_GATES); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The default quality gate cannot be removed"); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_ID, valueOf(defaultQualityGate.getUuid())) - .execute(); + .execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("The default quality gate cannot be removed"); } @Test public void fail_on_unknown_quality_gate() { userSession.addPermission(ADMINISTER_QUALITY_GATES); - expectedException.expect(NotFoundException.class); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_ID, "123") - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class); } @Test @@ -218,11 +212,10 @@ public class DestroyActionTest { db.qualityGates().createDefaultQualityGate(); userSession.logIn("john").addPermission(ADMINISTER_QUALITY_PROFILES); - expectedException.expect(ForbiddenException.class); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_ID, qualityGate.getUuid()) - .execute(); + .execute()) + .isInstanceOf(ForbiddenException.class); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/GetByProjectActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/GetByProjectActionTest.java index 58268b2da33..b30278a9ece 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/GetByProjectActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/GetByProjectActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.qualitygate.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.api.web.UserRole; @@ -41,6 +40,7 @@ import org.sonarqube.ws.Qualitygates.GetByProjectResponse; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.test.JsonAssert.assertJson; @@ -48,8 +48,6 @@ public class GetByProjectActionTest { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Rule public DbTester db = DbTester.create(System2.INSTANCE); private final DbClient dbClient = db.getDbClient(); @@ -172,28 +170,25 @@ public class GetByProjectActionTest { ComponentDto project = db.components().insertPrivateProject(); userSession.logIn(); - expectedException.expect(ForbiddenException.class); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("project", project.getKey()) - .execute(); + .execute()) + .isInstanceOf(ForbiddenException.class); } @Test public void fail_when_project_does_not_exist() { - expectedException.expect(NotFoundException.class); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("project", "Unknown") - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class); } @Test public void fail_when_missing_project_parameter() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The 'project' parameter is missing"); - - ws.newRequest().execute(); + assertThatThrownBy(() -> ws.newRequest().execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("The 'project' parameter is missing"); } @Test @@ -202,12 +197,9 @@ public class GetByProjectActionTest { userSession.logIn().addProjectPermission(UserRole.ADMIN, project); ComponentDto branch = db.components().insertProjectBranch(project); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(format("Project '%s' not found", branch.getDbKey())); - - ws.newRequest() - .setParam("project", branch.getDbKey()) - .execute(); + assertThatThrownBy(() -> ws.newRequest().setParam("project", branch.getDbKey()).execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining(format("Project '%s' not found", branch.getDbKey())); } private void logInAsProjectUser(ProjectDto project) { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/ListActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/ListActionTest.java index 8250502410a..e5ca169beb6 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/ListActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/ListActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.qualitygate.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbClient; import org.sonar.db.DbTester; @@ -34,6 +33,7 @@ import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.Qualitygates.ListWsResponse.QualityGate; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.AssertionsForClassTypes.tuple; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_GATES; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES; @@ -42,8 +42,6 @@ import static org.sonarqube.ws.Qualitygates.ListWsResponse; public class ListActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -102,10 +100,9 @@ public class ListActionTest { public void no_default_quality_gate() { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); - expectedException.expect(IllegalStateException.class); - - ListWsResponse response = ws.newRequest() - .executeProtobuf(ListWsResponse.class); + assertThatThrownBy(() -> ws.newRequest() + .executeProtobuf(ListWsResponse.class)) + .isInstanceOf(IllegalStateException.class); } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/ProjectStatusActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/ProjectStatusActionTest.java index 2db6ee173bf..b3f9044c16f 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/ProjectStatusActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/ProjectStatusActionTest.java @@ -24,7 +24,6 @@ import java.nio.charset.StandardCharsets; import org.apache.commons.io.IOUtils; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.measures.CoreMetrics; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; @@ -47,6 +46,7 @@ import org.sonarqube.ws.Qualitygates.ProjectStatusResponse.Status; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.db.component.SnapshotTesting.newAnalysis; import static org.sonar.db.measure.MeasureTesting.newLiveMeasure; @@ -62,8 +62,6 @@ import static org.sonar.test.JsonAssert.assertJson; public class ProjectStatusActionTest { private static final String ANALYSIS_ID = "task-uuid"; - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -316,12 +314,11 @@ public class ProjectStatusActionTest { public void fail_if_no_snapshot_id_found() { logInAsSystemAdministrator(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Analysis with id 'task-uuid' is not found"); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_ANALYSIS_ID, ANALYSIS_ID) - .executeProtobuf(ProjectStatusResponse.class); + .executeProtobuf(ProjectStatusResponse.class)) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("Analysis with id 'task-uuid' is not found"); } @Test @@ -331,11 +328,10 @@ public class ProjectStatusActionTest { dbSession.commit(); userSession.logIn(); - expectedException.expect(ForbiddenException.class); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_ANALYSIS_ID, snapshot.getUuid()) - .executeProtobuf(ProjectStatusResponse.class); + .executeProtobuf(ProjectStatusResponse.class)) + .isInstanceOf(ForbiddenException.class); } @Test @@ -343,13 +339,12 @@ public class ProjectStatusActionTest { ComponentDto project = db.components().insertPrivateProject(); logInAsSystemAdministrator(); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Either 'analysisId', 'projectId' or 'projectKey' must be provided"); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_ANALYSIS_ID, "analysis-id") .setParam(PARAM_PROJECT_ID, "project-uuid") - .execute().getInput(); + .execute().getInput()) + .isInstanceOf(BadRequestException.class) + .hasMessageContaining("Either 'analysisId', 'projectId' or 'projectKey' must be provided"); } @Test @@ -357,26 +352,23 @@ public class ProjectStatusActionTest { ComponentDto project = db.components().insertPrivateProject(); logInAsSystemAdministrator(); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Either 'branch' or 'pullRequest' can be provided, not both"); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_PROJECT_KEY, "key") .setParam(PARAM_BRANCH, "branch") .setParam(PARAM_PULL_REQUEST, "pr") - .execute().getInput(); + .execute().getInput()) + .isInstanceOf(BadRequestException.class) + .hasMessageContaining("Either 'branch' or 'pullRequest' can be provided, not both"); } @Test public void fail_if_no_parameter_provided() { logInAsSystemAdministrator(); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Either 'analysisId', 'projectId' or 'projectKey' must be provided"); - - ws.newRequest() - .execute() - .getInput(); + assertThatThrownBy(() -> ws.newRequest() + .execute().getInput()) + .isInstanceOf(BadRequestException.class) + .hasMessageContaining("Either 'analysisId', 'projectId' or 'projectKey' must be provided"); } @Test @@ -386,12 +378,11 @@ public class ProjectStatusActionTest { ComponentDto branch = db.components().insertProjectBranch(project); SnapshotDto snapshot = db.components().insertSnapshot(branch); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(format("Project '%s' not found", branch.getDbKey())); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_PROJECT_KEY, branch.getDbKey()) - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining(format("Project '%s' not found", branch.getDbKey())); } @Test @@ -401,12 +392,11 @@ public class ProjectStatusActionTest { ComponentDto branch = db.components().insertProjectBranch(project); SnapshotDto snapshot = db.components().insertSnapshot(branch); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(format("Project '%s' not found", branch.uuid())); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("projectId", branch.uuid()) - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining(format("Project '%s' not found", branch.uuid())); } private void logInAsSystemAdministrator() { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/QualityGateDetailsFormatterTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/QualityGateDetailsFormatterTest.java index 5e85ad0f6a5..67bdb32bd0f 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/QualityGateDetailsFormatterTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/QualityGateDetailsFormatterTest.java @@ -24,19 +24,16 @@ import java.util.List; import java.util.Optional; import javax.annotation.Nullable; import org.apache.commons.io.IOUtils; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.db.component.SnapshotDto; import org.sonarqube.ws.Qualitygates.ProjectStatusResponse; import org.sonarqube.ws.Qualitygates.ProjectStatusResponse.ProjectStatus; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.utils.DateUtils.formatDateTime; public class QualityGateDetailsFormatterTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private QualityGateDetailsFormatter underTest; @@ -117,10 +114,10 @@ public class QualityGateDetailsFormatterTest { " ]\n" + "}"; underTest = newQualityGateDetailsFormatter(measureData, new SnapshotDto()); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Unknown quality gate status 'UNKNOWN'"); - underTest.format(); + assertThatThrownBy(() -> underTest.format()) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Unknown quality gate status 'UNKNOWN'"); } @Test @@ -140,10 +137,10 @@ public class QualityGateDetailsFormatterTest { " ]\n" + "}"; underTest = newQualityGateDetailsFormatter(measureData, new SnapshotDto()); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Unknown quality gate comparator 'UNKNOWN'"); - underTest.format(); + assertThatThrownBy(() -> underTest.format()) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Unknown quality gate comparator 'UNKNOWN'"); } private static QualityGateDetailsFormatter newQualityGateDetailsFormatter(@Nullable String measureData, @Nullable SnapshotDto snapshotDto) { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/RemoveGroupActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/RemoveGroupActionTest.java index bbb5ec364b0..850013b56a6 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/RemoveGroupActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/RemoveGroupActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.qualitygate.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbClient; import org.sonar.db.DbTester; @@ -37,13 +36,12 @@ import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_GATE_NAME; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_GROUP_NAME; public class RemoveGroupActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -132,13 +130,12 @@ public class RemoveGroupActionTest { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_GATES); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Group with name 'unknown' is not found"); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_GATE_NAME, qualityGate.getName()) .setParam(PARAM_GROUP_NAME, "unknown") - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("Group with name 'unknown' is not found"); } @Test @@ -146,13 +143,12 @@ public class RemoveGroupActionTest { GroupDto group = db.users().insertGroup(); userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_GATES); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(String.format("No quality gate has been found for name unknown")); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_GATE_NAME, "unknown") .setParam(PARAM_GROUP_NAME, group.getName()) - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining(String.format("No quality gate has been found for name unknown")); } @Test @@ -161,13 +157,12 @@ public class RemoveGroupActionTest { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(qg -> qg.setBuiltIn(true)); userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_GATES); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(String.format("Operation forbidden for built-in Quality Gate '%s'", qualityGate.getName())); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_GATE_NAME, qualityGate.getName()) .setParam(PARAM_GROUP_NAME, group.getName()) - .execute(); + .execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(String.format("Operation forbidden for built-in Quality Gate '%s'", qualityGate.getName())); } @Test @@ -176,11 +171,10 @@ public class RemoveGroupActionTest { GroupDto group = db.users().insertGroup(); userSession.logIn(db.users().insertUser()).addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES); - expectedException.expect(ForbiddenException.class); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_GATE_NAME, qualityGate.getName()) .setParam(PARAM_GROUP_NAME, group.getName()) - .execute(); + .execute()) + .isInstanceOf(ForbiddenException.class); } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/RenameActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/RenameActionTest.java index e04e6d26cc4..9487f1588aa 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/RenameActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/RenameActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.qualitygate.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.db.DbTester; @@ -35,14 +34,13 @@ import org.sonarqube.ws.Qualitygates.QualityGate; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.AssertionsForClassTypes.tuple; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_GATES; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES; public class RenameActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -110,13 +108,12 @@ public class RenameActionTest { userSession.logIn("john").addPermission(ADMINISTER_QUALITY_GATES); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(qg -> qg.setBuiltIn(true)); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(format("Operation forbidden for built-in Quality Gate '%s'", qualityGate.getName())); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("id", qualityGate.getUuid()) .setParam("name", "name") - .execute(); + .execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(format("Operation forbidden for built-in Quality Gate '%s'", qualityGate.getName())); } @Test @@ -124,13 +121,12 @@ public class RenameActionTest { userSession.logIn("john").addPermission(ADMINISTER_QUALITY_GATES); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The 'name' parameter is missing"); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("id", qualityGate.getUuid()) .setParam("name", "") - .execute(); + .execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("The 'name' parameter is missing"); } @Test @@ -139,25 +135,23 @@ public class RenameActionTest { QualityGateDto qualityGate1 = db.qualityGates().insertQualityGate(); QualityGateDto qualityGate2 = db.qualityGates().insertQualityGate(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(format("Name '%s' has already been taken", qualityGate2.getName())); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("id", qualityGate1.getUuid()) .setParam("name", qualityGate2.getName()) - .execute(); + .execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(format("Name '%s' has already been taken", qualityGate2.getName())); } @Test public void fail_on_unknown_quality_gate() { userSession.logIn("john").addPermission(ADMINISTER_QUALITY_GATES); - expectedException.expect(NotFoundException.class); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("id", "123") .setParam("name", "new name") - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class); } @Test @@ -165,12 +159,11 @@ public class RenameActionTest { userSession.logIn("john").addPermission(ADMINISTER_QUALITY_PROFILES); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(qg -> qg.setName("old name")); - expectedException.expect(ForbiddenException.class); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("id", qualityGate.getUuid()) .setParam("name", "new name") - .execute(); + .execute()) + .isInstanceOf(ForbiddenException.class); } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/SearchActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/SearchActionTest.java index a33c5ee4a50..469176508ee 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/SearchActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/SearchActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.qualitygate.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbClient; import org.sonar.db.DbTester; @@ -38,6 +37,7 @@ import org.sonarqube.ws.Qualitygates.SearchResponse.Result; import static java.lang.String.valueOf; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.AssertionsForClassTypes.tuple; import static org.sonar.api.server.ws.WebService.SelectionMode.ALL; import static org.sonar.api.server.ws.WebService.SelectionMode.DESELECTED; @@ -51,8 +51,6 @@ import static org.sonarqube.ws.client.user.UsersWsParameters.PARAM_SELECTED; public class SearchActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @@ -199,8 +197,8 @@ public class SearchActionTest { .setParam(PARAM_PAGE_SIZE, "1") .executeProtobuf(SearchResponse.class) .getResultsList()) - .extracting(Result::getName) - .containsExactlyInAnyOrder(project1.getName()); + .extracting(Result::getName) + .containsExactlyInAnyOrder(project1.getName()); // Return partial result on second page assertThat(ws.newRequest() @@ -210,8 +208,8 @@ public class SearchActionTest { .setParam(PARAM_PAGE_SIZE, "1") .executeProtobuf(SearchResponse.class) .getResultsList()) - .extracting(Result::getName) - .containsExactlyInAnyOrder(project2.getName()); + .extracting(Result::getName) + .containsExactlyInAnyOrder(project2.getName()); // Return partial result on first page assertThat(ws.newRequest() @@ -221,8 +219,8 @@ public class SearchActionTest { .setParam(PARAM_PAGE_SIZE, "2") .executeProtobuf(SearchResponse.class) .getResultsList()) - .extracting(Result::getName) - .containsExactlyInAnyOrder(project1.getName(), project2.getName()); + .extracting(Result::getName) + .containsExactlyInAnyOrder(project1.getName(), project2.getName()); // Return all result on first page assertThat(ws.newRequest() @@ -232,8 +230,8 @@ public class SearchActionTest { .setParam(PARAM_PAGE_SIZE, "3") .executeProtobuf(SearchResponse.class) .getResultsList()) - .extracting(Result::getName) - .containsExactlyInAnyOrder(project1.getName(), project2.getName(), project3.getName()); + .extracting(Result::getName) + .containsExactlyInAnyOrder(project1.getName(), project2.getName(), project3.getName()); // Return no result as page index is off limit assertThat(ws.newRequest() @@ -243,8 +241,8 @@ public class SearchActionTest { .setParam(PARAM_PAGE_SIZE, "3") .executeProtobuf(SearchResponse.class) .getResultsList()) - .extracting(Result::getName) - .isEmpty(); + .extracting(Result::getName) + .isEmpty(); } @Test @@ -295,12 +293,11 @@ public class SearchActionTest { @Test public void fail_on_unknown_quality_gate() { - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("No quality gate has been found for id 42"); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_GATE_ID, "42") - .executeProtobuf(SearchResponse.class); + .executeProtobuf(SearchResponse.class)) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("No quality gate has been found for id 42"); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/SearchGroupsActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/SearchGroupsActionTest.java index b8fcb184430..3437fc46da6 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/SearchGroupsActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/SearchGroupsActionTest.java @@ -22,7 +22,6 @@ package org.sonar.server.qualitygate.ws; import org.assertj.core.api.Assertions; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbTester; import org.sonar.db.permission.GlobalPermission; @@ -37,6 +36,7 @@ import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.Qualitygates; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.server.ws.WebService.Param.PAGE; import static org.sonar.api.server.ws.WebService.Param.PAGE_SIZE; import static org.sonar.api.server.ws.WebService.Param.TEXT_QUERY; @@ -50,8 +50,6 @@ public class SearchGroupsActionTest { private static final String XOO = "xoo"; private static final String FOO = "foo"; - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -283,12 +281,11 @@ public class SearchGroupsActionTest { public void fail_when_qgate_does_not_exist() { userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_GATES); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("No quality gate has been found for name unknown"); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_GATE_NAME, "unknown") - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("No quality gate has been found for name unknown"); } @Test @@ -296,11 +293,10 @@ public class SearchGroupsActionTest { QualityGateDto gate = db.qualityGates().insertQualityGate(); userSession.logIn(db.users().insertUser()); - expectedException.expect(ForbiddenException.class); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_GATE_NAME, gate.getName()) - .execute(); + .execute()) + .isInstanceOf(ForbiddenException.class); } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/SelectActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/SelectActionTest.java index d558cd13cbc..3ecf469c37e 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/SelectActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/SelectActionTest.java @@ -22,7 +22,6 @@ package org.sonar.server.qualitygate.ws; import java.util.Optional; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.utils.System2; import org.sonar.db.DbClient; import org.sonar.db.DbTester; @@ -37,14 +36,13 @@ import org.sonar.server.ws.WsActionTester; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.web.UserRole.ADMIN; import static org.sonar.api.web.UserRole.ISSUE_ADMIN; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_GATES; public class SelectActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -142,12 +140,11 @@ public class SelectActionTest { userSession.addPermission(ADMINISTER_QUALITY_GATES); ComponentDto project = db.components().insertPrivateProject(); - expectedException.expect(NotFoundException.class); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("gateId", "1") .setParam("projectKey", project.getKey()) - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class); } @Test @@ -155,11 +152,11 @@ public class SelectActionTest { userSession.addPermission(ADMINISTER_QUALITY_GATES); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); - expectedException.expect(NotFoundException.class); - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("gateId", qualityGate.getUuid()) .setParam("projectKey", "unknown") - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class); } @Test @@ -168,11 +165,11 @@ public class SelectActionTest { ComponentDto project = db.components().insertPrivateProject(); userSession.anonymous(); - expectedException.expect(ForbiddenException.class); - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("gateId", qualityGate.getUuid()) .setParam("projectKey", project.getKey()) - .execute(); + .execute()) + .isInstanceOf(ForbiddenException.class); } @Test @@ -181,11 +178,11 @@ public class SelectActionTest { ComponentDto project = db.components().insertPrivateProject(); userSession.logIn().addProjectPermission(ISSUE_ADMIN, project); - expectedException.expect(ForbiddenException.class); - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("gateId", qualityGate.getUuid()) .setParam("projectKey", project.getDbKey()) - .execute(); + .execute()) + .isInstanceOf(ForbiddenException.class); } @Test @@ -194,11 +191,11 @@ public class SelectActionTest { ComponentDto project = db.components().insertPrivateProject(); userSession.logIn(); - expectedException.expect(ForbiddenException.class); - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("gateId", qualityGate.getUuid()) .setParam("projectKey", project.getDbKey()) - .execute(); + .execute()) + .isInstanceOf(ForbiddenException.class); } @Test @@ -208,13 +205,12 @@ public class SelectActionTest { userSession.logIn().addProjectPermission(ADMIN, project); ComponentDto branch = db.components().insertProjectBranch(project); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(format("Project '%s' not found", branch.getDbKey())); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("gateId", qualityGate.getUuid()) .setParam("projectKey", branch.getDbKey()) - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining(format("Project '%s' not found", branch.getDbKey())); } private void assertSelected(QualityGateDto qualityGate, ComponentDto project) { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/ShowActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/ShowActionTest.java index de776d5dbe5..8e9353f41ab 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/ShowActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/ShowActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.qualitygate.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.api.server.ws.WebService.Param; import org.sonar.api.utils.System2; @@ -40,6 +39,7 @@ import org.sonarqube.ws.Qualitygates.ShowWsResponse.Condition; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.AssertionsForClassTypes.tuple; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_GATES; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES; @@ -48,8 +48,6 @@ import static org.sonarqube.ws.Qualitygates.Actions; public class ShowActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -238,23 +236,21 @@ public class ShowActionTest { public void fail_when_no_name_or_id() { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Either 'id' or 'name' must be provided"); - - ws.newRequest().execute(); + assertThatThrownBy(() -> ws.newRequest().execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Either 'id' or 'name' must be provided"); } @Test public void fail_when_both_name_or_id() { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Either 'id' or 'name' must be provided"); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("name", qualityGate.getName()) .setParam("id", qualityGate.getUuid()) - .execute(); + .execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Either 'id' or 'name' must be provided"); } @Test @@ -266,36 +262,33 @@ public class ShowActionTest { db.getDbClient().metricDao().disableByKey(db.getSession(), metric.getKey()); db.commit(); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage(format("Could not find metric with id %s", metric.getUuid())); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("name", qualityGate.getName()) - .execute(); + .execute()) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining(format("Could not find metric with id %s", metric.getUuid())); } @Test public void fail_when_quality_name_does_not_exist() { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("No quality gate has been found for name UNKNOWN"); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("name", "UNKNOWN") - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("No quality gate has been found for name UNKNOWN"); } @Test public void fail_when_quality_id_does_not_exist() { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("No quality gate has been found for id 123"); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("id", "123") - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("No quality gate has been found for id 123"); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/UpdateConditionActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/UpdateConditionActionTest.java index c976515a9e5..9fad4771625 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/UpdateConditionActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualitygate/ws/UpdateConditionActionTest.java @@ -24,7 +24,6 @@ import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; @@ -48,6 +47,7 @@ import org.sonarqube.ws.Qualitygates.CreateConditionResponse; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.api.measures.Metric.ValueType.INT; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_GATES; @@ -59,8 +59,6 @@ import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_OPE @RunWith(DataProviderRunner.class) public class UpdateConditionActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @@ -160,15 +158,14 @@ public class UpdateConditionActionTest { MetricDto metric = insertMetric(); QualityGateConditionDto condition = db.qualityGates().addCondition(qualityGate, metric); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(format("Operation forbidden for built-in Quality Gate '%s'", qualityGate.getName())); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_ID, condition.getUuid()) .setParam(PARAM_METRIC, metric.getKey()) .setParam(PARAM_OPERATOR, "LT") .setParam(PARAM_ERROR, "10") - .execute(); + .execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(format("Operation forbidden for built-in Quality Gate '%s'", qualityGate.getName())); } @Test @@ -178,15 +175,14 @@ public class UpdateConditionActionTest { MetricDto metric = insertMetric(); db.qualityGates().addCondition(qualityGate, metric); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("No quality gate condition with uuid '123'"); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_ID, "123") .setParam(PARAM_METRIC, metric.getKey()) .setParam(PARAM_OPERATOR, "LT") .setParam(PARAM_ERROR, "90") - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("No quality gate condition with uuid '123'"); } @Test @@ -199,15 +195,14 @@ public class UpdateConditionActionTest { db.getDbClient().gateConditionDao().insert(condition, dbSession); db.commit(); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage(format("Condition '%s' is linked to an unknown quality gate '%s'", condition.getUuid(), 123L)); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_ID, condition.getUuid()) .setParam(PARAM_METRIC, metric.getKey()) .setParam(PARAM_OPERATOR, "LT") .setParam(PARAM_ERROR, "90") - .execute(); + .execute()) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining(format("Condition '%s' is linked to an unknown quality gate '%s'", condition.getUuid(), 123L)); } @Test @@ -218,15 +213,14 @@ public class UpdateConditionActionTest { QualityGateConditionDto condition = db.qualityGates().addCondition(qualityGate, metric, c -> c.setOperator("LT").setErrorThreshold("80")); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Value of parameter 'op' (ABC) must be one of: [LT, GT]"); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_ID, condition.getUuid()) .setParam(PARAM_METRIC, metric.getKey()) .setParam(PARAM_OPERATOR, "ABC") .setParam(PARAM_ERROR, "90") - .execute(); + .execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Value of parameter 'op' (ABC) must be one of: [LT, GT]"); } @Test @@ -238,15 +232,14 @@ public class UpdateConditionActionTest { QualityGateConditionDto condition = db.qualityGates().addCondition(qualityGate, metric, c -> c.setOperator(validOperator).setErrorThreshold("80")); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage(format("Operator %s is not allowed for this metric.", updateOperator)); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_ID, condition.getUuid()) .setParam(PARAM_METRIC, metric.getKey()) .setParam(PARAM_OPERATOR, updateOperator) .setParam(PARAM_ERROR, "90") - .execute(); + .execute()) + .isInstanceOf(BadRequestException.class) + .hasMessageContaining(format("Operator %s is not allowed for this metric.", updateOperator)); } @Test @@ -256,15 +249,14 @@ public class UpdateConditionActionTest { MetricDto metric = insertMetric(); QualityGateConditionDto condition = db.qualityGates().addCondition(qualityGate, metric); - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_ID, condition.getUuid()) .setParam(PARAM_METRIC, metric.getKey()) .setParam(PARAM_OPERATOR, "LT") .setParam(PARAM_ERROR, "90") - .execute(); + .execute()) + .isInstanceOf(ForbiddenException.class) + .hasMessageContaining("Insufficient privileges"); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/QProfileBackuperImplTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/QProfileBackuperImplTest.java index 913a4ea18f5..f45bf99198d 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/QProfileBackuperImplTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/QProfileBackuperImplTest.java @@ -30,7 +30,6 @@ import java.util.List; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.impl.utils.AlwaysIncreasingSystem2; import org.sonar.api.rule.RuleKey; import org.sonar.api.rule.RuleStatus; @@ -48,8 +47,8 @@ import org.sonar.server.rule.RuleCreator; import static java.nio.charset.StandardCharsets.UTF_8; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertThrows; -import static org.junit.rules.ExpectedException.none; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.Mockito.mock; @@ -65,8 +64,6 @@ public class QProfileBackuperImplTest { private final System2 system2 = new AlwaysIncreasingSystem2(); - @Rule - public ExpectedException expectedException = none(); @Rule public DbTester db = DbTester.create(system2); @@ -389,11 +386,13 @@ public class QProfileBackuperImplTest { @Test public void fail_to_restore_if_xml_is_not_well_formed() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Fail to restore Quality profile backup, XML document is not well formed"); - String notWellFormedXml = "\"profil\"\"language\" { + String notWellFormedXml = "\"profil\"\"language\"" + ""); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The quality profile cannot be restored as it contains rules from external rule engines: sonarjs:s001"); - underTest.restore(db.getSession(), backup, (String) null); + assertThatThrownBy(() -> { + underTest.restore(db.getSession(), backup, (String) null); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("The quality profile cannot be restored as it contains rules from external rule engines: sonarjs:s001"); } private RuleDefinitionDto createRule() { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/QProfileCopierTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/QProfileCopierTest.java index b80642077d0..ac34070dd93 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/QProfileCopierTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/QProfileCopierTest.java @@ -23,7 +23,6 @@ import java.util.Collection; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.impl.utils.AlwaysIncreasingSystem2; import org.sonar.api.impl.utils.JUnitTempFolder; import org.sonar.api.utils.System2; @@ -45,8 +44,6 @@ public class QProfileCopierTest { private static final String BACKUP = ""; private final System2 system2 = new AlwaysIncreasingSystem2(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester db = DbTester.create(system2); @Rule diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/QProfileExportersTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/QProfileExportersTest.java index 7d3fac8521e..bc760e31bdd 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/QProfileExportersTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/QProfileExportersTest.java @@ -27,7 +27,6 @@ import java.io.Writer; import java.util.Collection; import org.junit.Before; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; import org.sonar.api.impl.utils.AlwaysIncreasingSystem2; import org.sonar.api.profiles.ProfileExporter; @@ -63,8 +62,6 @@ public class QProfileExportersTest { private final System2 system2 = new AlwaysIncreasingSystem2(); - @org.junit.Rule - public ExpectedException expectedException = ExpectedException.none(); @org.junit.Rule public DbTester db = DbTester.create(system2); @@ -178,11 +175,11 @@ public class QProfileExportersTest { public void export_throws_NotFoundException_if_exporter_does_not_exist() { QProfileDto profile = createProfile(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Unknown quality profile exporter: does_not_exist"); - - underTest.export(db.getSession(), profile, "does_not_exist", new StringWriter()); - + assertThatThrownBy(() -> { + underTest.export(db.getSession(), profile, "does_not_exist", new StringWriter()); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("Unknown quality profile exporter: does_not_exist"); } private QProfileDto createProfile() { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/QProfileFactoryImplTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/QProfileFactoryImplTest.java index 314eddbcd4c..9e7fcdf9239 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/QProfileFactoryImplTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/QProfileFactoryImplTest.java @@ -22,10 +22,10 @@ package org.sonar.server.qualityprofile; import java.util.Collections; import java.util.Set; import org.assertj.core.api.AbstractObjectAssert; +import org.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; import org.sonar.api.impl.utils.AlwaysIncreasingSystem2; import org.sonar.api.rule.Severity; @@ -50,6 +50,7 @@ import org.sonar.server.qualityprofile.index.ActiveRuleIndexer; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyCollection; import static org.mockito.Mockito.mock; @@ -61,8 +62,6 @@ public class QProfileFactoryImplTest { private System2 system2 = new AlwaysIncreasingSystem2(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester db = DbTester.create(system2); @@ -97,18 +96,14 @@ public class QProfileFactoryImplTest { public void checkAndCreateCustom_throws_BadRequestException_if_name_null() { QProfileName name = new QProfileName("xoo", null); - expectBadRequestException("quality_profiles.profile_name_cant_be_blank"); - - underTest.checkAndCreateCustom(dbSession, name); + expectBadRequestException(() -> underTest.checkAndCreateCustom(dbSession, name), "quality_profiles.profile_name_cant_be_blank"); } @Test public void checkAndCreateCustom_throws_BadRequestException_if_name_empty() { QProfileName name = new QProfileName("xoo", ""); - expectBadRequestException("quality_profiles.profile_name_cant_be_blank"); - - underTest.checkAndCreateCustom(dbSession, name); + expectBadRequestException(() -> underTest.checkAndCreateCustom(dbSession, name), "quality_profiles.profile_name_cant_be_blank"); } @Test @@ -118,9 +113,7 @@ public class QProfileFactoryImplTest { underTest.checkAndCreateCustom(dbSession, name); dbSession.commit(); - expectBadRequestException("Quality profile already exists: xoo/P1"); - - underTest.checkAndCreateCustom(dbSession, name); + expectBadRequestException(() -> underTest.checkAndCreateCustom(dbSession, name), "Quality profile already exists: xoo/P1"); } @Test @@ -342,8 +335,9 @@ public class QProfileFactoryImplTest { assertThat(p2.getParentKee()).isEqualTo(p1.getParentKee()); } - private void expectBadRequestException(String message) { - expectedException.expect(BadRequestException.class); - expectedException.expectMessage(message); + private void expectBadRequestException(ThrowingCallable callback, String message) { + assertThatThrownBy(callback) + .isInstanceOf(BadRequestException.class) + .hasMessage(message); } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/QProfileResetImplTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/QProfileResetImplTest.java index f89a99edc4f..b6640dd8aca 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/QProfileResetImplTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/QProfileResetImplTest.java @@ -21,7 +21,6 @@ package org.sonar.server.qualityprofile; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.impl.utils.AlwaysIncreasingSystem2; import org.sonar.api.utils.System2; import org.sonar.db.DbTester; @@ -40,6 +39,7 @@ import static java.util.Arrays.asList; import static java.util.Collections.singleton; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.Mockito.mock; import static org.sonar.server.qualityprofile.ActiveRuleChange.Type.ACTIVATED; @@ -48,8 +48,6 @@ public class QProfileResetImplTest { private static final String LANGUAGE = "xoo"; - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester db = DbTester.create(); @Rule @@ -103,10 +101,11 @@ public class QProfileResetImplTest { QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(LANGUAGE).setIsBuiltIn(true)); RuleDefinitionDto defaultRule = db.rules().insert(r -> r.setLanguage(LANGUAGE)); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(String.format("Operation forbidden for built-in Quality Profile '%s'", profile.getKee())); - - underTest.reset(db.getSession(), profile, singletonList(RuleActivation.create(defaultRule.getUuid()))); + assertThatThrownBy(() -> { + underTest.reset(db.getSession(), profile, singletonList(RuleActivation.create(defaultRule.getUuid()))); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage(String.format("Operation forbidden for built-in Quality Profile '%s'", profile.getKee())); } @Test @@ -114,9 +113,10 @@ public class QProfileResetImplTest { QProfileDto profile = QualityProfileTesting.newQualityProfileDto().setRulesProfileUuid(null).setLanguage(LANGUAGE); RuleDefinitionDto defaultRule = db.rules().insert(r -> r.setLanguage(LANGUAGE)); - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("Quality profile must be persisted"); - - underTest.reset(db.getSession(), profile, singletonList(RuleActivation.create(defaultRule.getUuid()))); + assertThatThrownBy(() -> { + underTest.reset(db.getSession(), profile, singletonList(RuleActivation.create(defaultRule.getUuid()))); + }) + .isInstanceOf(NullPointerException.class) + .hasMessage("Quality profile must be persisted"); } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/QProfileRuleImplTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/QProfileRuleImplTest.java index 8ac2dc336bf..bad6cdc8336 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/QProfileRuleImplTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/QProfileRuleImplTest.java @@ -28,7 +28,6 @@ import java.util.stream.IntStream; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.PropertyType; import org.sonar.api.impl.utils.AlwaysIncreasingSystem2; import org.sonar.api.rule.RuleStatus; @@ -60,6 +59,7 @@ import static java.util.Collections.singleton; import static java.util.Collections.singletonList; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.fail; import static org.sonar.api.rule.Severity.BLOCKER; import static org.sonar.api.rule.Severity.CRITICAL; @@ -70,9 +70,6 @@ import static org.sonar.server.qualityprofile.ActiveRuleInheritance.INHERITED; public class QProfileRuleImplTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); - private System2 system2 = new AlwaysIncreasingSystem2(); @Rule public DbTester db = DbTester.create(system2); @@ -627,9 +624,9 @@ public class QProfileRuleImplTest { assertThatRuleIsActivated(parentProfile, rule, changes, rule.getSeverityString(), null, emptyMap()); assertThatRuleIsActivated(childProfile, rule, changes, rule.getSeverityString(), INHERITED, emptyMap()); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Cannot deactivate inherited rule"); - deactivate(childProfile, rule); + assertThatThrownBy(() -> deactivate(childProfile, rule)) + .isInstanceOf(BadRequestException.class) + .hasMessageContaining("Cannot deactivate inherited rule"); } @Test @@ -853,10 +850,11 @@ public class QProfileRuleImplTest { RuleDefinitionDto rule = createRule(); QProfileDto builtInProfile = db.qualityProfiles().insert(p -> p.setLanguage(rule.getLanguage()).setIsBuiltIn(true)); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The built-in profile " + builtInProfile.getName() + " is read-only and can't be updated"); - - underTest.activateAndCommit(db.getSession(), builtInProfile, singleton(RuleActivation.create(rule.getUuid()))); + assertThatThrownBy(() -> { + underTest.activateAndCommit(db.getSession(), builtInProfile, singleton(RuleActivation.create(rule.getUuid()))); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("The built-in profile " + builtInProfile.getName() + " is read-only and can't be updated"); } private void assertThatProfileHasNoActiveRules(QProfileDto profile) { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/QProfileTreeImplTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/QProfileTreeImplTest.java index f8bf0de5793..8d1d41d0233 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/QProfileTreeImplTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/QProfileTreeImplTest.java @@ -25,7 +25,6 @@ import java.util.Optional; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.impl.utils.AlwaysIncreasingSystem2; import org.sonar.api.rule.RuleStatus; import org.sonar.api.rule.Severity; @@ -47,14 +46,12 @@ import static java.util.Arrays.asList; import static java.util.Collections.emptyMap; import static java.util.Collections.singleton; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.rule.Severity.BLOCKER; import static org.sonar.server.qualityprofile.ActiveRuleInheritance.INHERITED; public class QProfileTreeImplTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); - private System2 system2 = new AlwaysIncreasingSystem2(); @Rule public DbTester db = DbTester.create(system2); @@ -73,10 +70,9 @@ public class QProfileTreeImplTest { RuleDefinitionDto rule = createRule(); QProfileDto profile = createProfile(rule); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage(" can not be selected as parent of "); - - underTest.setParentAndCommit(db.getSession(), profile, profile); + assertThatThrownBy(() -> underTest.setParentAndCommit(db.getSession(), profile, profile)) + .isInstanceOf(BadRequestException.class) + .hasMessageContaining(" can not be selected as parent of "); } @Test @@ -85,9 +81,9 @@ public class QProfileTreeImplTest { QProfileDto parentProfile = createProfile(rule); QProfileDto childProfile = createChildProfile(parentProfile); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage(" can not be selected as parent of "); - underTest.setParentAndCommit(db.getSession(), parentProfile, childProfile); + assertThatThrownBy(() -> underTest.setParentAndCommit(db.getSession(), parentProfile, childProfile)) + .isInstanceOf(BadRequestException.class) + .hasMessageContaining(" can not be selected as parent of "); } @Test @@ -97,9 +93,9 @@ public class QProfileTreeImplTest { QProfileDto childProfile = createChildProfile(parentProfile); QProfileDto grandchildProfile = createChildProfile(childProfile); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage(" can not be selected as parent of "); - underTest.setParentAndCommit(db.getSession(), parentProfile, grandchildProfile); + assertThatThrownBy(() -> underTest.setParentAndCommit(db.getSession(), parentProfile, grandchildProfile)) + .isInstanceOf(BadRequestException.class) + .hasMessageContaining(" can not be selected as parent of "); } @Test @@ -115,10 +111,9 @@ public class QProfileTreeImplTest { changes = activate(childProfile, RuleActivation.create(rule2.getUuid())); assertThat(changes).hasSize(1); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Cannot set the profile"); - - underTest.setParentAndCommit(db.getSession(), childProfile, parentProfile); + assertThatThrownBy(() -> underTest.setParentAndCommit(db.getSession(), childProfile, parentProfile)) + .isInstanceOf(BadRequestException.class) + .hasMessageContaining("Cannot set the profile"); } @Test @@ -209,7 +204,7 @@ public class QProfileTreeImplTest { } private void assertThatRuleIsActivated(QProfileDto profile, RuleDefinitionDto rule, @Nullable List changes, - String expectedSeverity, @Nullable ActiveRuleInheritance expectedInheritance, Map expectedParams) { + String expectedSeverity, @Nullable ActiveRuleInheritance expectedInheritance, Map expectedParams) { OrgActiveRuleDto activeRule = db.getDbClient().activeRuleDao().selectByProfile(db.getSession(), profile) .stream() .filter(ar -> ar.getRuleKey().equals(rule.getKey())) @@ -242,7 +237,7 @@ public class QProfileTreeImplTest { } private void assertThatRuleIsUpdated(QProfileDto profile, RuleDefinitionDto rule, - String expectedSeverity, @Nullable ActiveRuleInheritance expectedInheritance, Map expectedParams) { + String expectedSeverity, @Nullable ActiveRuleInheritance expectedInheritance, Map expectedParams) { OrgActiveRuleDto activeRule = db.getDbClient().activeRuleDao().selectByProfile(db.getSession(), profile) .stream() .filter(ar -> ar.getRuleKey().equals(rule.getKey())) diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/RegisterQualityProfilesNotificationTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/RegisterQualityProfilesNotificationTest.java index 61ced1e075f..3c90f266de6 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/RegisterQualityProfilesNotificationTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/RegisterQualityProfilesNotificationTest.java @@ -28,7 +28,6 @@ import java.util.Random; import java.util.function.Consumer; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; import org.sonar.api.rule.RuleKey; import org.sonar.api.rule.Severity; @@ -84,8 +83,6 @@ public class RegisterQualityProfilesNotificationTest { @Rule public UserSessionRule userSessionRule = UserSessionRule.standalone(); @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Rule public BuiltInQProfileRepositoryRule builtInQProfileRepositoryRule = new BuiltInQProfileRepositoryRule(); @Rule public LogTester logTester = new LogTester(); diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/RegisterQualityProfilesTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/RegisterQualityProfilesTest.java index be8e22f8b3f..4187524f5cf 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/RegisterQualityProfilesTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/RegisterQualityProfilesTest.java @@ -25,7 +25,6 @@ import java.util.List; import java.util.Optional; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.impl.utils.AlwaysIncreasingSystem2; import org.sonar.api.resources.Language; import org.sonar.api.utils.System2; @@ -42,6 +41,7 @@ import org.sonar.server.tester.UserSessionRule; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.sonar.db.qualityprofile.QualityProfileTesting.newQualityProfileDto; import static org.sonar.db.qualityprofile.QualityProfileTesting.newRuleProfileDto; @@ -56,8 +56,6 @@ public class RegisterQualityProfilesTest { @Rule public UserSessionRule userSessionRule = UserSessionRule.standalone(); @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Rule public BuiltInQProfileRepositoryRule builtInQProfileRepositoryRule = new BuiltInQProfileRepositoryRule(); @Rule public LogTester logTester = new LogTester(); @@ -70,10 +68,9 @@ public class RegisterQualityProfilesTest { @Test public void start_fails_if_BuiltInQProfileRepository_has_not_been_initialized() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("initialize must be called first"); - - underTest.start(); + assertThatThrownBy(() -> underTest.start()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("initialize must be called first"); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/ActivateRuleActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/ActivateRuleActionTest.java index bf7603d5c51..8e03c2c5930 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/ActivateRuleActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/ActivateRuleActionTest.java @@ -24,7 +24,6 @@ import java.util.Collection; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; import org.mockito.MockitoAnnotations; import org.sonar.api.rule.RuleKey; @@ -50,6 +49,7 @@ import org.sonar.server.ws.WsActionTester; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyCollection; import static org.mockito.Mockito.mock; @@ -64,8 +64,6 @@ public class ActivateRuleActionTest { public DbTester db = DbTester.create(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private final ArgumentCaptor> ruleActivationCaptor = ArgumentCaptor.forClass(Collection.class); private final DbClient dbClient = db.getDbClient(); @@ -94,9 +92,8 @@ public class ActivateRuleActionTest { .setParam(PARAM_RULE, RuleTesting.newRule().getKey().toString()) .setParam(PARAM_KEY, randomAlphanumeric(UUID_SIZE)); - expectedException.expect(UnauthorizedException.class); - - request.execute(); + assertThatThrownBy(() -> request.execute()) + .isInstanceOf(UnauthorizedException.class); } @Test @@ -108,9 +105,8 @@ public class ActivateRuleActionTest { .setParam(PARAM_RULE, RuleTesting.newRule().getKey().toString()) .setParam(PARAM_KEY, qualityProfile.getKee()); - expectedException.expect(ForbiddenException.class); - - request.execute(); + assertThatThrownBy(() -> request.execute()) + .isInstanceOf(ForbiddenException.class); } @Test @@ -123,10 +119,9 @@ public class ActivateRuleActionTest { .setParam(PARAM_RULE, RuleTesting.newRule().getKey().toString()) .setParam(PARAM_KEY, qualityProfile.getKee()); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Operation forbidden for built-in Quality Profile 'Xoo profile' with language 'xoo'"); - - request.execute(); + assertThatThrownBy(() -> request.execute()) + .isInstanceOf(BadRequestException.class) + .hasMessage("Operation forbidden for built-in Quality Profile 'Xoo profile' with language 'xoo'"); } @Test @@ -140,10 +135,9 @@ public class ActivateRuleActionTest { .setParam(PARAM_RULE, rule.getKey().toString()) .setParam(PARAM_KEY, qualityProfile.getKee()); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage(String.format("Operation forbidden for rule '%s' imported from an external rule engine.", rule.getKey())); - - request.execute(); + assertThatThrownBy(() -> request.execute()) + .isInstanceOf(BadRequestException.class) + .hasMessage(String.format("Operation forbidden for rule '%s' imported from an external rule engine.", rule.getKey())); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/ActivateRulesActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/ActivateRulesActionTest.java index 48cad343554..19a315e94b2 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/ActivateRulesActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/ActivateRulesActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.qualityprofile.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.Mockito; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbClient; @@ -40,6 +39,7 @@ import org.sonar.server.ws.WsActionTester; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -53,8 +53,6 @@ public class ActivateRulesActionTest { public DbTester db = DbTester.create(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private DbClient dbClient = db.getDbClient(); private final QProfileWsSupport wsSupport = new QProfileWsSupport(dbClient, userSession); @@ -130,9 +128,8 @@ public class ActivateRulesActionTest { .setMethod("POST") .setParam(PARAM_TARGET_KEY, randomAlphanumeric(UUID_SIZE)); - expectedException.expect(UnauthorizedException.class); - - request.execute(); + assertThatThrownBy(() -> request.execute()) + .isInstanceOf(UnauthorizedException.class); } @Test @@ -143,9 +140,8 @@ public class ActivateRulesActionTest { .setMethod("POST") .setParam(PARAM_TARGET_KEY, qualityProfile.getKee()); - expectedException.expect(BadRequestException.class); - - request.execute(); + assertThatThrownBy(() -> request.execute()) + .isInstanceOf(BadRequestException.class); } @Test @@ -153,11 +149,12 @@ public class ActivateRulesActionTest { userSession.logIn(db.users().insertUser()); QProfileDto qualityProfile = db.qualityProfiles().insert(); - expectedException.expect(ForbiddenException.class); - - ws.newRequest() - .setMethod("POST") - .setParam(PARAM_TARGET_KEY, qualityProfile.getKee()) - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setMethod("POST") + .setParam(PARAM_TARGET_KEY, qualityProfile.getKee()) + .execute(); + }) + .isInstanceOf(ForbiddenException.class); } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/AddGroupActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/AddGroupActionTest.java index bb815db29cc..42d4fa9efa5 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/AddGroupActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/AddGroupActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.qualityprofile.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.resources.Languages; import org.sonar.api.server.ws.WebService; import org.sonar.core.util.UuidFactory; @@ -41,6 +40,7 @@ import org.sonar.server.ws.WsActionTester; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_GROUP; import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_LANGUAGE; import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_QUALITY_PROFILE; @@ -50,8 +50,6 @@ public class AddGroupActionTest { private static final String XOO = "xoo"; private static final Languages LANGUAGES = LanguageTesting.newLanguages(XOO); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -173,14 +171,15 @@ public class AddGroupActionTest { QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO)); userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("No group with name 'unknown'"); - - ws.newRequest() - .setParam(PARAM_QUALITY_PROFILE, profile.getName()) - .setParam(PARAM_LANGUAGE, XOO) - .setParam(PARAM_GROUP, "unknown") - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam(PARAM_QUALITY_PROFILE, profile.getName()) + .setParam(PARAM_LANGUAGE, XOO) + .setParam(PARAM_GROUP, "unknown") + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("No group with name 'unknown'"); } @Test @@ -188,14 +187,15 @@ public class AddGroupActionTest { GroupDto group = db.users().insertGroup(); userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Quality Profile for language 'xoo' and name 'unknown' does not exist"); - - ws.newRequest() - .setParam(PARAM_QUALITY_PROFILE, "unknown") - .setParam(PARAM_LANGUAGE, XOO) - .setParam(PARAM_GROUP, group.getName()) - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam(PARAM_QUALITY_PROFILE, "unknown") + .setParam(PARAM_LANGUAGE, XOO) + .setParam(PARAM_GROUP, group.getName()) + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("Quality Profile for language 'xoo' and name 'unknown' does not exist"); } @Test @@ -204,14 +204,15 @@ public class AddGroupActionTest { UserDto user = db.users().insertUser(); userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(format("Quality Profile for language 'xoo' and name '%s' does not exist", profile.getName())); - - ws.newRequest() - .setParam(PARAM_QUALITY_PROFILE, profile.getName()) - .setParam(PARAM_LANGUAGE, XOO) - .setParam(PARAM_GROUP, user.getLogin()) - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam(PARAM_QUALITY_PROFILE, profile.getName()) + .setParam(PARAM_LANGUAGE, XOO) + .setParam(PARAM_GROUP, user.getLogin()) + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage(format("Quality Profile for language 'xoo' and name '%s' does not exist", profile.getName())); } @Test @@ -220,14 +221,15 @@ public class AddGroupActionTest { QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO).setIsBuiltIn(true)); userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage(String.format("Operation forbidden for built-in Quality Profile '%s' with language 'xoo'", profile.getName())); - - ws.newRequest() - .setParam(PARAM_QUALITY_PROFILE, profile.getName()) - .setParam(PARAM_LANGUAGE, XOO) - .setParam(PARAM_GROUP, user.getLogin()) - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam(PARAM_QUALITY_PROFILE, profile.getName()) + .setParam(PARAM_LANGUAGE, XOO) + .setParam(PARAM_GROUP, user.getLogin()) + .execute(); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage(String.format("Operation forbidden for built-in Quality Profile '%s' with language 'xoo'", profile.getName())); } @Test @@ -236,12 +238,13 @@ public class AddGroupActionTest { UserDto user = db.users().insertUser(); userSession.logIn(db.users().insertUser()).addPermission(GlobalPermission.ADMINISTER_QUALITY_GATES); - expectedException.expect(ForbiddenException.class); - - ws.newRequest() - .setParam(PARAM_QUALITY_PROFILE, profile.getName()) - .setParam(PARAM_LANGUAGE, XOO) - .setParam(PARAM_GROUP, user.getLogin()) - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam(PARAM_QUALITY_PROFILE, profile.getName()) + .setParam(PARAM_LANGUAGE, XOO) + .setParam(PARAM_GROUP, user.getLogin()) + .execute(); + }) + .isInstanceOf(ForbiddenException.class); } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/AddProjectActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/AddProjectActionTest.java index ae61598c0d4..ca7d402df11 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/AddProjectActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/AddProjectActionTest.java @@ -22,7 +22,6 @@ package org.sonar.server.qualityprofile.ws; import java.net.HttpURLConnection; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.resources.Languages; import org.sonar.api.server.ws.WebService; import org.sonar.api.web.UserRole; @@ -44,6 +43,7 @@ import org.sonar.server.ws.WsActionTester; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES; public class AddProjectActionTest { @@ -54,8 +54,6 @@ public class AddProjectActionTest { @Rule public DbTester db = DbTester.create(); @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Rule public UserSessionRule userSession = UserSessionRule.standalone(); private final DbClient dbClient = db.getDbClient(); @@ -153,10 +151,9 @@ public class AddProjectActionTest { ProjectDto project = db.components().insertPrivateProjectDto(); QProfileDto profile = db.qualityProfiles().insert(qp -> qp.setLanguage("xoo")); - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - - call(project, profile); + assertThatThrownBy(() -> call(project, profile)) + .isInstanceOf(ForbiddenException.class) + .hasMessage("Insufficient privileges"); } @Test @@ -165,10 +162,9 @@ public class AddProjectActionTest { ProjectDto project = db.components().insertPrivateProjectDto(); QProfileDto profile = db.qualityProfiles().insert(); - expectedException.expect(UnauthorizedException.class); - expectedException.expectMessage("Authentication is required"); - - call(project, profile); + assertThatThrownBy(() -> call(project, profile)) + .isInstanceOf(UnauthorizedException.class) + .hasMessage("Authentication is required"); } @Test @@ -176,13 +172,14 @@ public class AddProjectActionTest { logInAsProfileAdmin(); QProfileDto profile = db.qualityProfiles().insert(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Project 'unknown' not found"); - - tester.newRequest() - .setParam("project", "unknown") - .setParam("profileKey", profile.getKee()) - .execute(); + assertThatThrownBy(() -> { + tester.newRequest() + .setParam("project", "unknown") + .setParam("profileKey", profile.getKee()) + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("Project 'unknown' not found"); } @Test @@ -190,14 +187,15 @@ public class AddProjectActionTest { logInAsProfileAdmin(); ComponentDto project = db.components().insertPrivateProject(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Quality Profile for language 'xoo' and name 'unknown' does not exist"); - - tester.newRequest() - .setParam("project", project.getKey()) - .setParam("language", "xoo") - .setParam("qualityProfile", "unknown") - .execute(); + assertThatThrownBy(() -> { + tester.newRequest() + .setParam("project", project.getKey()) + .setParam("language", "xoo") + .setParam("qualityProfile", "unknown") + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("Quality Profile for language 'xoo' and name 'unknown' does not exist"); } @Test @@ -207,13 +205,14 @@ public class AddProjectActionTest { ComponentDto branch = db.components().insertProjectBranch(project); QProfileDto profile = db.qualityProfiles().insert(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(format("Project '%s' not found", branch.getDbKey())); - - tester.newRequest() - .setParam("project", branch.getDbKey()) - .setParam("profileKey", profile.getKee()) - .execute(); + assertThatThrownBy(() -> { + tester.newRequest() + .setParam("project", branch.getDbKey()) + .setParam("profileKey", profile.getKee()) + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage(format("Project '%s' not found", branch.getDbKey())); } private void assertProjectIsAssociatedToProfile(ProjectDto project, QProfileDto profile) { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/AddUserActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/AddUserActionTest.java index fed301d82b0..4f4a3171f9e 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/AddUserActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/AddUserActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.qualityprofile.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.resources.Languages; import org.sonar.api.server.ws.WebService; import org.sonar.core.util.UuidFactory; @@ -40,6 +39,7 @@ import org.sonar.server.ws.WsActionTester; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_LANGUAGE; import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_LOGIN; import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_QUALITY_PROFILE; @@ -49,8 +49,6 @@ public class AddUserActionTest { private static final String XOO = "xoo"; private static final Languages LANGUAGES = LanguageTesting.newLanguages(XOO); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -139,14 +137,13 @@ public class AddUserActionTest { QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO)); userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("User with login 'unknown' is not found"); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_QUALITY_PROFILE, profile.getName()) .setParam(PARAM_LANGUAGE, XOO) .setParam(PARAM_LOGIN, "unknown") - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("User with login 'unknown' is not found"); } @Test @@ -154,14 +151,15 @@ public class AddUserActionTest { UserDto user = db.users().insertUser(); userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Quality Profile for language 'xoo' and name 'unknown' does not exist"); - - ws.newRequest() - .setParam(PARAM_QUALITY_PROFILE, "unknown") - .setParam(PARAM_LANGUAGE, XOO) - .setParam(PARAM_LOGIN, user.getLogin()) - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam(PARAM_QUALITY_PROFILE, "unknown") + .setParam(PARAM_LANGUAGE, XOO) + .setParam(PARAM_LOGIN, user.getLogin()) + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("Quality Profile for language 'xoo' and name 'unknown' does not exist"); } @Test @@ -170,13 +168,15 @@ public class AddUserActionTest { UserDto user = db.users().insertUser(); userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(format("Quality Profile for language 'xoo' and name '%s' does not exist", profile.getName())); - ws.newRequest() - .setParam(PARAM_QUALITY_PROFILE, profile.getName()) - .setParam(PARAM_LANGUAGE, XOO) - .setParam(PARAM_LOGIN, user.getLogin()) - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam(PARAM_QUALITY_PROFILE, profile.getName()) + .setParam(PARAM_LANGUAGE, XOO) + .setParam(PARAM_LOGIN, user.getLogin()) + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage(format("Quality Profile for language 'xoo' and name '%s' does not exist", profile.getName())); } @Test @@ -185,14 +185,15 @@ public class AddUserActionTest { QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO).setIsBuiltIn(true)); userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage(String.format("Operation forbidden for built-in Quality Profile '%s' with language 'xoo'", profile.getName())); - - ws.newRequest() - .setParam(PARAM_QUALITY_PROFILE, profile.getName()) - .setParam(PARAM_LANGUAGE, XOO) - .setParam(PARAM_LOGIN, user.getLogin()) - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam(PARAM_QUALITY_PROFILE, profile.getName()) + .setParam(PARAM_LANGUAGE, XOO) + .setParam(PARAM_LOGIN, user.getLogin()) + .execute(); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage(String.format("Operation forbidden for built-in Quality Profile '%s' with language 'xoo'", profile.getName())); } @Test @@ -201,12 +202,13 @@ public class AddUserActionTest { UserDto user = db.users().insertUser(); userSession.logIn(db.users().insertUser()).addPermission(GlobalPermission.ADMINISTER_QUALITY_GATES); - expectedException.expect(ForbiddenException.class); - - ws.newRequest() - .setParam(PARAM_QUALITY_PROFILE, profile.getName()) - .setParam(PARAM_LANGUAGE, XOO) - .setParam(PARAM_LOGIN, user.getLogin()) - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam(PARAM_QUALITY_PROFILE, profile.getName()) + .setParam(PARAM_LANGUAGE, XOO) + .setParam(PARAM_LOGIN, user.getLogin()) + .execute(); + }) + .isInstanceOf(ForbiddenException.class); } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/ChangeParentActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/ChangeParentActionTest.java index 3dbcd8d6cab..b0eb360194b 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/ChangeParentActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/ChangeParentActionTest.java @@ -24,7 +24,6 @@ import java.util.List; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.resources.Language; import org.sonar.api.resources.Languages; import org.sonar.api.rule.RuleKey; @@ -64,6 +63,7 @@ import org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters; import static java.util.Arrays.asList; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES; import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_LANGUAGE; import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_PARENT_QUALITY_PROFILE; @@ -77,8 +77,6 @@ public class ChangeParentActionTest { public EsTester es = EsTester.create(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private DbClient dbClient; private DbSession dbSession; @@ -339,9 +337,8 @@ public class ChangeParentActionTest { .setParam(PARAM_QUALITY_PROFILE, child.getName()) .setParam(PARAM_PARENT_QUALITY_PROFILE, "palap"); - expectedException.expect(BadRequestException.class); - - request.execute(); + assertThatThrownBy(request::execute) + .isInstanceOf(BadRequestException.class); } @Test @@ -355,9 +352,9 @@ public class ChangeParentActionTest { .setParam(PARAM_LANGUAGE, child.getLanguage()) .setParam(PARAM_QUALITY_PROFILE, child.getName()); - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - request.execute(); + assertThatThrownBy(request::execute) + .isInstanceOf(ForbiddenException.class) + .hasMessage("Insufficient privileges"); } private QProfileDto createProfile() { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/ChangelogActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/ChangelogActionTest.java index 12107d13173..47af3d270f2 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/ChangelogActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/ChangelogActionTest.java @@ -26,7 +26,6 @@ import java.util.function.Consumer; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.impl.utils.TestSystem2; import org.sonar.api.resources.Languages; import org.sonar.api.rule.RuleKey; @@ -58,8 +57,6 @@ public class ChangelogActionTest { public DbTester db = DbTester.create(system2); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private final QProfileWsSupport wsSupport = new QProfileWsSupport(db.getDbClient(), userSession); private final WsActionTester ws = new WsActionTester(new ChangelogAction(wsSupport, new Languages(), db.getDbClient())); diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/CompareActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/CompareActionTest.java index 10b08e5e66c..3752b42c3cc 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/CompareActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/CompareActionTest.java @@ -22,7 +22,6 @@ package org.sonar.server.qualityprofile.ws; import org.apache.commons.lang.StringUtils; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.resources.Languages; import org.sonar.api.rule.RuleKey; import org.sonar.api.rule.RuleStatus; @@ -48,6 +47,7 @@ import org.sonar.server.ws.WsActionTester; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class CompareActionTest { @@ -56,8 +56,6 @@ public class CompareActionTest { @Rule public UserSessionRule userSessionRule = UserSessionRule.standalone(); @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Rule public UserSessionRule userSession = UserSessionRule.standalone(); private DbClient dbClient = db.getDbClient(); @@ -141,36 +139,50 @@ public class CompareActionTest { .execute().assertJson(this.getClass(), "compare_param_on_right.json"); } - @Test(expected = IllegalArgumentException.class) + @Test public void fail_on_missing_left_param() { - ws.newRequest() - .setParam("rightKey", "polop") - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam("rightKey", "polop") + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class); } - @Test(expected = IllegalArgumentException.class) + @Test public void fail_on_missing_right_param() { - ws.newRequest() - .setParam("leftKey", "polop") - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam("leftKey", "polop") + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class); } - @Test(expected = IllegalArgumentException.class) + @Test public void fail_on_left_profile_not_found() { createProfile("xoo", "Right", "xoo-right-12345"); - ws.newRequest() - .setParam("leftKey", "polop") - .setParam("rightKey", "xoo-right-12345") - .execute(); + + assertThatThrownBy(() -> { + ws.newRequest() + .setParam("leftKey", "polop") + .setParam("rightKey", "xoo-right-12345") + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class); } - @Test(expected = IllegalArgumentException.class) + @Test public void fail_on_right_profile_not_found() { createProfile("xoo", "Left", "xoo-left-12345"); - ws.newRequest() - .setParam("leftKey", "xoo-left-12345") - .setParam("rightKey", "polop") - .execute(); + + assertThatThrownBy(() -> { + ws.newRequest() + .setParam("leftKey", "xoo-left-12345") + .setParam("rightKey", "polop") + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/CopyActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/CopyActionTest.java index 098bb51c7f7..22f358e464d 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/CopyActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/CopyActionTest.java @@ -24,7 +24,6 @@ import java.io.Writer; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.impl.utils.JUnitTempFolder; import org.sonar.api.resources.Languages; import org.sonar.api.server.ws.WebService; @@ -48,6 +47,7 @@ import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES; import static org.sonar.test.JsonAssert.assertJson; @@ -59,8 +59,6 @@ public class CopyActionTest { @Rule public DbTester db = DbTester.create(); @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public JUnitTempFolder tempDir = new JUnitTempFolder(); @@ -202,14 +200,15 @@ public class CopyActionTest { public void throw_UnauthorizedException_if_not_logged_in() { userSession.anonymous(); - expectedException.expect(UnauthorizedException.class); - expectedException.expectMessage("Authentication is required"); - - tester.newRequest() - .setMethod("POST") - .setParam("fromKey", "foo") - .setParam("toName", "bar") - .execute(); + assertThatThrownBy(() -> { + tester.newRequest() + .setMethod("POST") + .setParam("fromKey", "foo") + .setParam("toName", "bar") + .execute(); + }) + .isInstanceOf(UnauthorizedException.class) + .hasMessage("Authentication is required"); } @Test @@ -217,14 +216,15 @@ public class CopyActionTest { QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(A_LANGUAGE)); userSession.logIn().addPermission(GlobalPermission.SCAN); - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - - tester.newRequest() - .setMethod("POST") - .setParam("fromKey", profile.getKee()) - .setParam("toName", "bar") - .execute(); + assertThatThrownBy(() -> { + tester.newRequest() + .setMethod("POST") + .setParam("fromKey", profile.getKee()) + .setParam("toName", "bar") + .execute(); + }) + .isInstanceOf(ForbiddenException.class) + .hasMessage("Insufficient privileges"); } @Test @@ -232,38 +232,41 @@ public class CopyActionTest { QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(A_LANGUAGE)); userSession.logIn().addPermission(GlobalPermission.SCAN); - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - - tester.newRequest() - .setMethod("POST") - .setParam("fromKey", profile.getKee()) - .setParam("toName", "bar") - .execute(); + assertThatThrownBy(() -> { + tester.newRequest() + .setMethod("POST") + .setParam("fromKey", profile.getKee()) + .setParam("toName", "bar") + .execute(); + }) + .isInstanceOf(ForbiddenException.class) + .hasMessage("Insufficient privileges"); } @Test public void fail_if_parameter_fromKey_is_missing() { logInAsQProfileAdministrator(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The 'fromKey' parameter is missing"); - - tester.newRequest() - .setParam("toName", "bar") - .execute(); + assertThatThrownBy(() -> { + tester.newRequest() + .setParam("toName", "bar") + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("The 'fromKey' parameter is missing"); } @Test public void fail_if_parameter_toName_is_missing() { logInAsQProfileAdministrator(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The 'toName' parameter is missing"); - - tester.newRequest() - .setParam("fromKey", "foo") - .execute(); + assertThatThrownBy(() -> { + tester.newRequest() + .setParam("fromKey", "foo") + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("The 'toName' parameter is missing"); } private void logInAsQProfileAdministrator() { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/CreateActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/CreateActionTest.java index bff9b7c4004..9afe6b21139 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/CreateActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/CreateActionTest.java @@ -25,7 +25,6 @@ import java.util.Collections; import java.util.Map; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.profiles.ProfileImporter; import org.sonar.api.profiles.RulesProfile; import org.sonar.api.rules.RulePriority; @@ -62,6 +61,7 @@ import org.sonarqube.ws.Qualityprofiles.CreateWsResponse; import org.sonarqube.ws.Qualityprofiles.CreateWsResponse.QualityProfile; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES; import static org.sonar.db.permission.GlobalPermission.SCAN; import static org.sonar.server.language.LanguageTesting.newLanguages; @@ -74,8 +74,6 @@ public class CreateActionTest { .setLanguage(XOO_LANGUAGE) .getDefinition(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester db = DbTester.create(); @Rule @@ -159,20 +157,23 @@ public class CreateActionTest { .logIn() .addPermission(SCAN); - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - - executeRequest(ws.newRequest() - .setParam("name", "some Name") - .setParam("language", XOO_LANGUAGE)); + assertThatThrownBy(() -> { + executeRequest(ws.newRequest() + .setParam("name", "some Name") + .setParam("language", XOO_LANGUAGE)); + }) + .isInstanceOf(ForbiddenException.class) + .hasMessage("Insufficient privileges"); } @Test public void fail_if_import_generate_error() { logInAsQProfileAdministrator(); - expectedException.expect(BadRequestException.class); - executeRequest("Profile with errors", XOO_LANGUAGE, ImmutableMap.of("with_errors", "")); + assertThatThrownBy(() -> { + executeRequest("Profile with errors", XOO_LANGUAGE, ImmutableMap.of("with_errors", "")); + }) + .isInstanceOf(BadRequestException.class); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/DeactivateRuleActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/DeactivateRuleActionTest.java index befb8c9a1e0..2a4423398c1 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/DeactivateRuleActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/DeactivateRuleActionTest.java @@ -24,7 +24,6 @@ import java.util.Collection; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; import org.mockito.MockitoAnnotations; import org.sonar.api.rule.RuleKey; @@ -47,6 +46,7 @@ import org.sonar.server.ws.WsActionTester; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyCollection; import static org.mockito.Mockito.mock; @@ -60,8 +60,6 @@ public class DeactivateRuleActionTest { public DbTester db = DbTester.create(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private final ArgumentCaptor> ruleUuidsCaptor = ArgumentCaptor.forClass(Collection.class); private final DbClient dbClient = db.getDbClient(); @@ -127,9 +125,8 @@ public class DeactivateRuleActionTest { .setParam(PARAM_RULE, RuleTesting.newRule().getKey().toString()) .setParam(PARAM_KEY, randomAlphanumeric(UUID_SIZE)); - expectedException.expect(UnauthorizedException.class); - - request.execute(); + assertThatThrownBy(request::execute) + .isInstanceOf(UnauthorizedException.class); } @Test @@ -143,10 +140,9 @@ public class DeactivateRuleActionTest { .setParam(PARAM_RULE, rule.getKey().toString()) .setParam(PARAM_KEY, qualityProfile.getKee()); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage(String.format("Operation forbidden for rule '%s' imported from an external rule engine.", rule.getKey())); - - request.execute(); + assertThatThrownBy(() -> request.execute()) + .isInstanceOf(BadRequestException.class) + .hasMessage(String.format("Operation forbidden for rule '%s' imported from an external rule engine.", rule.getKey())); } @Test @@ -160,8 +156,7 @@ public class DeactivateRuleActionTest { .setParam(PARAM_RULE, rule.getKey().toString()) .setParam(PARAM_KEY, qualityProfile.getKee()); - expectedException.expect(BadRequestException.class); - - request.execute(); + assertThatThrownBy(request::execute) + .isInstanceOf(BadRequestException.class); } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/DeactivateRulesActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/DeactivateRulesActionTest.java index 89b9956b63c..5436982fe6b 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/DeactivateRulesActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/DeactivateRulesActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.qualityprofile.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbClient; import org.sonar.db.DbTester; @@ -39,6 +38,7 @@ import org.sonar.server.ws.WsActionTester; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.mock; @@ -54,8 +54,6 @@ public class DeactivateRulesActionTest { public DbTester db = DbTester.create(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); - @Rule - public ExpectedException thrown = ExpectedException.none(); private DbClient dbClient = db.getDbClient(); private QProfileRules qProfileRules = mock(QProfileRules.class, RETURNS_DEEP_STUBS); @@ -131,8 +129,8 @@ public class DeactivateRulesActionTest { .setMethod("POST") .setParam(PARAM_TARGET_KEY, randomAlphanumeric(UUID_SIZE)); - thrown.expect(UnauthorizedException.class); - request.execute(); + assertThatThrownBy(request::execute) + .isInstanceOf(UnauthorizedException.class); } @Test @@ -143,9 +141,8 @@ public class DeactivateRulesActionTest { .setMethod("POST") .setParam(PARAM_TARGET_KEY, qualityProfile.getKee()); - thrown.expect(BadRequestException.class); - - request.execute(); + assertThatThrownBy(request::execute) + .isInstanceOf(BadRequestException.class); } @Test @@ -156,7 +153,7 @@ public class DeactivateRulesActionTest { .setMethod("POST") .setParam(PARAM_TARGET_KEY, qualityProfile.getKee()); - thrown.expect(ForbiddenException.class); - request.execute(); + assertThatThrownBy(request::execute) + .isInstanceOf(ForbiddenException.class); } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/DeleteActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/DeleteActionTest.java index bb694f75e70..3cbd6a9f72a 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/DeleteActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/DeleteActionTest.java @@ -22,7 +22,6 @@ package org.sonar.server.qualityprofile.ws; import java.net.HttpURLConnection; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.resources.Languages; import org.sonar.api.server.ws.WebService; import org.sonar.api.server.ws.WebService.Param; @@ -46,6 +45,7 @@ import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES; import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_KEY; @@ -59,8 +59,6 @@ public class DeleteActionTest { @Rule public DbTester db = DbTester.create(System2.INSTANCE); @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Rule public UserSessionRule userSession = UserSessionRule.standalone(); private final DbClient dbClient = db.getDbClient(); @@ -116,13 +114,14 @@ public class DeleteActionTest { QProfileDto profile1 = db.qualityProfiles().insert(p -> p.setIsBuiltIn(true).setLanguage(A_LANGUAGE)); logInAsQProfileAdministrator(); - expectedException.expect(BadRequestException.class); - - ws.newRequest() - .setMethod("POST") - .setParam(PARAM_LANGUAGE, profile1.getLanguage()) - .setParam(PARAM_QUALITY_PROFILE, profile1.getName()) - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setMethod("POST") + .setParam(PARAM_LANGUAGE, profile1.getLanguage()) + .setParam(PARAM_QUALITY_PROFILE, profile1.getName()) + .execute(); + }) + .isInstanceOf(BadRequestException.class); } @Test @@ -130,38 +129,41 @@ public class DeleteActionTest { QProfileDto qprofile = createProfile(); userSession.logIn(db.users().insertUser()); - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - - ws.newRequest() - .setMethod("POST") - .setParam(PARAM_LANGUAGE, qprofile.getLanguage()) - .setParam(PARAM_QUALITY_PROFILE, qprofile.getName()) - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setMethod("POST") + .setParam(PARAM_LANGUAGE, qprofile.getLanguage()) + .setParam(PARAM_QUALITY_PROFILE, qprofile.getName()) + .execute(); + }) + .isInstanceOf(ForbiddenException.class) + .hasMessage("Insufficient privileges"); } @Test public void fail_if_not_logged_in() { QProfileDto profile = createProfile(); - expectedException.expect(UnauthorizedException.class); - - ws.newRequest() - .setMethod("POST") - .setParam(PARAM_KEY, profile.getKee()) - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setMethod("POST") + .setParam(PARAM_KEY, profile.getKee()) + .execute(); + }) + .isInstanceOf(UnauthorizedException.class); } @Test public void fail_if_missing_parameters() { userSession.logIn(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The 'language' parameter is missing"); - - ws.newRequest() - .setMethod("POST") - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setMethod("POST") + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("The 'language' parameter is missing"); } @Test @@ -169,13 +171,14 @@ public class DeleteActionTest { QProfileDto profile = createProfile(); logInAsQProfileAdministrator(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The 'language' parameter is missing"); - - ws.newRequest() - .setMethod("POST") - .setParam("profileName", profile.getName()) - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setMethod("POST") + .setParam("profileName", profile.getName()) + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("The 'language' parameter is missing"); } @Test @@ -183,27 +186,29 @@ public class DeleteActionTest { QProfileDto profile = createProfile(); logInAsQProfileAdministrator(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The 'qualityProfile' parameter is missing"); - - ws.newRequest() - .setMethod("POST") - .setParam(PARAM_LANGUAGE, profile.getLanguage()) - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setMethod("POST") + .setParam(PARAM_LANGUAGE, profile.getLanguage()) + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("The 'qualityProfile' parameter is missing"); } @Test public void fail_if_profile_does_not_exist() { userSession.logIn(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Quality Profile for language 'xoo' and name 'does_not_exist' does not exist"); - - ws.newRequest() - .setMethod("POST") - .setParam(PARAM_QUALITY_PROFILE, "does_not_exist") - .setParam(PARAM_LANGUAGE, "xoo") - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setMethod("POST") + .setParam(PARAM_QUALITY_PROFILE, "does_not_exist") + .setParam(PARAM_LANGUAGE, "xoo") + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("Quality Profile for language 'xoo' and name 'does_not_exist' does not exist"); } @Test @@ -212,14 +217,15 @@ public class DeleteActionTest { db.qualityProfiles().setAsDefault(profile); logInAsQProfileAdministrator(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Profile '" + profile.getName() + "' cannot be deleted because it is marked as default"); - - ws.newRequest() - .setMethod("POST") - .setParam(PARAM_LANGUAGE, profile.getLanguage()) - .setParam(PARAM_QUALITY_PROFILE, profile.getName()) - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setMethod("POST") + .setParam(PARAM_LANGUAGE, profile.getLanguage()) + .setParam(PARAM_QUALITY_PROFILE, profile.getName()) + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Profile '" + profile.getName() + "' cannot be deleted because it is marked as default"); } @Test @@ -229,15 +235,16 @@ public class DeleteActionTest { db.qualityProfiles().setAsDefault(childProfile); logInAsQProfileAdministrator(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Profile '" + parentProfile.getName() + "' cannot be deleted because its descendant named '" + childProfile.getName() + - "' is marked as default"); - - ws.newRequest() - .setMethod("POST") - .setParam(PARAM_LANGUAGE, parentProfile.getLanguage()) - .setParam(PARAM_QUALITY_PROFILE, parentProfile.getName()) - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setMethod("POST") + .setParam(PARAM_LANGUAGE, parentProfile.getLanguage()) + .setParam(PARAM_QUALITY_PROFILE, parentProfile.getName()) + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Profile '" + parentProfile.getName() + "' cannot be deleted because its descendant named '" + childProfile.getName() + + "' is marked as default"); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/ExportActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/ExportActionTest.java index 75d92fd3230..4fa12601ddf 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/ExportActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/ExportActionTest.java @@ -26,7 +26,6 @@ import javax.annotation.Nullable; import org.apache.commons.lang.StringUtils; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.profiles.ProfileExporter; import org.sonar.api.profiles.RulesProfile; import org.sonar.api.server.ws.WebService; @@ -45,6 +44,7 @@ import org.sonar.server.ws.WsActionTester; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class ExportActionTest { @@ -55,8 +55,6 @@ public class ExportActionTest { public DbTester db = DbTester.create(System2.INSTANCE); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private final DbClient dbClient = db.getDbClient(); private final QProfileBackuper backuper = new TestBackuper(); @@ -105,23 +103,25 @@ public class ExportActionTest { @Test public void throw_NotFoundException_if_profile_with_specified_name_does_not_exist() { - expectedException.expect(NotFoundException.class); - - newWsActionTester().newRequest() - .setParam("language", XOO_LANGUAGE) - .setParam("exporterKey", "polop").execute(); + assertThatThrownBy(() -> { + newWsActionTester().newRequest() + .setParam("language", XOO_LANGUAGE) + .setParam("exporterKey", "polop").execute(); + }) + .isInstanceOf(NotFoundException.class); } @Test public void throw_IAE_if_export_with_specified_key_does_not_exist() { QProfileDto profile = createProfile(true); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Value of parameter 'exporterKey' (unknown) must be one of: [polop, palap]"); - - newWsActionTester(newExporter("polop"), newExporter("palap")).newRequest() - .setParam("language", XOO_LANGUAGE) - .setParam("exporterKey", "unknown").execute(); + assertThatThrownBy(() -> { + newWsActionTester(newExporter("polop"), newExporter("palap")).newRequest() + .setParam("language", XOO_LANGUAGE) + .setParam("exporterKey", "unknown").execute(); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Value of parameter 'exporterKey' (unknown) must be one of: [polop, palap]"); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/InheritanceActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/InheritanceActionTest.java index 3061c3b1a4c..3b66cfd2f20 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/InheritanceActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/InheritanceActionTest.java @@ -24,7 +24,6 @@ import java.util.ArrayList; import java.util.Date; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.resources.Languages; import org.sonar.api.rule.RuleKey; import org.sonar.api.rule.RuleStatus; @@ -59,6 +58,7 @@ import org.sonarqube.ws.Qualityprofiles.InheritanceWsResponse; import static java.util.Arrays.asList; import static java.util.Collections.singleton; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.test.JsonAssert.assertJson; import static org.sonarqube.ws.MediaTypes.PROTOBUF; import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_LANGUAGE; @@ -72,8 +72,6 @@ public class InheritanceActionTest { public EsTester es = EsTester.create(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private DbClient dbClient = db.getDbClient(); private DbSession dbSession = db.getSession(); @@ -204,12 +202,15 @@ public class InheritanceActionTest { assertJson(response).isSimilarTo(getClass().getResource("InheritanceActionTest/inheritance-simple.json")); } - @Test(expected = NotFoundException.class) + @Test public void fail_if_not_found() { - ws.newRequest() - .setParam(PARAM_LANGUAGE, "xoo") - .setParam(PARAM_QUALITY_PROFILE, "asd") - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam(PARAM_LANGUAGE, "xoo") + .setParam(PARAM_QUALITY_PROFILE, "asd") + .execute(); + }) + .isInstanceOf(NotFoundException.class); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/ProjectsActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/ProjectsActionTest.java index 67cfd2b8acf..f06404efe17 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/ProjectsActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/ProjectsActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.qualityprofile.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.api.server.ws.WebService.Param; import org.sonar.api.utils.System2; @@ -35,6 +34,7 @@ import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.server.ws.WebService.Param.PAGE; import static org.sonar.api.server.ws.WebService.Param.PAGE_SIZE; import static org.sonar.api.server.ws.WebService.Param.TEXT_QUERY; @@ -43,8 +43,6 @@ import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters. public class ProjectsActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester db = DbTester.create(System2.INSTANCE); @Rule @@ -292,11 +290,12 @@ public class ProjectsActionTest { @Test public void fail_on_nonexistent_profile() { - expectedException.expect(NotFoundException.class); - - ws.newRequest() - .setParam(PARAM_KEY, "unknown") - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam(PARAM_KEY, "unknown") + .execute(); + }) + .isInstanceOf(NotFoundException.class); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/QProfileReferenceTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/QProfileReferenceTest.java index 5741c543bd3..4bccc1dc98c 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/QProfileReferenceTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/QProfileReferenceTest.java @@ -19,20 +19,17 @@ */ package org.sonar.server.qualityprofile.ws; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.impl.ws.SimpleGetRequest; import org.sonar.api.resources.Languages; import org.sonar.api.server.ws.WebService; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.server.language.LanguageTesting.newLanguage; public class QProfileReferenceTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void fromKey_creates_reference_by_key() { @@ -45,18 +42,18 @@ public class QProfileReferenceTest { public void getLanguage_throws_ISE_on_reference_by_key() { QProfileReference ref = QProfileReference.fromKey("foo"); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Language is not defined. Please call hasKey()."); - ref.getLanguage(); + assertThatThrownBy(() -> ref.getLanguage()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Language is not defined. Please call hasKey()."); } @Test public void getName_throws_ISE_on_reference_by_key() { QProfileReference ref = QProfileReference.fromKey("foo"); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Name is not defined. Please call hasKey()."); - ref.getName(); + assertThatThrownBy(() -> ref.getName()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Name is not defined. Please call hasKey()."); } @Test @@ -71,10 +68,9 @@ public class QProfileReferenceTest { public void getKey_throws_ISE_on_reference_by_name() { QProfileReference ref = QProfileReference.fromName("js", "Sonar way"); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Key is not defined. Please call hasKey()."); - - ref.getKey(); + assertThatThrownBy(() -> ref.getKey()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Key is not defined. Please call hasKey()."); } @Test @@ -92,8 +88,8 @@ public class QProfileReferenceTest { public void throw_IAE_if_request_does_not_define_ref() { SimpleGetRequest req = new SimpleGetRequest(); - expectedException.expect(IllegalArgumentException.class); - QProfileReference.fromName(req); + assertThatThrownBy(() -> QProfileReference.fromName(req)) + .isInstanceOf(IllegalArgumentException.class); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/QProfileWsSupportTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/QProfileWsSupportTest.java index d49b654d8ec..12899be914e 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/QProfileWsSupportTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/QProfileWsSupportTest.java @@ -21,7 +21,6 @@ package org.sonar.server.qualityprofile.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.db.DbTester; import org.sonar.db.qualityprofile.QProfileDto; import org.sonar.db.qualityprofile.QualityProfileTesting; @@ -32,11 +31,10 @@ import org.sonar.server.tester.UserSessionRule; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class QProfileWsSupportTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester db = DbTester.create(); @Rule @@ -57,10 +55,9 @@ public class QProfileWsSupportTest { @Test public void getProfile_throws_NotFoundException_if_specified_key_does_not_exist() { - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Quality Profile with key 'missing' does not exist"); - - underTest.getProfile(db.getSession(), QProfileReference.fromKey("missing")); + assertThatThrownBy(() -> underTest.getProfile(db.getSession(), QProfileReference.fromKey("missing"))) + .isInstanceOf(NotFoundException.class) + .hasMessage("Quality Profile with key 'missing' does not exist"); } @Test @@ -80,19 +77,17 @@ public class QProfileWsSupportTest { QProfileDto profile = QualityProfileTesting.newQualityProfileDto(); db.qualityProfiles().insert(profile); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Quality Profile for language 'java' and name 'missing' does not exist"); - - underTest.getProfile(db.getSession(), QProfileReference.fromName("java", "missing")); + assertThatThrownBy(() -> underTest.getProfile(db.getSession(), QProfileReference.fromName("java", "missing"))) + .isInstanceOf(NotFoundException.class) + .hasMessage("Quality Profile for language 'java' and name 'missing' does not exist"); } @Test public void getRule_throws_BadRequest_if_rule_is_external() { RuleDefinitionDto rule = db.rules().insert(r -> r.setIsExternal(true)); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage(format("Operation forbidden for rule '%s' imported from an external rule engine.", rule.getKey())); - - underTest.getRule(db.getSession(), rule.getKey()); + assertThatThrownBy(() -> underTest.getRule(db.getSession(), rule.getKey())) + .isInstanceOf(BadRequestException.class) + .hasMessage(format("Operation forbidden for rule '%s' imported from an external rule engine.", rule.getKey())); } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/RemoveGroupActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/RemoveGroupActionTest.java index f855a3ac7e2..19df31aa12a 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/RemoveGroupActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/RemoveGroupActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.qualityprofile.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.resources.Languages; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbTester; @@ -39,6 +38,7 @@ import org.sonar.server.ws.WsActionTester; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_GROUP; import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_LANGUAGE; import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_QUALITY_PROFILE; @@ -48,8 +48,6 @@ public class RemoveGroupActionTest { private static final String XOO = "xoo"; private static final Languages LANGUAGES = LanguageTesting.newLanguages(XOO); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -140,14 +138,15 @@ public class RemoveGroupActionTest { QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO)); userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("No group with name 'unknown'"); - - ws.newRequest() - .setParam(PARAM_QUALITY_PROFILE, profile.getName()) - .setParam(PARAM_LANGUAGE, XOO) - .setParam(PARAM_GROUP, "unknown") - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam(PARAM_QUALITY_PROFILE, profile.getName()) + .setParam(PARAM_LANGUAGE, XOO) + .setParam(PARAM_GROUP, "unknown") + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("No group with name 'unknown'"); } @Test @@ -155,14 +154,15 @@ public class RemoveGroupActionTest { GroupDto group = db.users().insertGroup(); userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Quality Profile for language 'xoo' and name 'unknown' does not exist"); - - ws.newRequest() - .setParam(PARAM_QUALITY_PROFILE, "unknown") - .setParam(PARAM_LANGUAGE, XOO) - .setParam(PARAM_GROUP, group.getName()) - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam(PARAM_QUALITY_PROFILE, "unknown") + .setParam(PARAM_LANGUAGE, XOO) + .setParam(PARAM_GROUP, group.getName()) + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("Quality Profile for language 'xoo' and name 'unknown' does not exist"); } @Test @@ -171,14 +171,15 @@ public class RemoveGroupActionTest { GroupDto group = db.users().insertGroup(); userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(format("Quality Profile for language 'xoo' and name '%s' does not exist", profile.getName())); - - ws.newRequest() - .setParam(PARAM_QUALITY_PROFILE, profile.getName()) - .setParam(PARAM_LANGUAGE, XOO) - .setParam(PARAM_GROUP, group.getName()) - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam(PARAM_QUALITY_PROFILE, profile.getName()) + .setParam(PARAM_LANGUAGE, XOO) + .setParam(PARAM_GROUP, group.getName()) + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage(format("Quality Profile for language 'xoo' and name '%s' does not exist", profile.getName())); } @Test @@ -187,14 +188,15 @@ public class RemoveGroupActionTest { QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO).setIsBuiltIn(true)); userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage(String.format("Operation forbidden for built-in Quality Profile '%s' with language 'xoo'", profile.getName())); - - ws.newRequest() - .setParam(PARAM_QUALITY_PROFILE, profile.getName()) - .setParam(PARAM_LANGUAGE, XOO) - .setParam(PARAM_GROUP, group.getName()) - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam(PARAM_QUALITY_PROFILE, profile.getName()) + .setParam(PARAM_LANGUAGE, XOO) + .setParam(PARAM_GROUP, group.getName()) + .execute(); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage(String.format("Operation forbidden for built-in Quality Profile '%s' with language 'xoo'", profile.getName())); } @Test @@ -203,12 +205,13 @@ public class RemoveGroupActionTest { GroupDto group = db.users().insertGroup(); userSession.logIn(db.users().insertUser()).addPermission(GlobalPermission.ADMINISTER_QUALITY_GATES); - expectedException.expect(ForbiddenException.class); - - ws.newRequest() - .setParam(PARAM_QUALITY_PROFILE, profile.getName()) - .setParam(PARAM_LANGUAGE, XOO) - .setParam(PARAM_GROUP, group.getName()) - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam(PARAM_QUALITY_PROFILE, profile.getName()) + .setParam(PARAM_LANGUAGE, XOO) + .setParam(PARAM_GROUP, group.getName()) + .execute(); + }) + .isInstanceOf(ForbiddenException.class); } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/RemoveProjectActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/RemoveProjectActionTest.java index f014a7e885c..365327dd4a0 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/RemoveProjectActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/RemoveProjectActionTest.java @@ -22,7 +22,6 @@ package org.sonar.server.qualityprofile.ws; import java.net.HttpURLConnection; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.resources.Languages; import org.sonar.api.resources.Qualifiers; import org.sonar.api.server.ws.WebService; @@ -46,6 +45,7 @@ import org.sonar.server.ws.WsActionTester; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES; public class RemoveProjectActionTest { @@ -55,8 +55,6 @@ public class RemoveProjectActionTest { @Rule public DbTester db = DbTester.create(); @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Rule public UserSessionRule userSession = UserSessionRule.standalone(); private final DbClient dbClient = db.getDbClient(); @@ -146,10 +144,9 @@ public class RemoveProjectActionTest { ProjectDto project = db.components().insertPrivateProjectDto(); QProfileDto profile = db.qualityProfiles().insert(qp -> qp.setLanguage("xoo")); - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - - call(project, profile); + assertThatThrownBy(() -> call(project, profile)) + .isInstanceOf(ForbiddenException.class) + .hasMessage("Insufficient privileges"); } @Test @@ -158,10 +155,9 @@ public class RemoveProjectActionTest { ProjectDto project = db.components().insertPrivateProjectDto(); QProfileDto profile = db.qualityProfiles().insert(); - expectedException.expect(UnauthorizedException.class); - expectedException.expectMessage("Authentication is required"); - - call(project, profile); + assertThatThrownBy(() -> call(project, profile)) + .isInstanceOf(UnauthorizedException.class) + .hasMessage("Authentication is required"); } @Test @@ -169,13 +165,14 @@ public class RemoveProjectActionTest { logInAsProfileAdmin(); QProfileDto profile = db.qualityProfiles().insert(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Project 'unknown' not found"); - - ws.newRequest() - .setParam("project", "unknown") - .setParam("profileKey", profile.getKee()) - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam("project", "unknown") + .setParam("profileKey", profile.getKee()) + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("Project 'unknown' not found"); } @Test @@ -183,14 +180,15 @@ public class RemoveProjectActionTest { logInAsProfileAdmin(); ComponentDto project = db.components().insertPrivateProject(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Quality Profile for language 'xoo' and name 'unknown' does not exist"); - - ws.newRequest() - .setParam("project", project.getDbKey()) - .setParam("language", "xoo") - .setParam("qualityProfile", "unknown") - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam("project", project.getDbKey()) + .setParam("language", "xoo") + .setParam("qualityProfile", "unknown") + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("Quality Profile for language 'xoo' and name 'unknown' does not exist"); } @Test @@ -200,14 +198,15 @@ public class RemoveProjectActionTest { ComponentDto branch = db.components().insertProjectBranch(project); QProfileDto profile = db.qualityProfiles().insert(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(format("Project '%s' not found", branch.getDbKey())); - - ws.newRequest() - .setParam("project", branch.getDbKey()) - .setParam("language", profile.getLanguage()) - .setParam("qualityProfile", profile.getName()) - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam("project", branch.getDbKey()) + .setParam("language", profile.getLanguage()) + .setParam("qualityProfile", profile.getName()) + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage(format("Project '%s' not found", branch.getDbKey())); } private void assertProjectIsAssociatedToProfile(ProjectDto project, QProfileDto profile) { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/RemoveUserActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/RemoveUserActionTest.java index a749f83e3ca..2314ad00019 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/RemoveUserActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/RemoveUserActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.qualityprofile.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.resources.Languages; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbTester; @@ -38,6 +37,7 @@ import org.sonar.server.ws.WsActionTester; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES; import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_LANGUAGE; import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_LOGIN; @@ -48,8 +48,6 @@ public class RemoveUserActionTest { private static final String XOO = "xoo"; private static final Languages LANGUAGES = LanguageTesting.newLanguages(XOO); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -155,14 +153,13 @@ public class RemoveUserActionTest { QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO)); userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("User with login 'unknown' is not found"); - - ws.newRequest() - .setParam(PARAM_QUALITY_PROFILE, profile.getName()) - .setParam(PARAM_LANGUAGE, XOO) - .setParam(PARAM_LOGIN, "unknown") - .execute(); + assertThatThrownBy(() -> ws.newRequest() + .setParam(PARAM_QUALITY_PROFILE, profile.getName()) + .setParam(PARAM_LANGUAGE, XOO) + .setParam(PARAM_LOGIN, "unknown") + .execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("User with login 'unknown' is not found'"); } @Test @@ -170,14 +167,15 @@ public class RemoveUserActionTest { UserDto user = db.users().insertUser(); userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Quality Profile for language 'xoo' and name 'unknown' does not exist"); - - ws.newRequest() - .setParam(PARAM_QUALITY_PROFILE, "unknown") - .setParam(PARAM_LANGUAGE, XOO) - .setParam(PARAM_LOGIN, user.getLogin()) - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam(PARAM_QUALITY_PROFILE, "unknown") + .setParam(PARAM_LANGUAGE, XOO) + .setParam(PARAM_LOGIN, user.getLogin()) + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("Quality Profile for language 'xoo' and name 'unknown' does not exist"); } @Test @@ -186,14 +184,15 @@ public class RemoveUserActionTest { UserDto user = db.users().insertUser(); userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(format("Quality Profile for language 'xoo' and name '%s' does not exist", profile.getName())); - - ws.newRequest() - .setParam(PARAM_QUALITY_PROFILE, profile.getName()) - .setParam(PARAM_LANGUAGE, XOO) - .setParam(PARAM_LOGIN, user.getLogin()) - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam(PARAM_QUALITY_PROFILE, profile.getName()) + .setParam(PARAM_LANGUAGE, XOO) + .setParam(PARAM_LOGIN, user.getLogin()) + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage(format("Quality Profile for language 'xoo' and name '%s' does not exist", profile.getName())); } @Test @@ -201,14 +200,16 @@ public class RemoveUserActionTest { UserDto user = db.users().insertUser(); QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO).setIsBuiltIn(true)); userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage(String.format("Operation forbidden for built-in Quality Profile '%s' with language 'xoo'", profile.getName())); - ws.newRequest() - .setParam(PARAM_QUALITY_PROFILE, profile.getName()) - .setParam(PARAM_LANGUAGE, XOO) - .setParam(PARAM_LOGIN, user.getLogin()) - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam(PARAM_QUALITY_PROFILE, profile.getName()) + .setParam(PARAM_LANGUAGE, XOO) + .setParam(PARAM_LOGIN, user.getLogin()) + .execute(); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage(String.format("Operation forbidden for built-in Quality Profile '%s' with language 'xoo'", profile.getName())); } @Test @@ -217,12 +218,13 @@ public class RemoveUserActionTest { UserDto user = db.users().insertUser(); userSession.logIn(db.users().insertUser()).addPermission(GlobalPermission.ADMINISTER_QUALITY_GATES); - expectedException.expect(ForbiddenException.class); - - ws.newRequest() - .setParam(PARAM_QUALITY_PROFILE, profile.getName()) - .setParam(PARAM_LANGUAGE, XOO) - .setParam(PARAM_LOGIN, user.getLogin()) - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam(PARAM_QUALITY_PROFILE, profile.getName()) + .setParam(PARAM_LANGUAGE, XOO) + .setParam(PARAM_LOGIN, user.getLogin()) + .execute(); + }) + .isInstanceOf(ForbiddenException.class); } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/RenameActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/RenameActionTest.java index b63893eaab3..6775b601d9d 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/RenameActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/RenameActionTest.java @@ -23,7 +23,6 @@ import javax.annotation.Nullable; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.api.server.ws.WebService.Param; import org.sonar.api.utils.System2; @@ -42,6 +41,7 @@ import org.sonar.server.ws.WsActionTester; import static java.util.Optional.ofNullable; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES; import static org.sonar.db.permission.GlobalPermission.SCAN; @@ -51,8 +51,6 @@ public class RenameActionTest { public DbTester db = DbTester.create(System2.INSTANCE); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private DbClient dbClient = db.getDbClient(); @@ -97,10 +95,11 @@ public class RenameActionTest { db.qualityProfiles().insert(qualityProfile2); String qualityProfileKey2 = qualityProfile2.getKee(); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Quality profile already exists: Invalid, duplicated name"); - - call(qualityProfileKey1, "Invalid, duplicated name"); + assertThatThrownBy(() -> { + call(qualityProfileKey1, "Invalid, duplicated name"); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Quality profile already exists: Invalid, duplicated name"); } @Test @@ -120,20 +119,22 @@ public class RenameActionTest { public void fail_if_parameter_profile_is_missing() { logInAsQProfileAdministrator(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The 'key' parameter is missing"); - - call(null, "Other Sonar Way"); + assertThatThrownBy(() -> { + call(null, "Other Sonar Way"); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("The 'key' parameter is missing"); } @Test public void fail_if_parameter_name_is_missing() { logInAsQProfileAdministrator(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The 'name' parameter is missing"); - - call("sonar-way-xoo1-13245", null); + assertThatThrownBy(() -> { + call("sonar-way-xoo1-13245", null); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("The 'name' parameter is missing"); } @Test @@ -145,28 +146,31 @@ public class RenameActionTest { db.qualityProfiles().insert(qualityProfile); String qualityProfileKey = qualityProfile.getKee(); - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - - call(qualityProfileKey, "Hey look I am not quality profile admin!"); + assertThatThrownBy(() -> { + call(qualityProfileKey, "Hey look I am not quality profile admin!"); + }) + .isInstanceOf(ForbiddenException.class) + .hasMessage("Insufficient privileges"); } @Test public void fail_if_not_logged_in() { - expectedException.expect(UnauthorizedException.class); - expectedException.expectMessage("Authentication is required"); - - call("sonar-way-xoo1-13245", "Not logged in"); + assertThatThrownBy(() -> { + call("sonar-way-xoo1-13245", "Not logged in"); + }) + .isInstanceOf(UnauthorizedException.class) + .hasMessage("Authentication is required"); } @Test public void fail_if_profile_does_not_exist() { logInAsQProfileAdministrator(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Quality Profile with key 'polop' does not exist"); - - call("polop", "Uh oh, I don't know this profile"); + assertThatThrownBy(() -> { + call("polop", "Uh oh, I don't know this profile"); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("Quality Profile with key 'polop' does not exist"); } @Test @@ -174,29 +178,32 @@ public class RenameActionTest { logInAsQProfileAdministrator(); String qualityProfileKey = db.qualityProfiles().insert(p -> p.setIsBuiltIn(true)).getKee(); - expectedException.expect(BadRequestException.class); - - call(qualityProfileKey, "the new name"); + assertThatThrownBy(() -> { + call(qualityProfileKey, "the new name"); + }) + .isInstanceOf(BadRequestException.class); } @Test public void fail_if_blank_renaming() { String qualityProfileKey = createNewValidQualityProfileKey(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The 'name' parameter is missing"); - - call(qualityProfileKey, " "); + assertThatThrownBy(() -> { + call(qualityProfileKey, " "); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("The 'name' parameter is missing"); } @Test public void fail_renaming_if_profile_not_found() { logInAsQProfileAdministrator(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Quality Profile with key 'unknown' does not exist"); - - call("unknown", "the new name"); + assertThatThrownBy(() -> { + call("unknown", "the new name"); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("Quality Profile with key 'unknown' does not exist"); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/RestoreActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/RestoreActionTest.java index 20ba451f08c..1809086642f 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/RestoreActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/RestoreActionTest.java @@ -26,7 +26,6 @@ import javax.annotation.Nullable; import org.apache.commons.io.IOUtils; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.resources.Languages; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbSession; @@ -45,14 +44,13 @@ import org.sonar.server.ws.WsActionTester; import org.sonar.test.JsonAssert; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES; public class RestoreActionTest { private static final String A_LANGUAGE = "xoo"; - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester db = DbTester.create(); @Rule @@ -102,32 +100,35 @@ public class RestoreActionTest { public void throw_IAE_if_backup_is_missing() { logInAsQProfileAdministrator(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("A backup file must be provided"); - - tester.newRequest() - .setMethod("POST") - .execute(); + assertThatThrownBy(() -> { + tester.newRequest() + .setMethod("POST") + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("A backup file must be provided"); } @Test public void throw_ForbiddenException_if_not_profile_administrator() { userSession.logIn(); - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - - restore(""); + assertThatThrownBy(() -> { + restore(""); + }) + .isInstanceOf(ForbiddenException.class) + .hasMessage("Insufficient privileges"); } @Test public void throw_UnauthorizedException_if_not_logged_in() { userSession.anonymous(); - expectedException.expect(UnauthorizedException.class); - expectedException.expectMessage("Authentication is required"); - - restore(""); + assertThatThrownBy(() -> { + restore(""); + }) + .isInstanceOf(UnauthorizedException.class) + .hasMessage("Authentication is required"); } private void logInAsQProfileAdministrator() { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/SearchActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/SearchActionTest.java index a1f4c1dd19f..f72724412cb 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/SearchActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/SearchActionTest.java @@ -22,7 +22,6 @@ package org.sonar.server.qualityprofile.ws; import java.util.List; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.resources.Language; import org.sonar.api.resources.Languages; import org.sonar.api.server.ws.Change; @@ -50,6 +49,7 @@ import org.sonarqube.ws.Qualityprofiles.SearchWsResponse.QualityProfile; import static java.util.stream.IntStream.range; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.api.rule.RuleStatus.DEPRECATED; import static org.sonar.api.utils.DateUtils.parseDateTime; @@ -72,8 +72,6 @@ public class SearchActionTest { public DbTester db = DbTester.create(System2.INSTANCE); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private final QualityProfileDbTester qualityProfileDb = db.qualityProfiles(); private final DbClient dbClient = db.getDbClient(); @@ -364,10 +362,11 @@ public class SearchActionTest { @Test public void fail_if_project_does_not_exist() { - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Project 'unknown-project' not found"); - - call(ws.newRequest().setParam(PARAM_PROJECT, "unknown-project")); + assertThatThrownBy(() -> { + call(ws.newRequest().setParam(PARAM_PROJECT, "unknown-project")); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("Project 'unknown-project' not found"); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/SearchGroupsActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/SearchGroupsActionTest.java index 8457db9b844..e0df0b4fab2 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/SearchGroupsActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/SearchGroupsActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.qualityprofile.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.resources.Languages; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbTester; @@ -38,6 +37,7 @@ import org.sonarqube.ws.Qualityprofiles.SearchGroupsResponse; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.api.server.ws.WebService.Param.PAGE; import static org.sonar.api.server.ws.WebService.Param.PAGE_SIZE; @@ -55,8 +55,6 @@ public class SearchGroupsActionTest { private static final String FOO = "foo"; private static final Languages LANGUAGES = LanguageTesting.newLanguages(XOO, FOO); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -287,13 +285,14 @@ public class SearchGroupsActionTest { public void fail_when_qprofile_does_not_exist() { userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Quality Profile for language 'xoo' and name 'unknown' does not exist"); - - ws.newRequest() - .setParam(PARAM_QUALITY_PROFILE, "unknown") - .setParam(PARAM_LANGUAGE, XOO) - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam(PARAM_QUALITY_PROFILE, "unknown") + .setParam(PARAM_LANGUAGE, XOO) + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("Quality Profile for language 'xoo' and name 'unknown' does not exist"); } @Test @@ -301,13 +300,14 @@ public class SearchGroupsActionTest { QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO)); userSession.logIn().addPermission(ADMINISTER_QUALITY_PROFILES); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(format("Quality Profile for language 'foo' and name '%s' does not exist", profile.getName())); - - ws.newRequest() - .setParam(PARAM_QUALITY_PROFILE, profile.getName()) - .setParam(PARAM_LANGUAGE, FOO) - .executeProtobuf(SearchGroupsResponse.class); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam(PARAM_QUALITY_PROFILE, profile.getName()) + .setParam(PARAM_LANGUAGE, FOO) + .executeProtobuf(SearchGroupsResponse.class); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage(format("Quality Profile for language 'foo' and name '%s' does not exist", profile.getName())); } @Test @@ -315,11 +315,12 @@ public class SearchGroupsActionTest { QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(XOO)); userSession.logIn(db.users().insertUser()).addPermission(GlobalPermission.ADMINISTER_QUALITY_GATES); - expectedException.expect(ForbiddenException.class); - - ws.newRequest() - .setParam(PARAM_QUALITY_PROFILE, profile.getName()) - .setParam(PARAM_LANGUAGE, XOO) - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam(PARAM_QUALITY_PROFILE, profile.getName()) + .setParam(PARAM_LANGUAGE, XOO) + .execute(); + }) + .isInstanceOf(ForbiddenException.class); } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/SearchUsersActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/SearchUsersActionTest.java index 5c12e76502c..16d2f63e809 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/SearchUsersActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/SearchUsersActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.qualityprofile.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.resources.Languages; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbTester; @@ -40,6 +39,7 @@ import org.sonarqube.ws.Qualityprofiles.SearchUsersResponse; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.api.server.ws.WebService.Param.PAGE; import static org.sonar.api.server.ws.WebService.Param.PAGE_SIZE; @@ -57,8 +57,6 @@ public class SearchUsersActionTest { private static final String FOO = "foo"; private static final Languages LANGUAGES = LanguageTesting.newLanguages(XOO, FOO); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -232,8 +230,8 @@ public class SearchUsersActionTest { .setParam(PAGE, "1") .setParam(PAGE_SIZE, "1") .executeProtobuf(SearchUsersResponse.class).getUsersList()) - .extracting(SearchUsersResponse.User::getLogin) - .containsExactly(user1.getLogin()); + .extracting(SearchUsersResponse.User::getLogin) + .containsExactly(user1.getLogin()); assertThat(ws.newRequest() .setParam(PARAM_QUALITY_PROFILE, profile.getName()) @@ -242,8 +240,8 @@ public class SearchUsersActionTest { .setParam(PAGE, "3") .setParam(PAGE_SIZE, "1") .executeProtobuf(SearchUsersResponse.class).getUsersList()) - .extracting(SearchUsersResponse.User::getLogin) - .containsExactly(user3.getLogin()); + .extracting(SearchUsersResponse.User::getLogin) + .containsExactly(user3.getLogin()); assertThat(ws.newRequest() .setParam(PARAM_QUALITY_PROFILE, profile.getName()) @@ -252,8 +250,8 @@ public class SearchUsersActionTest { .setParam(PAGE, "1") .setParam(PAGE_SIZE, "10") .executeProtobuf(SearchUsersResponse.class).getUsersList()) - .extracting(SearchUsersResponse.User::getLogin) - .containsExactly(user1.getLogin(), user2.getLogin(), user3.getLogin()); + .extracting(SearchUsersResponse.User::getLogin) + .containsExactly(user1.getLogin(), user2.getLogin(), user3.getLogin()); } @Test @@ -309,13 +307,14 @@ public class SearchUsersActionTest { UserDto user = db.users().insertUser(); userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Quality Profile for language 'xoo' and name 'unknown' does not exist"); - - ws.newRequest() - .setParam(PARAM_QUALITY_PROFILE, "unknown") - .setParam(PARAM_LANGUAGE, XOO) - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam(PARAM_QUALITY_PROFILE, "unknown") + .setParam(PARAM_LANGUAGE, XOO) + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("Quality Profile for language 'xoo' and name 'unknown' does not exist"); } @Test @@ -325,13 +324,14 @@ public class SearchUsersActionTest { db.qualityProfiles().addUserPermission(profile, user1); userSession.logIn().addPermission(ADMINISTER_QUALITY_PROFILES); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(format("Quality Profile for language 'foo' and name '%s' does not exist", profile.getName())); - - ws.newRequest() - .setParam(PARAM_QUALITY_PROFILE, profile.getName()) - .setParam(PARAM_LANGUAGE, FOO) - .executeProtobuf(SearchUsersResponse.class); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam(PARAM_QUALITY_PROFILE, profile.getName()) + .setParam(PARAM_LANGUAGE, FOO) + .executeProtobuf(SearchUsersResponse.class); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage(format("Quality Profile for language 'foo' and name '%s' does not exist", profile.getName())); } @Test @@ -340,11 +340,11 @@ public class SearchUsersActionTest { UserDto user = db.users().insertUser(); userSession.logIn(db.users().insertUser()).addPermission(GlobalPermission.ADMINISTER_QUALITY_GATES); - expectedException.expect(ForbiddenException.class); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_QUALITY_PROFILE, profile.getName()) .setParam(PARAM_LANGUAGE, XOO) - .execute(); + .execute()) + .isInstanceOf(ForbiddenException.class) + .hasMessage("Insufficient privileges"); } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/SetDefaultActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/SetDefaultActionTest.java index c2b21fa95e4..77bf62f0732 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/SetDefaultActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/SetDefaultActionTest.java @@ -23,7 +23,6 @@ import org.assertj.core.api.Fail; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.api.server.ws.WebService.Param; import org.sonar.db.DbClient; @@ -39,6 +38,7 @@ import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES; import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_KEY; import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_LANGUAGE; @@ -49,8 +49,6 @@ public class SetDefaultActionTest { private static final String XOO_1_KEY = "xoo1"; private static final String XOO_2_KEY = "xoo2"; - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester db = DbTester.create(); @Rule @@ -134,23 +132,25 @@ public class SetDefaultActionTest { public void throw_ForbiddenException_if_not_profile_administrator() { userSessionRule.logIn(); - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - - ws.newRequest().setMethod("POST") - .setParam(PARAM_QUALITY_PROFILE, xoo2Profile.getName()) - .setParam(PARAM_LANGUAGE, xoo2Profile.getLanguage()) - .execute(); + assertThatThrownBy(() -> { + ws.newRequest().setMethod("POST") + .setParam(PARAM_QUALITY_PROFILE, xoo2Profile.getName()) + .setParam(PARAM_LANGUAGE, xoo2Profile.getLanguage()) + .execute(); + }) + .isInstanceOf(ForbiddenException.class) + .hasMessage("Insufficient privileges"); } @Test public void throw_UnauthorizedException_if_not_logged_in() { - expectedException.expect(UnauthorizedException.class); - expectedException.expectMessage("Authentication is required"); - - ws.newRequest().setMethod("POST") - .setParam(PARAM_KEY, xoo2Profile.getKee()) - .execute(); + assertThatThrownBy(() -> { + ws.newRequest().setMethod("POST") + .setParam(PARAM_KEY, xoo2Profile.getKee()) + .execute(); + }) + .isInstanceOf(UnauthorizedException.class) + .hasMessage("Authentication is required"); } private void logInAsQProfileAdministrator() { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/ShowActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/ShowActionTest.java index 69db2937342..480e3834c69 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/ShowActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/ws/ShowActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.qualityprofile.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.resources.Language; import org.sonar.api.resources.Languages; import org.sonar.api.server.ws.WebService; @@ -46,6 +45,7 @@ import org.sonarqube.ws.Qualityprofiles.ShowResponse.QualityProfile; import static java.util.stream.IntStream.range; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.rule.RuleStatus.DEPRECATED; import static org.sonar.api.utils.DateUtils.parseDateTime; import static org.sonar.server.language.LanguageTesting.newLanguage; @@ -65,8 +65,6 @@ public class ShowActionTest { public DbTester db = DbTester.create(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private RuleIndexer ruleIndexer = new RuleIndexer(es.client(), db.getDbClient()); private ActiveRuleIndexer activeRuleIndexer = new ActiveRuleIndexer(db.getDbClient(), es.client()); @@ -293,18 +291,20 @@ public class ShowActionTest { public void fail_if_profile_language_is_not_supported() { QProfileDto profile = db.qualityProfiles().insert(p -> p.setKee("unknown-profile").setLanguage("kotlin")); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Quality Profile with key 'unknown-profile' does not exist"); - - call(ws.newRequest().setParam(PARAM_KEY, profile.getKee())); + assertThatThrownBy(() -> { + call(ws.newRequest().setParam(PARAM_KEY, profile.getKee())); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("Quality Profile with key 'unknown-profile' does not exist"); } @Test public void fail_if_profile_does_not_exist() { - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Quality Profile with key 'unknown-profile' does not exist"); - - call(ws.newRequest().setParam(PARAM_KEY, "unknown-profile")); + assertThatThrownBy(() -> { + call(ws.newRequest().setParam(PARAM_KEY, "unknown-profile")); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("Quality Profile with key 'unknown-profile' does not exist"); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/root/ws/SearchActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/root/ws/SearchActionTest.java index 227a274f64c..941af70ba68 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/root/ws/SearchActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/root/ws/SearchActionTest.java @@ -20,9 +20,9 @@ package org.sonar.server.root.ws; import java.util.List; +import org.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.db.DbSession; @@ -38,6 +38,7 @@ import org.sonarqube.ws.MediaTypes; import org.sonarqube.ws.Roots; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.test.JsonAssert.assertJson; public class SearchActionTest { @@ -46,8 +47,6 @@ public class SearchActionTest { public DbTester dbTester = DbTester.create(System2.INSTANCE); @Rule public UserSessionRule userSessionRule = UserSessionRule.standalone(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private UserDao userDao = dbTester.getDbClient().userDao(); private DbSession dbSession = dbTester.getSession(); @@ -72,18 +71,14 @@ public class SearchActionTest { @Test public void execute_fails_with_ForbiddenException_when_user_is_not_logged_in() { - expectInsufficientPrivilegesForbiddenException(); - - executeRequest(); + expectInsufficientPrivilegesForbiddenException(() -> executeRequest()); } @Test public void execute_fails_with_ForbiddenException_when_user_is_not_root() { userSessionRule.logIn().setNonRoot(); - expectInsufficientPrivilegesForbiddenException(); - - executeRequest(); + expectInsufficientPrivilegesForbiddenException(() -> executeRequest()); } @Test @@ -146,9 +141,10 @@ public class SearchActionTest { .getRootsList(); } - private void expectInsufficientPrivilegesForbiddenException() { - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); + private void expectInsufficientPrivilegesForbiddenException(ThrowingCallable callback) { + assertThatThrownBy(callback) + .isInstanceOf(ForbiddenException.class) + .hasMessage("Insufficient privileges"); } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/root/ws/SetRootActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/root/ws/SetRootActionTest.java index 52824db39b3..ed2f8b0288a 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/root/ws/SetRootActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/root/ws/SetRootActionTest.java @@ -20,9 +20,9 @@ package org.sonar.server.root.ws; import javax.annotation.Nullable; +import org.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.db.DbSession; @@ -37,6 +37,7 @@ import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class SetRootActionTest { private static final String SOME_LOGIN = "johndoe"; @@ -45,8 +46,6 @@ public class SetRootActionTest { public DbTester dbTester = DbTester.create(System2.INSTANCE); @Rule public UserSessionRule userSessionRule = UserSessionRule.standalone(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private UserDao userDao = dbTester.getDbClient().userDao(); private DbSession dbSession = dbTester.getSession(); @@ -79,28 +78,23 @@ public class SetRootActionTest { @Test public void execute_fails_with_ForbiddenException_when_user_is_not_logged_in() { - expectInsufficientPrivilegesForbiddenException(); - - executeRequest(SOME_LOGIN); + expectInsufficientPrivilegesForbiddenException(() -> executeRequest(SOME_LOGIN)); } @Test public void execute_fails_with_ForbiddenException_when_user_is_not_root() { userSessionRule.logIn().setNonRoot(); - expectInsufficientPrivilegesForbiddenException(); - - executeRequest(SOME_LOGIN); + expectInsufficientPrivilegesForbiddenException(() -> executeRequest(SOME_LOGIN)); } @Test public void execute_fails_with_IAE_when_login_param_is_not_provided() { logInAsRoot(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The 'login' parameter is missing"); - - executeRequest(null); + assertThatThrownBy(() -> executeRequest(null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("The 'login' parameter is missing"); } @Test @@ -136,10 +130,9 @@ public class SetRootActionTest { public void execute_fails_with_NotFoundException_when_user_for_specified_login_does_not_exist() { logInAsRoot(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("User with login 'foo_bar' not found"); - - executeRequest("foo_bar"); + assertThatThrownBy(() -> executeRequest("foo_bar")) + .isInstanceOf(NotFoundException.class) + .hasMessage("User with login 'foo_bar' not found"); } @Test @@ -149,19 +142,19 @@ public class SetRootActionTest { dbSession.commit(); logInAsRoot(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("User with login '" + userDto.getLogin() + "' not found"); - - executeRequest(userDto.getLogin()); + assertThatThrownBy(() -> executeRequest(userDto.getLogin())) + .isInstanceOf(NotFoundException.class) + .hasMessage("User with login '" + userDto.getLogin() + "' not found"); } private void logInAsRoot() { userSessionRule.logIn().setRoot(); } - private void expectInsufficientPrivilegesForbiddenException() { - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); + private void expectInsufficientPrivilegesForbiddenException(ThrowingCallable callback) { + assertThatThrownBy(callback) + .isInstanceOf(ForbiddenException.class) + .hasMessage("Insufficient privileges"); } private int executeRequest(@Nullable String login) { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/root/ws/UnsetRootActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/root/ws/UnsetRootActionTest.java index 95d83357cc2..13c1eea56fc 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/root/ws/UnsetRootActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/root/ws/UnsetRootActionTest.java @@ -20,9 +20,9 @@ package org.sonar.server.root.ws; import javax.annotation.Nullable; +import org.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.db.DbSession; @@ -37,6 +37,7 @@ import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.db.user.UserTesting.newUserDto; public class UnsetRootActionTest { @@ -46,8 +47,6 @@ public class UnsetRootActionTest { public DbTester dbTester = DbTester.create(System2.INSTANCE); @Rule public UserSessionRule userSessionRule = UserSessionRule.standalone(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private UserDao userDao = dbTester.getDbClient().userDao(); private DbSession dbSession = dbTester.getSession(); @@ -80,28 +79,23 @@ public class UnsetRootActionTest { @Test public void execute_fails_with_ForbiddenException_when_user_is_not_logged_in() { - expectInsufficientPrivilegesForbiddenException(); - - executeRequest(SOME_LOGIN); + expectInsufficientPrivilegesForbiddenException(() -> executeRequest(SOME_LOGIN)); } @Test public void execute_fails_with_ForbiddenException_when_user_is_not_root() { userSessionRule.logIn().setNonRoot(); - expectInsufficientPrivilegesForbiddenException(); - - executeRequest(SOME_LOGIN); + expectInsufficientPrivilegesForbiddenException(() -> executeRequest(SOME_LOGIN)); } @Test public void execute_fails_with_IAE_when_login_param_is_not_provided() { logInAsRoot(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The 'login' parameter is missing"); - - executeRequest(null); + assertThatThrownBy(() -> executeRequest(null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("The 'login' parameter is missing"); } @Test @@ -134,10 +128,9 @@ public class UnsetRootActionTest { insertNonRootUser(newUserDto()); logInAsRoot(); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Last root can't be unset"); - - executeRequest(SOME_LOGIN); + assertThatThrownBy(() -> executeRequest(SOME_LOGIN)) + .isInstanceOf(BadRequestException.class) + .hasMessage("Last root can't be unset"); } @Test @@ -146,20 +139,18 @@ public class UnsetRootActionTest { insertNonRootUser(userDto1); logInAsRoot(); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Last root can't be unset"); - - executeRequest(userDto1.getLogin()); + assertThatThrownBy(() -> executeRequest(userDto1.getLogin())) + .isInstanceOf(BadRequestException.class) + .hasMessage("Last root can't be unset"); } @Test public void execute_fails_with_NotFoundException_when_user_for_specified_login_does_not_exist() { logInAsRoot(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("User with login 'bar_foo' not found"); - - executeRequest("bar_foo"); + assertThatThrownBy(() -> executeRequest("bar_foo")) + .isInstanceOf(NotFoundException.class) + .hasMessage("User with login 'bar_foo' not found"); } @Test @@ -167,10 +158,9 @@ public class UnsetRootActionTest { UserDto userDto = insertRootUser(newUserDto().setActive(false)); logInAsRoot(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("User with login '" + userDto.getLogin() + "' not found"); - - executeRequest(userDto.getLogin()); + assertThatThrownBy(() -> executeRequest(userDto.getLogin())) + .isInstanceOf(NotFoundException.class) + .hasMessage("User with login '" + userDto.getLogin() + "' not found"); } private UserDto insertNonRootUser(UserDto dto) { @@ -190,9 +180,11 @@ public class UnsetRootActionTest { userSessionRule.logIn().setRoot(); } - private void expectInsufficientPrivilegesForbiddenException() { - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); + private void expectInsufficientPrivilegesForbiddenException(ThrowingCallable callback) { + assertThatThrownBy(callback) + .isInstanceOf(ForbiddenException.class) + .hasMessage("Insufficient privileges"); + } private int executeRequest(@Nullable String login) { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/RuleCreatorTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/RuleCreatorTest.java index 74c214d0b5a..ab33fba794b 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/RuleCreatorTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/RuleCreatorTest.java @@ -26,10 +26,10 @@ import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.List; +import java.util.concurrent.atomic.AtomicReference; import org.assertj.core.api.Fail; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.impl.utils.TestSystem2; import org.sonar.api.rule.RuleKey; import org.sonar.api.rule.RuleStatus; @@ -53,6 +53,7 @@ import org.sonar.server.rule.index.RuleIndexer; import org.sonar.server.rule.index.RuleQuery; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.fail; import static org.sonar.db.rule.RuleTesting.newRule; import static org.sonar.server.util.TypeValidationsTesting.newFullTypeValidations; @@ -61,8 +62,6 @@ public class RuleCreatorTest { private System2 system2 = new TestSystem2().setNow(Instant.now().toEpochMilli()); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester dbTester = DbTester.create(system2); @@ -224,17 +223,18 @@ public class RuleCreatorTest { dbTester.rules().insert(rule); dbSession.commit(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("This rule is not a template rule: java:S001"); - - // Create custom rule with unknown template rule - NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", rule.getKey()) - .setName("My custom") - .setHtmlDescription("Some description") - .setSeverity(Severity.MAJOR) - .setStatus(RuleStatus.READY) - .setParameters(ImmutableMap.of("regex", "a.*")); - underTest.create(dbSession, Collections.singletonList(newRule)); + assertThatThrownBy(() -> { + // Create custom rule with unknown template rule + NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", rule.getKey()) + .setName("My custom") + .setHtmlDescription("Some description") + .setSeverity(Severity.MAJOR) + .setStatus(RuleStatus.READY) + .setParameters(ImmutableMap.of("regex", "a.*")); + underTest.create(dbSession, Collections.singletonList(newRule)); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("This rule is not a template rule: java:S001"); } @Test @@ -242,17 +242,18 @@ public class RuleCreatorTest { // insert template rule RuleDefinitionDto templateRule = createTemplateRuleWithIntArrayParam(); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Value 'polop' must be an integer."); - - // Create custom rule - NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey()) - .setName("My custom") - .setMarkdownDescription("Some description") - .setSeverity(Severity.MAJOR) - .setStatus(RuleStatus.READY) - .setParameters(ImmutableMap.of("myIntegers", "1,polop,2")); - underTest.create(dbSession, newRule); + assertThatThrownBy(() -> { + // Create custom rule + NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey()) + .setName("My custom") + .setMarkdownDescription("Some description") + .setSeverity(Severity.MAJOR) + .setStatus(RuleStatus.READY) + .setParameters(ImmutableMap.of("myIntegers", "1,polop,2")); + underTest.create(dbSession, newRule); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Value 'polop' must be an integer."); } @Test @@ -357,16 +358,17 @@ public class RuleCreatorTest { // insert template rule RuleDto templateRule = createTemplateRule(); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("The rule key \"*INVALID*\" is invalid, it should only contain: a-z, 0-9, \"_\""); - - NewCustomRule newRule = NewCustomRule.createForCustomRule("*INVALID*", templateRule.getKey()) - .setName("My custom") - .setHtmlDescription("Some description") - .setSeverity(Severity.MAJOR) - .setStatus(RuleStatus.READY) - .setParameters(ImmutableMap.of("regex", "a.*")); - underTest.create(dbSession, newRule); + assertThatThrownBy(() -> { + NewCustomRule newRule = NewCustomRule.createForCustomRule("*INVALID*", templateRule.getKey()) + .setName("My custom") + .setHtmlDescription("Some description") + .setSeverity(Severity.MAJOR) + .setStatus(RuleStatus.READY) + .setParameters(ImmutableMap.of("regex", "a.*")); + underTest.create(dbSession, newRule); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("The rule key \"*INVALID*\" is invalid, it should only contain: a-z, 0-9, \"_\""); } @Test @@ -374,25 +376,26 @@ public class RuleCreatorTest { // insert template rule RuleDto templateRule = createTemplateRule(); // Create a custom rule - NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey()) + AtomicReference newRule = new AtomicReference<>(NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey()) .setName("My custom") .setHtmlDescription("Some description") .setSeverity(Severity.MAJOR) .setStatus(RuleStatus.READY) - .setParameters(ImmutableMap.of("regex", "a.*")); - underTest.create(dbSession, newRule); - - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("A rule with the key 'CUSTOM_RULE' already exists"); - - // Create another custom rule having same key - newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey()) - .setName("My another custom") - .setHtmlDescription("Some description") - .setSeverity(Severity.MAJOR) - .setStatus(RuleStatus.READY) - .setParameters(ImmutableMap.of("regex", "a.*")); - underTest.create(dbSession, newRule); + .setParameters(ImmutableMap.of("regex", "a.*"))); + underTest.create(dbSession, newRule.get()); + + assertThatThrownBy(() -> { + // Create another custom rule having same key + newRule.set(NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey()) + .setName("My another custom") + .setHtmlDescription("Some description") + .setSeverity(Severity.MAJOR) + .setStatus(RuleStatus.READY) + .setParameters(ImmutableMap.of("regex", "a.*"))); + underTest.create(dbSession, newRule.get()); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("A rule with the key 'CUSTOM_RULE' already exists"); } @Test @@ -400,15 +403,16 @@ public class RuleCreatorTest { // insert template rule RuleDto templateRule = createTemplateRule(); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("The name is missing"); - - NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey()) - .setHtmlDescription("Some description") - .setSeverity(Severity.MAJOR) - .setStatus(RuleStatus.READY) - .setParameters(ImmutableMap.of("regex", "a.*")); - underTest.create(dbSession, newRule); + assertThatThrownBy(() -> { + NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey()) + .setHtmlDescription("Some description") + .setSeverity(Severity.MAJOR) + .setStatus(RuleStatus.READY) + .setParameters(ImmutableMap.of("regex", "a.*")); + underTest.create(dbSession, newRule); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("The name is missing"); } @Test @@ -416,15 +420,16 @@ public class RuleCreatorTest { // insert template rule RuleDto templateRule = createTemplateRule(); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("The description is missing"); - - NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey()) - .setName("My custom") - .setSeverity(Severity.MAJOR) - .setStatus(RuleStatus.READY) - .setParameters(ImmutableMap.of("regex", "a.*")); - underTest.create(dbSession, newRule); + assertThatThrownBy(() -> { + NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey()) + .setName("My custom") + .setSeverity(Severity.MAJOR) + .setStatus(RuleStatus.READY) + .setParameters(ImmutableMap.of("regex", "a.*")); + underTest.create(dbSession, newRule); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("The description is missing"); } @Test @@ -432,15 +437,16 @@ public class RuleCreatorTest { // insert template rule RuleDto templateRule = createTemplateRule(); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("The severity is missing"); - - NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey()) - .setName("My custom") - .setHtmlDescription("Some description") - .setStatus(RuleStatus.READY) - .setParameters(ImmutableMap.of("regex", "a.*")); - underTest.create(dbSession, newRule); + assertThatThrownBy(() -> { + NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey()) + .setName("My custom") + .setHtmlDescription("Some description") + .setStatus(RuleStatus.READY) + .setParameters(ImmutableMap.of("regex", "a.*")); + underTest.create(dbSession, newRule); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("The severity is missing"); } @Test @@ -448,16 +454,17 @@ public class RuleCreatorTest { // insert template rule RuleDto templateRule = createTemplateRule(); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Severity \"INVALID\" is invalid"); - - NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey()) - .setName("My custom") - .setHtmlDescription("Some description") - .setSeverity("INVALID") - .setStatus(RuleStatus.READY) - .setParameters(ImmutableMap.of("regex", "a.*")); - underTest.create(dbSession, newRule); + assertThatThrownBy(() -> { + NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey()) + .setName("My custom") + .setHtmlDescription("Some description") + .setSeverity("INVALID") + .setStatus(RuleStatus.READY) + .setParameters(ImmutableMap.of("regex", "a.*")); + underTest.create(dbSession, newRule); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Severity \"INVALID\" is invalid"); } @Test @@ -465,15 +472,16 @@ public class RuleCreatorTest { // insert template rule RuleDto templateRule = createTemplateRule(); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("The status is missing"); - - NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey()) - .setName("My custom") - .setHtmlDescription("Some description") - .setSeverity(Severity.MAJOR) - .setParameters(ImmutableMap.of("regex", "a.*")); - underTest.create(dbSession, newRule); + assertThatThrownBy(() -> { + NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey()) + .setName("My custom") + .setHtmlDescription("Some description") + .setSeverity(Severity.MAJOR) + .setParameters(ImmutableMap.of("regex", "a.*")); + underTest.create(dbSession, newRule); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("The status is missing"); } @Test @@ -483,31 +491,33 @@ public class RuleCreatorTest { dbTester.rules().insert(rule); dbSession.commit(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("This rule is not a template rule: java:S001"); - - // Create custom rule with unknown template rule - NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", rule.getKey()) - .setName("My custom") - .setHtmlDescription("Some description") - .setSeverity(Severity.MAJOR) - .setStatus(RuleStatus.READY) - .setParameters(ImmutableMap.of("regex", "a.*")); - underTest.create(dbSession, newRule); + assertThatThrownBy(() -> { + // Create custom rule with unknown template rule + NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", rule.getKey()) + .setName("My custom") + .setHtmlDescription("Some description") + .setSeverity(Severity.MAJOR) + .setStatus(RuleStatus.READY) + .setParameters(ImmutableMap.of("regex", "a.*")); + underTest.create(dbSession, newRule); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("This rule is not a template rule: java:S001"); } @Test public void fail_to_create_custom_rule_when_unknown_template() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The template key doesn't exist: java:S001"); - - // Create custom rule - NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", RuleKey.of("java", "S001")) - .setName("My custom") - .setMarkdownDescription("Some description") - .setSeverity(Severity.MAJOR) - .setStatus(RuleStatus.READY); - underTest.create(dbSession, newRule); + assertThatThrownBy(() -> { + // Create custom rule + NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", RuleKey.of("java", "S001")) + .setName("My custom") + .setMarkdownDescription("Some description") + .setSeverity(Severity.MAJOR) + .setStatus(RuleStatus.READY); + underTest.create(dbSession, newRule); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("The template key doesn't exist: java:S001"); } private RuleDto createTemplateRule() { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/RuleUpdaterTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/RuleUpdaterTest.java index c84bb4d1e24..465f7a9b7d8 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/RuleUpdaterTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/RuleUpdaterTest.java @@ -28,7 +28,6 @@ import java.util.Map; import java.util.stream.Collectors; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.impl.utils.TestSystem2; import org.sonar.api.rule.RuleKey; import org.sonar.api.rule.RuleStatus; @@ -56,6 +55,7 @@ import org.sonar.server.rule.index.RuleQuery; import org.sonar.server.tester.UserSessionRule; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.rule.Severity.CRITICAL; import static org.sonar.db.rule.RuleTesting.newRule; import static org.sonar.server.rule.RuleUpdate.createForCustomRule; @@ -67,8 +67,6 @@ public class RuleUpdaterTest { private final System2 system2 = new TestSystem2().setNow(Instant.now().toEpochMilli()); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSessionRule = UserSessionRule.standalone(); @@ -93,10 +91,11 @@ public class RuleUpdaterTest { RuleUpdate update = createForPluginRule(RULE_KEY) .setTags(Sets.newHashSet("java9")); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Rule with REMOVED status cannot be updated: squid:S001"); - - underTest.update(dbSession, update, userSessionRule); + assertThatThrownBy(() -> { + underTest.update(dbSession, update, userSessionRule); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Rule with REMOVED status cannot be updated: squid:S001"); } @Test @@ -500,10 +499,11 @@ public class RuleUpdaterTest { .setName("") .setMarkdownDescription("New desc"); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The name is missing"); - - underTest.update(dbSession, update, userSessionRule); + assertThatThrownBy(() -> { + underTest.update(dbSession, update, userSessionRule); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("The name is missing"); } @Test @@ -518,12 +518,13 @@ public class RuleUpdaterTest { dbSession.commit(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The description is missing"); - - underTest.update(dbSession, - createForCustomRule(customRule.getKey()).setName("New name").setMarkdownDescription(""), - userSessionRule); + assertThatThrownBy(() -> { + underTest.update(dbSession, + createForCustomRule(customRule.getKey()).setName("New name").setMarkdownDescription(""), + userSessionRule); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("The description is missing"); } @Test @@ -531,10 +532,11 @@ public class RuleUpdaterTest { RuleDefinitionDto ruleDefinition = db.rules().insert(newRule(RuleKey.of("squid", "S01"))); dbSession.commit(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Not a custom rule"); - - createForPluginRule(ruleDefinition.getKey()).setName("New name"); + assertThatThrownBy(() -> { + createForPluginRule(ruleDefinition.getKey()).setName("New name"); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Not a custom rule"); } @Test @@ -542,10 +544,11 @@ public class RuleUpdaterTest { RuleDefinitionDto ruleDefinition = db.rules().insert(newRule(RuleKey.of("squid", "S01"))); dbSession.commit(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Not a custom rule"); - - createForPluginRule(ruleDefinition.getKey()).setMarkdownDescription("New description"); + assertThatThrownBy(() -> { + createForPluginRule(ruleDefinition.getKey()).setMarkdownDescription("New description"); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Not a custom rule"); } @Test @@ -553,10 +556,11 @@ public class RuleUpdaterTest { RuleDefinitionDto ruleDefinition = db.rules().insert(newRule(RuleKey.of("squid", "S01"))); dbSession.commit(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Not a custom rule"); - - createForPluginRule(ruleDefinition.getKey()).setSeverity(CRITICAL); + assertThatThrownBy(() -> { + createForPluginRule(ruleDefinition.getKey()).setSeverity(CRITICAL); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Not a custom rule"); } private static Map paramsByName(List params) { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/ws/AppActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/ws/AppActionTest.java index 37a9c2ba679..4cad7a586b5 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/ws/AppActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/ws/AppActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.rule.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.resources.Language; import org.sonar.api.resources.Languages; import org.sonar.api.server.ws.WebService; @@ -42,8 +41,6 @@ public class AppActionTest { private static final Language LANG1 = LanguageTesting.newLanguage("xoo", "Xoo"); private static final Language LANG2 = LanguageTesting.newLanguage("ws", "Whitespace"); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester db = DbTester.create(System2.INSTANCE); @Rule diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/ws/CreateActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/ws/CreateActionTest.java index f4e200ea137..ae62086d98a 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/ws/CreateActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/ws/CreateActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.rule.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.resources.Languages; import org.sonar.api.rule.RuleKey; import org.sonar.api.rule.RuleStatus; @@ -44,6 +43,7 @@ import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.AdditionalAnswers.returnsFirstArg; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doAnswer; @@ -60,8 +60,6 @@ public class CreateActionTest { private System2 system2 = mock(System2.class); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @@ -183,10 +181,9 @@ public class CreateActionTest { .setParam("severity", "MAJOR") .setParam("prevent_reactivation", "true"); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The template key doesn't exist: non:existing"); - - request.execute(); + assertThatThrownBy(request::execute) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("The template key doesn't exist: non:existing"); } @Test @@ -203,26 +200,23 @@ public class CreateActionTest { .setParam("severity", "MAJOR") .setParam("prevent_reactivation", "true"); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The template key doesn't exist: " + templateRule.getKey()); - - request.execute(); + assertThatThrownBy(request::execute) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("The template key doesn't exist: " + templateRule.getKey()); } @Test public void throw_ForbiddenException_if_not_profile_administrator() { userSession.logIn(); - expectedException.expect(ForbiddenException.class); - - ws.newRequest().execute(); + assertThatThrownBy(() -> ws.newRequest().execute()) + .isInstanceOf(ForbiddenException.class); } @Test public void throw_UnauthorizedException_if_not_logged_in() { - expectedException.expect(UnauthorizedException.class); - - ws.newRequest().execute(); + assertThatThrownBy(() -> ws.newRequest().execute()) + .isInstanceOf(UnauthorizedException.class); } private static MacroInterpreter createMacroInterpreter() { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/ws/DeleteActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/ws/DeleteActionTest.java index de6d1817d32..391eaa54727 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/ws/DeleteActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/ws/DeleteActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.rule.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.rule.RuleStatus; import org.sonar.api.utils.System2; import org.sonar.db.DbClient; @@ -37,6 +36,7 @@ import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; @@ -53,8 +53,6 @@ public class DeleteActionTest { public DbTester dbTester = DbTester.create(); @Rule public EsTester es = EsTester.create(); - @Rule - public ExpectedException thrown = ExpectedException.none(); private DbClient dbClient = dbTester.getDbClient(); private DbSession dbSession = dbTester.getSession(); private RuleIndexer ruleIndexer = spy(new RuleIndexer(es.client(), dbClient)); @@ -94,22 +92,24 @@ public class DeleteActionTest { public void throw_ForbiddenException_if_not_profile_administrator() { userSession.logIn(); - thrown.expect(ForbiddenException.class); - - tester.newRequest() - .setMethod("POST") - .setParam("key", "anyRuleKey") - .execute(); + assertThatThrownBy(() -> { + tester.newRequest() + .setMethod("POST") + .setParam("key", "anyRuleKey") + .execute(); + }) + .isInstanceOf(ForbiddenException.class); } @Test public void throw_UnauthorizedException_if_not_logged_in() { - thrown.expect(UnauthorizedException.class); - - tester.newRequest() - .setMethod("POST") - .setParam("key", "anyRuleKey") - .execute(); + assertThatThrownBy(() -> { + tester.newRequest() + .setMethod("POST") + .setParam("key", "anyRuleKey") + .execute(); + }) + .isInstanceOf(UnauthorizedException.class); } @Test @@ -117,13 +117,14 @@ public class DeleteActionTest { logInAsQProfileAdministrator(); RuleDefinitionDto rule = dbTester.rules().insert(); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Rule '" + rule.getKey().toString() + "' cannot be deleted because it is not a custom rule"); - - tester.newRequest() - .setMethod("POST") - .setParam("key", rule.getKey().toString()) - .execute(); + assertThatThrownBy(() -> { + tester.newRequest() + .setMethod("POST") + .setParam("key", rule.getKey().toString()) + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Rule '" + rule.getKey().toString() + "' cannot be deleted because it is not a custom rule"); } private void logInAsQProfileAdministrator() { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/ws/RuleQueryFactoryTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/ws/RuleQueryFactoryTest.java index df2275c1cf5..2163e9e8dc5 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/ws/RuleQueryFactoryTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/ws/RuleQueryFactoryTest.java @@ -21,7 +21,6 @@ package org.sonar.server.rule.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.impl.ws.SimpleGetRequest; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; @@ -38,6 +37,7 @@ import org.sonar.server.ws.WsAction; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.rule.RuleStatus.DEPRECATED; import static org.sonar.api.rule.RuleStatus.READY; import static org.sonar.api.rule.Severity.CRITICAL; @@ -73,8 +73,6 @@ public class RuleQueryFactoryTest { @Rule public DbTester db = DbTester.create(System2.INSTANCE); @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Rule public UserSessionRule userSession = UserSessionRule.standalone(); private DbClient dbClient = db.getDbClient(); @@ -148,9 +146,11 @@ public class RuleQueryFactoryTest { db.qualityProfiles().insert(); Request request = new SimpleGetRequest(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The 'include_external' parameter is missing"); - underTest.createRuleSearchQuery(db.getSession(), request); + assertThatThrownBy(() -> { + underTest.createRuleSearchQuery(db.getSession(), request); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("The 'include_external' parameter is missing"); } @Test @@ -228,21 +228,23 @@ public class RuleQueryFactoryTest { } public void fail_when_profile_does_not_exist() { - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("The specified qualityProfile 'unknown' does not exist"); - - execute(PARAM_QPROFILE, "unknown"); + assertThatThrownBy(() -> { + execute(PARAM_QPROFILE, "unknown"); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("The specified qualityProfile 'unknown' does not exist"); } @Test public void fail_when_compare_to_profile_does_not_exist() { QProfileDto qualityProfile = db.qualityProfiles().insert(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("The specified qualityProfile 'unknown' does not exist"); - - execute(PARAM_QPROFILE, qualityProfile.getKee(), - PARAM_COMPARE_TO_PROFILE, "unknown"); + assertThatThrownBy(() -> { + execute(PARAM_QPROFILE, qualityProfile.getKee(), + PARAM_COMPARE_TO_PROFILE, "unknown"); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("The specified qualityProfile 'unknown' does not exist"); } private void assertResult(RuleQuery result, QProfileDto qualityProfile, QProfileDto compareToQualityProfile) { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/ws/SearchActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/ws/SearchActionTest.java index 162ddbc1456..6f33104fa57 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/ws/SearchActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/ws/SearchActionTest.java @@ -26,7 +26,6 @@ import java.util.stream.Collectors; import org.assertj.core.api.iterable.Extractor; import org.junit.Before; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.impl.utils.AlwaysIncreasingSystem2; import org.sonar.api.resources.Languages; import org.sonar.api.rule.RuleKey; @@ -72,6 +71,7 @@ import static java.util.Collections.singleton; import static java.util.Collections.singletonList; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.assertj.guava.api.Assertions.entry; import static org.mockito.ArgumentMatchers.anyString; @@ -91,8 +91,6 @@ public class SearchActionTest { @org.junit.Rule public UserSessionRule userSession = UserSessionRule.standalone(); - @org.junit.Rule - public ExpectedException expectedException = ExpectedException.none(); private final System2 system2 = new AlwaysIncreasingSystem2(); @org.junit.Rule @@ -698,13 +696,15 @@ public class SearchActionTest { tuple(ruleParam2.getName(), ruleParam2.getDefaultValue())); String unknownProfile = "unknown_profile" + randomAlphanumeric(5); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("The specified qualityProfile '" + unknownProfile + "' does not exist"); - ws.newRequest() - .setParam("activation", "true") - .setParam("qprofile", unknownProfile) - .executeProtobuf(SearchResponse.class); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam("activation", "true") + .setParam("qprofile", unknownProfile) + .executeProtobuf(SearchResponse.class); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("The specified qualityProfile '" + unknownProfile + "' does not exist"); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/ws/UpdateActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/ws/UpdateActionTest.java index a24be9569f7..644e123c33d 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/ws/UpdateActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/ws/UpdateActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.rule.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.resources.Languages; import org.sonar.api.rule.RuleKey; import org.sonar.api.rule.RuleStatus; @@ -46,6 +45,7 @@ import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.Rules; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.AdditionalAnswers.returnsFirstArg; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doAnswer; @@ -67,8 +67,6 @@ public class UpdateActionTest { private static final long PAST = 10000L; - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester db = DbTester.create(); @@ -250,14 +248,15 @@ public class UpdateActionTest { r -> r.setCreatedAt(PAST), r -> r.setUpdatedAt(PAST)); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The description is missing"); - - ws.newRequest().setMethod("POST") - .setParam("key", customRule.getKey().toString()) - .setParam("name", "My custom rule") - .setParam("markdown_description", "") - .execute(); + assertThatThrownBy(() -> { + ws.newRequest().setMethod("POST") + .setParam("key", customRule.getKey().toString()) + .setParam("name", "My custom rule") + .setParam("markdown_description", "") + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("The description is missing"); } @Test @@ -265,31 +264,33 @@ public class UpdateActionTest { logInAsQProfileAdministrator(); RuleDefinitionDto rule = db.rules().insert(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Not a custom rule"); - - ws.newRequest().setMethod("POST") - .setParam("key", rule.getKey().toString()) - .setParam("name", rule.getName()) - .setParam("markdown_description", "New description") - .execute(); - + assertThatThrownBy(() -> { + ws.newRequest().setMethod("POST") + .setParam("key", rule.getKey().toString()) + .setParam("name", rule.getName()) + .setParam("markdown_description", "New description") + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Not a custom rule"); } @Test public void throw_ForbiddenException_if_not_profile_administrator() { userSession.logIn(); - expectedException.expect(ForbiddenException.class); - - ws.newRequest().setMethod("POST").execute(); + assertThatThrownBy(() -> { + ws.newRequest().setMethod("POST").execute(); + }) + .isInstanceOf(ForbiddenException.class); } @Test public void throw_UnauthorizedException_if_not_logged_in() { - expectedException.expect(UnauthorizedException.class); - - ws.newRequest().setMethod("POST").execute(); + assertThatThrownBy(() -> { + ws.newRequest().setMethod("POST").execute(); + }) + .isInstanceOf(UnauthorizedException.class); } private void logInAsQProfileAdministrator() { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/setting/ws/CheckSecretKeyActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/setting/ws/CheckSecretKeyActionTest.java index 4bdf572d454..04d060248ea 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/setting/ws/CheckSecretKeyActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/setting/ws/CheckSecretKeyActionTest.java @@ -24,7 +24,6 @@ import java.io.IOException; import org.apache.commons.io.FileUtils; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.sonar.api.config.internal.Encryption; import org.sonar.api.config.internal.MapSettings; @@ -35,11 +34,10 @@ import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.Settings.CheckSecretKeyWsResponse; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.test.JsonAssert.assertJson; public class CheckSecretKeyActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -90,10 +88,9 @@ public class CheckSecretKeyActionTest { public void throw_ForbiddenException_if_not_system_administrator() { userSession.logIn().setNonSystemAdministrator(); - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - - call(); + assertThatThrownBy(() -> call()) + .isInstanceOf(ForbiddenException.class) + .hasMessage("Insufficient privileges"); } private CheckSecretKeyWsResponse call() { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/setting/ws/EncryptActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/setting/ws/EncryptActionTest.java index 70876c252ab..e338c428031 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/setting/ws/EncryptActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/setting/ws/EncryptActionTest.java @@ -22,12 +22,10 @@ package org.sonar.server.setting.ws; import java.io.File; import java.nio.charset.StandardCharsets; import javax.annotation.Nullable; - import org.apache.commons.io.FileUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.sonar.api.config.internal.Encryption; import org.sonar.api.config.internal.MapSettings; @@ -40,11 +38,10 @@ import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.Settings.EncryptWsResponse; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.server.setting.ws.SettingsWsParameters.PARAM_VALUE; public class EncryptActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -89,29 +86,26 @@ public class EncryptActionTest { public void throw_ForbiddenException_if_not_system_administrator() { userSession.logIn().setNonSystemAdministrator(); - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - - call("my value"); + assertThatThrownBy(() -> call("my value")) + .isInstanceOf(ForbiddenException.class) + .hasMessage("Insufficient privileges"); } @Test public void fail_if_value_is_not_provided() { logInAsSystemAdministrator(); - expectedException.expect(IllegalArgumentException.class); - - call(null); + assertThatThrownBy(() -> call(null)) + .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_if_value_is_empty() { logInAsSystemAdministrator(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The 'value' parameter is missing"); - - call(" "); + assertThatThrownBy(() -> call(" ")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("The 'value' parameter is missing"); } @Test @@ -120,10 +114,9 @@ public class EncryptActionTest { encryption.setPathToSecretKey("unknown/path/to/secret/key"); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("No secret key available"); - - call("my value"); + assertThatThrownBy(() -> call("my value")) + .isInstanceOf(BadRequestException.class) + .hasMessage("No secret key available"); } private EncryptWsResponse call(@Nullable String value) { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/setting/ws/GenerateSecretKeyActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/setting/ws/GenerateSecretKeyActionTest.java index fdcd9597c1a..85816f3ad80 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/setting/ws/GenerateSecretKeyActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/setting/ws/GenerateSecretKeyActionTest.java @@ -25,7 +25,6 @@ import java.nio.charset.StandardCharsets; import org.apache.commons.io.FileUtils; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.sonar.api.config.internal.Encryption; import org.sonar.api.config.internal.MapSettings; @@ -40,10 +39,9 @@ import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.Settings.GenerateSecretKeyWsResponse; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class GenerateSecretKeyActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone().logIn().setSystemAdministrator(); @Rule @@ -85,10 +83,9 @@ public class GenerateSecretKeyActionTest { public void throw_ForbiddenException_if_not_system_administrator() { userSession.logIn().setNonSystemAdministrator(); - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - - call(); + assertThatThrownBy(() -> call()) + .isInstanceOf(ForbiddenException.class) + .hasMessage("Insufficient privileges"); } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/setting/ws/GenerateSecretKeyActionWithPersisterTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/setting/ws/GenerateSecretKeyActionWithPersisterTest.java index 92726e1b98a..dc7c205e106 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/setting/ws/GenerateSecretKeyActionWithPersisterTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/setting/ws/GenerateSecretKeyActionWithPersisterTest.java @@ -21,7 +21,6 @@ package org.sonar.server.setting.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.utils.System2; import org.sonar.db.DbClient; @@ -38,8 +37,6 @@ import static org.mockito.Mockito.verify; public class GenerateSecretKeyActionWithPersisterTest { private final AuditPersister auditPersister = mock(AuditPersister.class); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone().logIn().setSystemAdministrator(); @Rule diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/setting/ws/ListDefinitionsActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/setting/ws/ListDefinitionsActionTest.java index b1009264049..cf56ecd68c6 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/setting/ws/ListDefinitionsActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/setting/ws/ListDefinitionsActionTest.java @@ -23,7 +23,6 @@ import javax.annotation.Nullable; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.PropertyType; import org.sonar.api.config.PropertyDefinition; import org.sonar.api.config.PropertyDefinitions; @@ -49,6 +48,7 @@ import org.sonarqube.ws.Settings.ListDefinitionsWsResponse; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.groups.Tuple.tuple; import static org.sonar.api.resources.Qualifiers.MODULE; import static org.sonar.api.resources.Qualifiers.PROJECT; @@ -72,8 +72,6 @@ import static org.sonarqube.ws.Settings.Type.TEXT; public class ListDefinitionsActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -392,19 +390,19 @@ public class ListDefinitionsActionTest { userSession.logIn("project-admin").addProjectPermission(CODEVIEWER, project); propertyDefinitions.addComponent(PropertyDefinition.builder("foo").build()); - expectedException.expect(ForbiddenException.class); - - executeRequest(project.getDbKey()); + assertThatThrownBy(() -> executeRequest(project.getDbKey())) + .isInstanceOf(ForbiddenException.class); } @Test public void fail_when_component_not_found() { - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Component key 'unknown' not found"); - - ws.newRequest() - .setParam("component", "unknown") - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam("component", "unknown") + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("Component key 'unknown' not found"); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/setting/ws/ResetActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/setting/ws/ResetActionTest.java index da1439addee..8f589b02875 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/setting/ws/ResetActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/setting/ws/ResetActionTest.java @@ -24,7 +24,6 @@ import javax.annotation.Nullable; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.config.PropertyDefinition; import org.sonar.api.config.PropertyDefinitions; import org.sonar.api.server.ws.WebService; @@ -57,6 +56,7 @@ import org.sonarqube.ws.MediaTypes; import static java.lang.String.format; import static java.net.HttpURLConnection.HTTP_NO_CONTENT; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.resources.Qualifiers.PROJECT; import static org.sonar.api.resources.Qualifiers.VIEW; import static org.sonar.api.web.UserRole.ADMIN; @@ -67,8 +67,6 @@ import static org.sonar.db.property.PropertyTesting.newUserPropertyDto; public class ResetActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -248,10 +246,9 @@ public class ResetActionTest { userSession.logIn().setNonSystemAdministrator(); definitions.addComponent(PropertyDefinition.builder("foo").build()); - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - - executeRequestOnGlobalSetting("foo"); + assertThatThrownBy(() -> executeRequestOnGlobalSetting("foo")) + .isInstanceOf(ForbiddenException.class) + .hasMessage("Insufficient privileges"); } @Test @@ -259,10 +256,11 @@ public class ResetActionTest { userSession.logIn().addProjectPermission(USER, project); definitions.addComponent(PropertyDefinition.builder("foo").build()); - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - - executeRequestOnComponentSetting("foo", project); + assertThatThrownBy(() -> { + executeRequestOnComponentSetting("foo", project); + }) + .isInstanceOf(ForbiddenException.class) + .hasMessage("Insufficient privileges"); } @Test @@ -270,10 +268,11 @@ public class ResetActionTest { logInAsSystemAdministrator(); definitions.addComponent(PropertyDefinition.builder("foo").build()); - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - - executeRequestOnComponentSetting("foo", project); + assertThatThrownBy(() -> { + executeRequestOnComponentSetting("foo", project); + }) + .isInstanceOf(ForbiddenException.class) + .hasMessage("Insufficient privileges"); } @Test @@ -283,10 +282,11 @@ public class ResetActionTest { .onlyOnQualifiers(VIEW) .build()); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Setting 'foo' cannot be global"); - - executeRequestOnGlobalSetting("foo"); + assertThatThrownBy(() -> { + executeRequestOnGlobalSetting("foo"); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Setting 'foo' cannot be global"); } @Test @@ -297,10 +297,11 @@ public class ResetActionTest { .build()); i18n.put("qualifier." + PROJECT, "project"); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Setting 'foo' cannot be set on a project"); - - executeRequestOnComponentSetting("foo", project); + assertThatThrownBy(() -> { + executeRequestOnComponentSetting("foo", project); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Setting 'foo' cannot be set on a project"); } @Test @@ -310,10 +311,11 @@ public class ResetActionTest { definitions.addComponent(PropertyDefinition.builder("foo").build()); i18n.put("qualifier." + PROJECT, "project"); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Setting 'foo' cannot be set on a project"); - - executeRequestOnComponentSetting("foo", project); + assertThatThrownBy(() -> { + executeRequestOnComponentSetting("foo", project); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Setting 'foo' cannot be set on a project"); } @Test @@ -371,24 +373,26 @@ public class ResetActionTest { ComponentDto branch = db.components().insertProjectBranch(project); definitions.addComponent(PropertyDefinition.builder("foo").onQualifiers(PROJECT).build()); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(format("Component key '%s' not found", branch.getDbKey())); - - ws.newRequest() - .setParam("keys", "foo") - .setParam("component", branch.getDbKey()) - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam("keys", "foo") + .setParam("component", branch.getDbKey()) + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage(format("Component key '%s' not found", branch.getDbKey())); } @Test public void fail_when_component_not_found() { - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Component key 'unknown' not found"); - - ws.newRequest() - .setParam("keys", "foo") - .setParam("component", "unknown") - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam("keys", "foo") + .setParam("component", "unknown") + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("Component key 'unknown' not found"); } @Test @@ -398,14 +402,15 @@ public class ResetActionTest { ComponentDto branch = db.components().insertProjectBranch(project); String settingKey = "not_allowed_on_branch"; - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(format("Component '%s' on branch 'unknown' not found", branch.getKey())); - - ws.newRequest() - .setParam("keys", settingKey) - .setParam("component", branch.getKey()) - .setParam("branch", "unknown") - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam("keys", settingKey) + .setParam("component", branch.getKey()) + .setParam("branch", "unknown") + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage(format("Component '%s' on branch 'unknown' not found", branch.getKey())); } @Test @@ -414,13 +419,14 @@ public class ResetActionTest { logInAsProjectAdmin(project); String settingKey = ProcessProperties.Property.JDBC_URL.getKey(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(format("Setting '%s' can only be used in sonar.properties", settingKey)); - - ws.newRequest() - .setParam("keys", settingKey) - .setParam("component", project.getKey()) - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam("keys", settingKey) + .setParam("component", project.getKey()) + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage(format("Setting '%s' can only be used in sonar.properties", settingKey)); } private void succeedForPropertyWithoutDefinitionAndValidComponent(ComponentDto root, ComponentDto module) { @@ -433,10 +439,11 @@ public class ResetActionTest { i18n.put("qualifier." + component.qualifier(), "QualifierLabel"); logInAsProjectAdmin(root); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Setting 'foo' cannot be set on a QualifierLabel"); - - executeRequestOnComponentSetting("foo", component); + assertThatThrownBy(() -> { + executeRequestOnComponentSetting("foo", component); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Setting 'foo' cannot be set on a QualifierLabel"); } private void executeRequestOnGlobalSetting(String key) { @@ -495,9 +502,9 @@ public class ResetActionTest { private void assertUserPropertyExists(String key, UserDto user) { assertThat(dbClient.propertiesDao().selectByQuery(PropertyQuery.builder() - .setKey(key) - .setUserUuid(user.getUuid()) - .build(), + .setKey(key) + .setUserUuid(user.getUuid()) + .build(), dbSession)).isNotEmpty(); } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/setting/ws/SetActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/setting/ws/SetActionTest.java index 262e1d10ac8..3744821bf72 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/setting/ws/SetActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/setting/ws/SetActionTest.java @@ -31,7 +31,6 @@ import javax.annotation.Nullable; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.api.PropertyType; import org.sonar.api.config.PropertyDefinition; @@ -80,8 +79,6 @@ public class SetActionTest { private static final Gson GSON = GsonHelper.create(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone().logIn(); @Rule @@ -632,52 +629,57 @@ public class SetActionTest { @Test public void fail_when_no_key() { - expectedException.expect(IllegalArgumentException.class); - - callForGlobalSetting(null, "my value"); + assertThatThrownBy(() -> { + callForGlobalSetting(null, "my value"); + }) + .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_when_empty_key_value() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The 'key' parameter is missing"); - - callForGlobalSetting(" ", "my value"); + assertThatThrownBy(() -> { + callForGlobalSetting(" ", "my value"); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("The 'key' parameter is missing"); } @Test public void fail_when_no_value() { - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Either 'value', 'values' or 'fieldValues' must be provided"); - - callForGlobalSetting("my.key", null); + assertThatThrownBy(() -> { + callForGlobalSetting("my.key", null); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Either 'value', 'values' or 'fieldValues' must be provided"); } @Test public void fail_when_empty_value() { - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("A non empty value must be provided"); - - callForGlobalSetting("my.key", ""); + assertThatThrownBy(() -> { + callForGlobalSetting("my.key", ""); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("A non empty value must be provided"); } @Test public void fail_when_one_empty_value_on_multi_value() { - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("A non empty value must be provided"); - - callForMultiValueGlobalSetting("my.key", newArrayList("oneValue", " ", "anotherValue")); - + assertThatThrownBy(() -> { + callForMultiValueGlobalSetting("my.key", newArrayList("oneValue", " ", "anotherValue")); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("A non empty value must be provided"); } @Test public void throw_ForbiddenException_if_not_system_administrator() { userSession.logIn().setNonSystemAdministrator(); - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - - callForGlobalSetting("my.key", "my value"); + assertThatThrownBy(() -> { + callForGlobalSetting("my.key", "my value"); + }) + .isInstanceOf(ForbiddenException.class) + .hasMessage("Insufficient privileges"); } @Test @@ -692,10 +694,12 @@ public class SetActionTest { .defaultValue("default") .build()); i18n.put("property.error.notInteger", "Not an integer error message"); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Not an integer error message"); - callForGlobalSetting("my.key", "My Value"); + assertThatThrownBy(() -> { + callForGlobalSetting("my.key", "My Value"); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Not an integer error message"); } @Test @@ -714,10 +718,11 @@ public class SetActionTest { dbClient.metricDao().insert(dbSession, newMetricDto().setKey("metric_disabled_key").setEnabled(false)); dbSession.commit(); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Error when validating metric setting with key 'my_key' and values [metric_key, metric_disabled_key]. A value is not a valid metric key."); - - callForMultiValueGlobalSetting("my_key", newArrayList("metric_key", "metric_disabled_key")); + assertThatThrownBy(() -> { + callForMultiValueGlobalSetting("my_key", newArrayList("metric_key", "metric_disabled_key")); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Error when validating metric setting with key 'my_key' and values [metric_key, metric_disabled_key]. A value is not a valid metric key."); } @Test @@ -735,10 +740,11 @@ public class SetActionTest { db.users().insertUser(newUserDto().setLogin("login.1")); db.users().insertUser(newUserDto().setLogin("login.2").setActive(false)); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Error when validating login setting with key 'my.key' and values [login.1, login.2]. A value is not a valid login."); - - callForMultiValueGlobalSetting("my.key", newArrayList("login.1", "login.2")); + assertThatThrownBy(() -> { + callForMultiValueGlobalSetting("my.key", newArrayList("login.1", "login.2")); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Error when validating login setting with key 'my.key' and values [login.1, login.2]. A value is not a valid login."); } @Test @@ -752,10 +758,12 @@ public class SetActionTest { .type(PropertyType.INTEGER) .defaultValue("default") .build()); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Error when validating setting with key 'my.key' and value [My Value, My Other Value]"); - callForMultiValueGlobalSetting("my.key", newArrayList("My Value", "My Other Value")); + assertThatThrownBy(() -> { + callForMultiValueGlobalSetting("my.key", newArrayList("My Value", "My Other Value")); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Error when validating setting with key 'my.key' and value [My Value, My Other Value]"); } @Test @@ -770,10 +778,12 @@ public class SetActionTest { .defaultValue("default") .onlyOnQualifiers(Qualifiers.PROJECT) .build()); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Setting 'my.key' cannot be global"); - callForGlobalSetting("my.key", "42"); + assertThatThrownBy(() -> { + callForGlobalSetting("my.key", "42"); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Setting 'my.key' cannot be global"); } @Test @@ -790,11 +800,13 @@ public class SetActionTest { .build()); ComponentDto view = db.components().insertPublicPortfolio(); i18n.put("qualifier." + Qualifiers.VIEW, "View"); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Setting 'my.key' cannot be set on a View"); - logInAsProjectAdministrator(view); - callForProjectSettingByKey("my.key", "My Value", view.getDbKey()); + assertThatThrownBy(() -> { + logInAsProjectAdministrator(view); + callForProjectSettingByKey("my.key", "My Value", view.getDbKey()); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Setting 'my.key' cannot be set on a View"); } @Test @@ -814,10 +826,11 @@ public class SetActionTest { i18n.put("qualifier." + file.qualifier(), "CptLabel"); logInAsProjectAdministrator(project); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Setting 'my.key' cannot be set on a CptLabel"); - - callForProjectSettingByKey("my.key", "My Value", file.getDbKey()); + assertThatThrownBy(() -> { + callForProjectSettingByKey("my.key", "My Value", file.getDbKey()); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Setting 'my.key' cannot be set on a CptLabel"); } @Test @@ -880,18 +893,20 @@ public class SetActionTest { i18n.put("qualifier." + component.qualifier(), "QualifierLabel"); logInAsProjectAdministrator(root); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Setting 'my.key' cannot be set on a QualifierLabel"); - - callForProjectSettingByKey("my.key", "My Value", component.getDbKey()); + assertThatThrownBy(() -> { + callForProjectSettingByKey("my.key", "My Value", component.getDbKey()); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Setting 'my.key' cannot be set on a QualifierLabel"); } @Test public void fail_when_single_and_multi_value_provided() { - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Either 'value', 'values' or 'fieldValues' must be provided"); - - call("my.key", "My Value", newArrayList("Another Value"), null, null); + assertThatThrownBy(() -> { + call("my.key", "My Value", newArrayList("Another Value"), null, null); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Either 'value', 'values' or 'fieldValues' must be provided"); } @Test @@ -905,10 +920,11 @@ public class SetActionTest { .multiValues(true) .build()); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Parameter 'value' must be used for single value setting. Parameter 'values' must be used for multi value setting."); - - callForGlobalSetting("my.key", "My Value"); + assertThatThrownBy(() -> { + callForGlobalSetting("my.key", "My Value"); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Parameter 'value' must be used for single value setting. Parameter 'values' must be used for multi value setting."); } @Test @@ -922,10 +938,11 @@ public class SetActionTest { .multiValues(false) .build()); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Parameter 'value' must be used for single value setting. Parameter 'values' must be used for multi value setting."); - - callForMultiValueGlobalSetting("my.key", newArrayList("My Value")); + assertThatThrownBy(() -> { + callForMultiValueGlobalSetting("my.key", newArrayList("My Value")); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Parameter 'value' must be used for single value setting. Parameter 'values' must be used for multi value setting."); } @Test @@ -949,13 +966,14 @@ public class SetActionTest { .build())) .build()); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("A non empty value must be provided"); - - callForGlobalPropertySet("my.key", newArrayList( - GSON.toJson(ImmutableMap.of("firstField", "firstValue", "secondField", "secondValue")), - GSON.toJson(ImmutableMap.of("firstField", "", "secondField", "")), - GSON.toJson(ImmutableMap.of("firstField", "yetFirstValue", "secondField", "yetSecondValue")))); + assertThatThrownBy(() -> { + callForGlobalPropertySet("my.key", newArrayList( + GSON.toJson(ImmutableMap.of("firstField", "firstValue", "secondField", "secondValue")), + GSON.toJson(ImmutableMap.of("firstField", "", "secondField", "")), + GSON.toJson(ImmutableMap.of("firstField", "yetFirstValue", "secondField", "yetSecondValue")))); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("A non empty value must be provided"); } @Test @@ -989,10 +1007,11 @@ public class SetActionTest { @Test public void fail_when_property_set_setting_is_not_defined() { - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Setting 'my.key' is undefined"); - - callForGlobalPropertySet("my.key", singletonList("{\"field\":\"value\"}")); + assertThatThrownBy(() -> { + callForGlobalPropertySet("my.key", singletonList("{\"field\":\"value\"}")); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Setting 'my.key' is undefined"); } @Test @@ -1012,10 +1031,11 @@ public class SetActionTest { .build())) .build()); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Unknown field key 'unknownField' for setting 'my.key'"); - - callForGlobalPropertySet("my.key", newArrayList(GSON.toJson(ImmutableMap.of("field", "value", "unknownField", "anotherValue")))); + assertThatThrownBy(() -> { + callForGlobalPropertySet("my.key", newArrayList(GSON.toJson(ImmutableMap.of("field", "value", "unknownField", "anotherValue")))); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Unknown field key 'unknownField' for setting 'my.key'"); } @Test @@ -1035,10 +1055,11 @@ public class SetActionTest { .build())) .build()); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Error when validating setting with key 'my.key'. Field 'field' has incorrect value 'notAnInt'."); - - callForGlobalPropertySet("my.key", newArrayList(GSON.toJson(ImmutableMap.of("field", "notAnInt")))); + assertThatThrownBy(() -> { + callForGlobalPropertySet("my.key", newArrayList(GSON.toJson(ImmutableMap.of("field", "notAnInt")))); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Error when validating setting with key 'my.key'. Field 'field' has incorrect value 'notAnInt'."); } @Test @@ -1058,10 +1079,11 @@ public class SetActionTest { .build())) .build()); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("A non empty value must be provided"); - - callForGlobalPropertySet("my.key", newArrayList("{\"field\": null}")); + assertThatThrownBy(() -> { + callForGlobalPropertySet("my.key", newArrayList("{\"field\": null}")); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("A non empty value must be provided"); } @Test @@ -1081,11 +1103,12 @@ public class SetActionTest { .build())) .build()); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("JSON 'incorrectJson:incorrectJson' does not respect expected format for setting 'my.key'. " + - "Ex: {\"field1\":\"value1\", \"field2\":\"value2\"}"); - - callForGlobalPropertySet("my.key", newArrayList("incorrectJson:incorrectJson")); + assertThatThrownBy(() -> { + callForGlobalPropertySet("my.key", newArrayList("incorrectJson:incorrectJson")); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("JSON 'incorrectJson:incorrectJson' does not respect expected format for setting 'my.key'. " + + "Ex: {\"field1\":\"value1\", \"field2\":\"value2\"}"); } @Test @@ -1105,11 +1128,12 @@ public class SetActionTest { .build())) .build()); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("JSON '[{\"field\":\"v1\"}, {\"field\":\"v2\"}]' does not respect expected format for setting 'my.key'. " + - "Ex: {\"field1\":\"value1\", \"field2\":\"value2\"}"); - - callForGlobalPropertySet("my.key", newArrayList("[{\"field\":\"v1\"}, {\"field\":\"v2\"}]")); + assertThatThrownBy(() -> { + callForGlobalPropertySet("my.key", newArrayList("[{\"field\":\"v1\"}, {\"field\":\"v2\"}]")); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("JSON '[{\"field\":\"v1\"}, {\"field\":\"v2\"}]' does not respect expected format for setting 'my.key'. " + + "Ex: {\"field1\":\"value1\", \"field2\":\"value2\"}"); } @Test @@ -1128,11 +1152,12 @@ public class SetActionTest { ComponentDto project = db.components().insertPrivateProject(); logInAsProjectAdministrator(project); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Setting 'my.key' cannot be set on a Project"); - - callForComponentPropertySet("my.key", newArrayList( - GSON.toJson(ImmutableMap.of("firstField", "firstValue"))), project.getDbKey()); + assertThatThrownBy(() -> { + callForComponentPropertySet("my.key", newArrayList( + GSON.toJson(ImmutableMap.of("firstField", "firstValue"))), project.getDbKey()); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Setting 'my.key' cannot be set on a Project"); } @Test @@ -1141,22 +1166,24 @@ public class SetActionTest { userSession.logIn().addProjectPermission(UserRole.ADMIN, project); ComponentDto branch = db.components().insertProjectBranch(project); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(format("Component key '%s' not found", branch.getDbKey())); - - callForProjectSettingByKey("my.key", "My Value", branch.getDbKey()); + assertThatThrownBy(() -> { + callForProjectSettingByKey("my.key", "My Value", branch.getDbKey()); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage(format("Component key '%s' not found", branch.getDbKey())); } @Test public void fail_when_component_not_found() { - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Component key 'unknown' not found"); - - ws.newRequest() - .setParam("key", "foo") - .setParam("value", "2") - .setParam("component", "unknown") - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam("key", "foo") + .setParam("value", "2") + .setParam("component", "unknown") + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("Component key 'unknown' not found"); } @Test @@ -1165,14 +1192,15 @@ public class SetActionTest { logInAsProjectAdministrator(project); String settingKey = ProcessProperties.Property.JDBC_URL.getKey(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(format("Setting '%s' can only be used in sonar.properties", settingKey)); - - ws.newRequest() - .setParam("key", settingKey) - .setParam("value", "any value") - .setParam("component", project.getKey()) - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam("key", settingKey) + .setParam("value", "any value") + .setParam("component", project.getKey()) + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage(format("Setting '%s' can only be used in sonar.properties", settingKey)); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/setting/ws/SettingsUpdaterTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/setting/ws/SettingsUpdaterTest.java index 27f8169904a..2beee1faa34 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/setting/ws/SettingsUpdaterTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/setting/ws/SettingsUpdaterTest.java @@ -22,7 +22,6 @@ package org.sonar.server.setting.ws; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.PropertyType; import org.sonar.api.config.PropertyDefinition; import org.sonar.api.config.PropertyDefinitions; @@ -41,14 +40,13 @@ import org.sonar.db.user.UserTesting; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.db.property.PropertyTesting.newComponentPropertyDto; import static org.sonar.db.property.PropertyTesting.newGlobalPropertyDto; import static org.sonar.db.property.PropertyTesting.newUserPropertyDto; public class SettingsUpdaterTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester db = DbTester.create(System2.INSTANCE); @@ -186,18 +184,20 @@ public class SettingsUpdaterTest { @Test public void fail_to_delete_global_setting_when_no_setting_key() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("At least one setting key is required"); - - underTest.deleteGlobalSettings(dbSession); + assertThatThrownBy(() -> { + underTest.deleteGlobalSettings(dbSession); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("At least one setting key is required"); } @Test public void fail_to_delete_component_setting_when_no_setting_key() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("At least one setting key is required"); - - underTest.deleteComponentSettings(dbSession, project); + assertThatThrownBy(() -> { + underTest.deleteComponentSettings(dbSession, project); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("At least one setting key is required"); } private void assertGlobalPropertyDoesNotExist(String key) { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/setting/ws/ValuesActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/setting/ws/ValuesActionTest.java index fafc5b77b31..e679e0c4d9e 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/setting/ws/ValuesActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/setting/ws/ValuesActionTest.java @@ -28,7 +28,6 @@ import javax.annotation.Nullable; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.PropertyType; import org.sonar.api.config.PropertyDefinition; import org.sonar.api.config.PropertyDefinitions; @@ -59,6 +58,7 @@ import static java.lang.String.format; import static java.util.Arrays.asList; import static java.util.Comparator.comparing; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.groups.Tuple.tuple; import static org.sonar.api.resources.Qualifiers.MODULE; import static org.sonar.api.resources.Qualifiers.PROJECT; @@ -77,8 +77,6 @@ public class ValuesActionTest { private static Joiner COMMA_JOINER = Joiner.on(","); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -711,9 +709,10 @@ public class ValuesActionTest { userSession.logIn("project-admin").addProjectPermission(CODEVIEWER, project); definitions.addComponent(PropertyDefinition.builder("foo").build()); - expectedException.expect(ForbiddenException.class); - - executeRequest(project.getDbKey(), "foo"); + assertThatThrownBy(() -> { + executeRequest(project.getDbKey(), "foo"); + }) + .isInstanceOf(ForbiddenException.class); } @Test @@ -726,21 +725,23 @@ public class ValuesActionTest { propertyDb.insertProperties(null, null, null, null, newGlobalPropertyDto().setKey("foo").setValue("one")); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("'foo' and 'deprecated' cannot be used at the same time as they refer to the same setting"); - - executeRequestForGlobalProperties("foo", "deprecated"); + assertThatThrownBy(() -> { + executeRequestForGlobalProperties("foo", "deprecated"); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("'foo' and 'deprecated' cannot be used at the same time as they refer to the same setting"); } @Test public void fail_when_component_not_found() { - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Component key 'unknown' not found"); - - newTester().newRequest() - .setParam("keys", "foo") - .setParam("component", "unknown") - .execute(); + assertThatThrownBy(() -> { + newTester().newRequest() + .setParam("keys", "foo") + .setParam("component", "unknown") + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("Component key 'unknown' not found"); } @Test @@ -786,13 +787,14 @@ public class ValuesActionTest { userSession.logIn().addProjectPermission(UserRole.USER, project); ComponentDto branch = db.components().insertProjectBranch(project); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(format("Component key '%s' not found", branch.getDbKey())); - - newTester().newRequest() - .setParam("keys", "foo") - .setParam("component", branch.getDbKey()) - .execute(); + assertThatThrownBy(() -> { + newTester().newRequest() + .setParam("keys", "foo") + .setParam("component", branch.getDbKey()) + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage(format("Component key '%s' not found", branch.getDbKey())); } @Test @@ -801,13 +803,14 @@ public class ValuesActionTest { userSession.logIn().addProjectPermission(UserRole.USER, project); String settingKey = ProcessProperties.Property.JDBC_URL.getKey(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(format("Setting '%s' can only be used in sonar.properties", settingKey)); - - newTester().newRequest() - .setParam("keys", settingKey) - .setParam("component", project.getKey()) - .execute(); + assertThatThrownBy(() -> { + newTester().newRequest() + .setParam("keys", settingKey) + .setParam("component", project.getKey()) + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage(format("Setting '%s' can only be used in sonar.properties", settingKey)); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/source/SourceServiceTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/source/SourceServiceTest.java index c4a99ac8ec9..cefd6b58a24 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/source/SourceServiceTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/source/SourceServiceTest.java @@ -28,7 +28,6 @@ import java.util.Set; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.utils.System2; import org.sonar.core.util.Uuids; import org.sonar.db.DbTester; @@ -37,6 +36,7 @@ import org.sonar.db.source.FileSourceDto; import org.sonar.server.source.index.FileSourceTesting; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -47,8 +47,6 @@ public class SourceServiceTest { @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); - @Rule - public ExpectedException expectedException = ExpectedException.none(); HtmlSourceDecorator htmlDecorator = mock(HtmlSourceDecorator.class); @@ -108,18 +106,16 @@ public class SourceServiceTest { @Test public void getLines_fails_if_range_starts_at_zero() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Line number must start at 1, got 0"); - - underTest.getLines(dbTester.getSession(), FILE_UUID, 0, 2); + assertThatThrownBy(() -> underTest.getLines(dbTester.getSession(), FILE_UUID, 0, 2)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Line number must start at 1, got 0"); } @Test public void getLines_fails_if_range_upper_bound_less_than_lower_bound() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Line number must greater than or equal to 5, got 4"); - - underTest.getLines(dbTester.getSession(), FILE_UUID, 5, 4); + assertThatThrownBy(() -> underTest.getLines(dbTester.getSession(), FILE_UUID, 5, 4)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Line number must greater than or equal to 5, got 4"); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/source/ws/IndexActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/source/ws/IndexActionTest.java index 9446eb3d548..fbda9134695 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/source/ws/IndexActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/source/ws/IndexActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.source.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.utils.System2; import org.sonar.core.util.Uuids; import org.sonar.db.DbTester; @@ -38,6 +37,7 @@ import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; import static java.lang.String.format; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.web.UserRole.CODEVIEWER; import static org.sonar.api.web.UserRole.USER; import static org.sonar.db.component.ComponentTesting.newFileDto; @@ -45,8 +45,6 @@ import static org.sonar.test.JsonAssert.assertJson; public class IndexActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -101,20 +99,18 @@ public class IndexActionTest { userSession.addProjectPermission(USER, project); ComponentDto file = db.components().insertComponent(newFileDto(project)); - expectedException.expect(ForbiddenException.class); - - tester.newRequest() + assertThatThrownBy(() -> tester.newRequest() .setParam("resource", file.getDbKey()) - .execute(); + .execute()) + .isInstanceOf(ForbiddenException.class); } @Test public void fail_when_component_does_not_exist() { - expectedException.expect(NotFoundException.class); - - tester.newRequest() + assertThatThrownBy(() -> tester.newRequest() .setParam("resource", "unknown") - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class); } @Test @@ -123,12 +119,11 @@ public class IndexActionTest { ComponentDto branch = db.components().insertProjectBranch(project); userSession.addProjectPermission(USER, project); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(format("Component key '%s' not found", branch.getDbKey())); - - tester.newRequest() + assertThatThrownBy(() -> tester.newRequest() .setParam("resource", branch.getDbKey()) - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining(format("Component key '%s' not found", branch.getDbKey())); } private static DbFileSources.Data newData(String... lines) { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/source/ws/IssueSnippetsActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/source/ws/IssueSnippetsActionTest.java index 520d8b635d6..ace7be4113c 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/source/ws/IssueSnippetsActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/source/ws/IssueSnippetsActionTest.java @@ -24,7 +24,6 @@ import java.util.Arrays; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.stubbing.Answer; import org.sonar.api.utils.System2; import org.sonar.db.DbClient; @@ -48,6 +47,7 @@ import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; import org.sonar.test.JsonAssert; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -64,8 +64,6 @@ import static org.sonar.db.component.ComponentTesting.newFileDto; public class IssueSnippetsActionTest { private static final String SCM_AUTHOR_JSON_FIELD = "scmAuthor"; - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester db = DbTester.create(System2.INSTANCE); @Rule @@ -161,8 +159,9 @@ public class IssueSnippetsActionTest { userSession.logIn().addProjectPermission(USER, project, file); String issueKey = insertIssue(file, newLocation(file.uuid(), 5, 5)); - expectedException.expect(ForbiddenException.class); - actionTester.newRequest().setParam("issueKey", issueKey).execute(); + + assertThatThrownBy(() -> actionTester.newRequest().setParam("issueKey", issueKey).execute()) + .isInstanceOf(ForbiddenException.class); } @Test @@ -171,9 +170,9 @@ public class IssueSnippetsActionTest { insertIssue(file, newLocation(file.uuid(), 5, 5)); userSession.logIn().addProjectPermission(CODEVIEWER, project, file); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Issue with key 'invalid' does not exist"); - actionTester.newRequest().setParam("issueKey", "invalid").execute(); + assertThatThrownBy(() -> actionTester.newRequest().setParam("issueKey", "invalid").execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("Issue with key 'invalid' does not exist"); } @Test @@ -181,10 +180,9 @@ public class IssueSnippetsActionTest { ComponentDto file = insertFile(project, "file"); userSession.logIn().addProjectPermission(CODEVIEWER, project, file); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The 'issueKey' parameter is missing"); - - actionTester.newRequest().execute(); + assertThatThrownBy(() -> actionTester.newRequest().execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("The 'issueKey' parameter is missing"); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/source/ws/LinesActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/source/ws/LinesActionTest.java index 2cbec0cee39..9ceb41d110c 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/source/ws/LinesActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/source/ws/LinesActionTest.java @@ -22,7 +22,6 @@ package org.sonar.server.source.ws; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.stubbing.Answer; import org.sonar.api.utils.System2; import org.sonar.api.web.UserRole; @@ -48,6 +47,7 @@ import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; import static java.lang.String.format; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -56,8 +56,6 @@ import static org.sonar.db.component.ComponentTesting.newFileDto; public class LinesActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester db = DbTester.create(System2.INSTANCE); @Rule @@ -99,9 +97,8 @@ public class LinesActionTest { TestRequest request = tester.newRequest() .setParam("uuid", file.uuid()); - expectedException.expect(NotFoundException.class); - - request.execute(); + assertThatThrownBy(() -> request.execute()) + .isInstanceOf(NotFoundException.class); } @Test @@ -167,26 +164,23 @@ public class LinesActionTest { @Test public void fail_when_no_uuid_or_key_param() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Either 'uuid' or 'key' must be provided"); - - tester.newRequest().execute(); + assertThatThrownBy(() -> tester.newRequest().execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Either 'uuid' or 'key' must be provided"); } @Test public void fail_when_file_key_does_not_exist() { - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Component key 'Foo.java' not found"); - - tester.newRequest().setParam("key", "Foo.java").execute(); + assertThatThrownBy(() -> tester.newRequest().setParam("key", "Foo.java").execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("Component key 'Foo.java' not found"); } @Test public void fail_when_file_uuid_does_not_exist() { - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Component id 'ABCD' not found"); - - tester.newRequest().setParam("uuid", "ABCD").execute(); + assertThatThrownBy(() -> tester.newRequest().setParam("uuid", "ABCD").execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("Component id 'ABCD' not found"); } @Test @@ -196,22 +190,24 @@ public class LinesActionTest { db.components().insertComponents(file); setUserWithValidPermission(file); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Component key 'file-key' not found"); - - tester.newRequest().setParam("key", "file-key").execute(); + assertThatThrownBy(() -> tester.newRequest().setParam("key", "file-key").execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("Component key 'file-key' not found"); } - @Test(expected = ForbiddenException.class) + @Test public void check_permission() { ComponentDto privateProject = db.components().insertPrivateProject(); ComponentDto file = insertFileWithData(FileSourceTesting.newFakeData(1).build(), privateProject); userSession.logIn("login"); - tester.newRequest() - .setParam("uuid", file.uuid()) - .execute(); + assertThatThrownBy(() -> { + tester.newRequest() + .setParam("uuid", file.uuid()) + .execute(); + }) + .isInstanceOf(ForbiddenException.class); } @Test @@ -308,13 +304,12 @@ public class LinesActionTest { userSession.addProjectPermission(UserRole.USER, project); db.components().insertProjectBranch(project, b -> b.setKey("my_branch")); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(String.format("Component '%s' on branch '%s' not found", file.getKey(), "another_branch")); - - tester.newRequest() + assertThatThrownBy(() -> tester.newRequest() .setParam("key", file.getKey()) .setParam("branch", "another_branch") - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining(String.format("Component '%s' on branch '%s' not found", file.getKey(), "another_branch")); } @Test @@ -324,13 +319,12 @@ public class LinesActionTest { userSession.addProjectPermission(UserRole.USER, project); db.components().insertProjectBranch(project, b -> b.setKey("my_branch")); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Parameter 'uuid' cannot be used at the same time as 'branch' or 'pullRequest'"); - - tester.newRequest() + assertThatThrownBy(() -> tester.newRequest() .setParam("uuid", file.uuid()) .setParam("branch", "another_branch") - .execute(); + .execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Parameter 'uuid' cannot be used at the same time as 'branch' or 'pullRequest'"); } @Test @@ -339,12 +333,11 @@ public class LinesActionTest { ComponentDto branch = db.components().insertProjectBranch(project); userSession.addProjectPermission(UserRole.USER, project); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(format("Component key '%s' not found", branch.getDbKey())); - - tester.newRequest() + assertThatThrownBy(() -> tester.newRequest() .setParam("key", branch.getDbKey()) - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining(format("Component key '%s' not found", branch.getDbKey())); } @Test @@ -353,12 +346,11 @@ public class LinesActionTest { ComponentDto branch = db.components().insertProjectBranch(project); userSession.addProjectPermission(UserRole.USER, project); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(format("Component id '%s' not found", branch.uuid())); - - tester.newRequest() + assertThatThrownBy(() -> tester.newRequest() .setParam("uuid", branch.uuid()) - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining(format("Component id '%s' not found", branch.uuid())); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/source/ws/RawActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/source/ws/RawActionTest.java index c4caeb46941..a659558d37a 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/source/ws/RawActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/source/ws/RawActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.source.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.resources.Qualifiers; import org.sonar.api.utils.System2; import org.sonar.api.web.UserRole; @@ -37,14 +36,13 @@ import org.sonar.server.ws.WsActionTester; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.db.component.ComponentTesting.newFileDto; import static org.sonar.db.protobuf.DbFileSources.Data; import static org.sonar.db.protobuf.DbFileSources.Line; public class RawActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -96,12 +94,11 @@ public class RawActionTest { @Test public void fail_on_unknown_file() { - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Component key 'unknown' not found"); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("key", "unknown") - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining("Component key 'unknown' not found"); } @Test @@ -112,13 +109,12 @@ public class RawActionTest { ComponentDto file = db.components().insertComponent(newFileDto(branch)); db.fileSources().insertFileSource(file); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(format("Component '%s' on branch 'unknown' not found", file.getKey())); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("key", file.getKey()) .setParam("branch", "unknown") - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining(format("Component '%s' on branch 'unknown' not found", file.getKey())); } @Test @@ -129,12 +125,11 @@ public class RawActionTest { ComponentDto file = db.components().insertComponent(newFileDto(branch)); db.fileSources().insertFileSource(file); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(format("Component key '%s' not found", file.getDbKey())); - - ws.newRequest() - .setParam("key", file.getDbKey()) - .execute(); + assertThatThrownBy(() -> ws.newRequest() + .setParam("key", file.getKey()) + .execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining(format("Component key '%s' not found", file.getKey())); } @Test @@ -143,10 +138,9 @@ public class RawActionTest { userSession.addProjectPermission(UserRole.ISSUE_ADMIN, project); ComponentDto file = db.components().insertComponent(newFileDto(project)); - expectedException.expect(ForbiddenException.class); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setParam("key", file.getKey()) - .execute(); + .execute()) + .isInstanceOf(ForbiddenException.class); } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/source/ws/ScmActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/source/ws/ScmActionTest.java index 4157b78a670..2f6fa54c32b 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/source/ws/ScmActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/source/ws/ScmActionTest.java @@ -23,7 +23,6 @@ import java.util.Date; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.utils.DateUtils; import org.sonar.api.utils.System2; import org.sonar.api.web.UserRole; @@ -44,6 +43,7 @@ import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.WsActionTester; import static java.lang.String.format; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class ScmActionTest { @@ -54,8 +54,6 @@ public class ScmActionTest { @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Rule public UserSessionRule userSessionRule = UserSessionRule.standalone(); private final DbClient dbClient = dbTester.getDbClient(); @@ -205,13 +203,16 @@ public class ScmActionTest { .assertJson(getClass(), "return_empty_value_when_no_scm.json"); } - @Test(expected = ForbiddenException.class) + @Test public void fail_without_code_viewer_permission() { userSessionRule.addProjectPermission(UserRole.USER, project, file); - tester.newRequest() - .setParam("key", FILE_KEY) - .execute(); + assertThatThrownBy(() -> { + tester.newRequest() + .setParam("key", FILE_KEY) + .execute(); + }) + .isInstanceOf(ForbiddenException.class); } @Test @@ -220,12 +221,11 @@ public class ScmActionTest { ComponentDto branch = dbTester.components().insertProjectBranch(project); userSessionRule.addProjectPermission(UserRole.CODEVIEWER, project); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(format("Component key '%s' not found", branch.getDbKey())); - - tester.newRequest() + assertThatThrownBy(() -> tester.newRequest() .setParam("key", branch.getDbKey()) - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class) + .hasMessageContaining(format("Component key '%s' not found", branch.getDbKey())); } private DbFileSources.Line newSourceLine(String author, String revision, Date date, int line) { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/source/ws/ShowActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/source/ws/ShowActionTest.java index ed5be088c5c..00c29a179c5 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/source/ws/ShowActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/source/ws/ShowActionTest.java @@ -38,6 +38,7 @@ import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.WsActionTester; import static com.google.common.collect.Lists.newArrayList; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; @@ -118,10 +119,12 @@ public class ShowActionTest { verify(sourceService).getLinesAsHtml(session, file.uuid(), 1, 5); } - @Test(expected = ForbiddenException.class) + @Test public void require_code_viewer() { String fileKey = "src/Foo.java"; when(componentDao.selectByKey(session, fileKey)).thenReturn(Optional.of(file)); - tester.newRequest().setParam("key", fileKey).execute(); + + assertThatThrownBy(() -> tester.newRequest().setParam("key", fileKey).execute()) + .isInstanceOf(ForbiddenException.class); } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ui/PageRepositoryTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ui/PageRepositoryTest.java index b5cd629fd36..afab3703339 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ui/PageRepositoryTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ui/PageRepositoryTest.java @@ -23,7 +23,6 @@ import java.util.List; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.resources.Qualifiers; import org.sonar.api.utils.log.LogTester; import org.sonar.api.web.page.Page; @@ -34,6 +33,7 @@ import org.sonar.core.platform.PluginInfo; import org.sonar.core.platform.PluginRepository; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; @@ -43,8 +43,6 @@ import static org.sonar.api.web.page.Page.Scope.GLOBAL; public class PageRepositoryTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public LogTester logTester = new LogTester(); @@ -65,7 +63,7 @@ public class PageRepositoryTest { .addPage(Page.builder("my_plugin/K1").setName("N1").build()) .addPage(Page.builder("my_plugin/K3").setName("N3").build()); PageDefinition secondPlugin = context -> context.addPage(Page.builder("my_plugin/K2").setName("N2").build()); - underTest = new PageRepository(pluginRepository, coreExtensionRepository, new PageDefinition[] {firstPlugin, secondPlugin}); + underTest = new PageRepository(pluginRepository, coreExtensionRepository, new PageDefinition[]{firstPlugin, secondPlugin}); underTest.start(); List result = underTest.getAllPages(); @@ -88,7 +86,7 @@ public class PageRepositoryTest { .addPage(Page.builder("my_plugin/K4").setName("K4").setScope(GLOBAL).build()) .addPage(Page.builder("my_plugin/K5").setName("K5").setScope(COMPONENT).setComponentQualifiers(Qualifier.VIEW).build()) .addPage(Page.builder("my_plugin/K6").setName("K6").setScope(COMPONENT).setComponentQualifiers(Qualifier.APP).build()); - underTest = new PageRepository(pluginRepository, coreExtensionRepository, new PageDefinition[] {plugin}); + underTest = new PageRepository(pluginRepository, coreExtensionRepository, new PageDefinition[]{plugin}); underTest.start(); List result = underTest.getComponentPages(false, Qualifiers.PROJECT); @@ -113,7 +111,7 @@ public class PageRepositoryTest { .addPage(Page.builder("my_plugin/K1").setName("N1").build()) .addPage(Page.builder("my_plugin/K2").setName("N2").build()) .addPage(Page.builder("my_plugin/K3").setName("N3").build()); - underTest = new PageRepository(pluginRepository, coreExtensionRepository, new PageDefinition[] {plugin}); + underTest = new PageRepository(pluginRepository, coreExtensionRepository, new PageDefinition[]{plugin}); underTest.start(); List result = underTest.getGlobalPages(false); @@ -125,10 +123,9 @@ public class PageRepositoryTest { @Test public void fail_if_pages_called_before_server_startup() { - expectedException.expect(NullPointerException.class); - expectedException.expectMessage("Pages haven't been initialized yet"); - - underTest.getAllPages(); + assertThatThrownBy(() -> underTest.getAllPages()) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("Pages haven't been initialized yet"); } @Test @@ -137,11 +134,10 @@ public class PageRepositoryTest { PageDefinition plugin42 = context -> context.addPage(Page.builder("plugin_42/my_key").setName("N2").build()); pluginRepository = mock(PluginRepository.class); when(pluginRepository.hasPlugin("governance")).thenReturn(true); - underTest = new PageRepository(pluginRepository, coreExtensionRepository, new PageDefinition[] {governance, plugin42}); + underTest = new PageRepository(pluginRepository, coreExtensionRepository, new PageDefinition[]{governance, plugin42}); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Page 'N2' references plugin 'plugin_42' that does not exist"); - - underTest.start(); + assertThatThrownBy(() -> underTest.start()) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Page 'N2' references plugin 'plugin_42' that does not exist"); } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ui/ws/ComponentActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ui/ws/ComponentActionTest.java index 0dc807153d1..a12f8aa65e4 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ui/ws/ComponentActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ui/ws/ComponentActionTest.java @@ -716,16 +716,17 @@ public class ComponentActionTest { assertThat(componentId.exampleValue()).isNotNull(); } - @Test(expected = BadRequestException.class) + @Test public void fail_on_module_key_as_param() { ComponentDto project = insertProject(); ComponentDto module = componentDbTester.insertComponent(newModuleDto("bcde", project).setDbKey("palap").setName("Palap")); init(); - execute(module.getKey()); + assertThatThrownBy(() -> execute(module.getKey())) + .isInstanceOf(BadRequestException.class); } - @Test(expected = BadRequestException.class) + @Test public void fail_on_directory_key_as_param() { ComponentDto project = insertProject(); ComponentDto module = componentDbTester.insertComponent(newModuleDto("bcde", project).setDbKey("palap").setName("Palap")); @@ -733,7 +734,8 @@ public class ComponentActionTest { userSession.addProjectPermission(UserRole.USER, project); init(); - execute(directory.getDbKey()); + assertThatThrownBy(() -> execute(directory.getDbKey())) + .isInstanceOf(BadRequestException.class); } private ComponentDto insertProject() { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ui/ws/MarketplaceActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ui/ws/MarketplaceActionTest.java index 6a617f93407..a55a8a752dc 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ui/ws/MarketplaceActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/ui/ws/MarketplaceActionTest.java @@ -22,7 +22,6 @@ package org.sonar.server.ui.ws; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.api.platform.Server; import org.sonar.api.server.ws.WebService; @@ -38,6 +37,7 @@ import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.Navigation; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.api.measures.CoreMetrics.NCLOC_KEY; @@ -47,8 +47,6 @@ import static org.sonar.test.JsonAssert.assertJson; @RunWith(DataProviderRunner.class) public class MarketplaceActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSessionRule = UserSessionRule.standalone(); @Rule @@ -77,10 +75,9 @@ public class MarketplaceActionTest { userSessionRule.anonymous(); TestRequest request = ws.newRequest(); - expectedException.expect(UnauthorizedException.class); - expectedException.expectMessage("Authentication is required"); - - request.execute(); + assertThatThrownBy(() -> request.execute()) + .isInstanceOf(UnauthorizedException.class) + .hasMessageContaining("Authentication is required"); } @Test @@ -88,10 +85,9 @@ public class MarketplaceActionTest { userSessionRule.logIn(); TestRequest request = ws.newRequest(); - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - - request.execute(); + assertThatThrownBy(() -> request.execute()) + .isInstanceOf(ForbiddenException.class) + .hasMessageContaining("Insufficient privileges"); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/CreateActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/CreateActionTest.java index e4fea469850..4946ebba46c 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/CreateActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/CreateActionTest.java @@ -24,7 +24,6 @@ import org.elasticsearch.search.builder.SearchSourceBuilder; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.impl.utils.AlwaysIncreasingSystem2; import org.sonar.api.server.ws.WebService; @@ -52,6 +51,7 @@ import static java.lang.String.format; import static java.util.Collections.singletonList; import static java.util.Optional.ofNullable; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.elasticsearch.index.query.QueryBuilders.boolQuery; import static org.elasticsearch.index.query.QueryBuilders.termQuery; import static org.mockito.Mockito.mock; @@ -72,8 +72,6 @@ public class CreateActionTest { public EsTester es = EsTester.create(); @Rule public UserSessionRule userSessionRule = UserSessionRule.standalone(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private final UserIndexer userIndexer = new UserIndexer(db.getDbClient(), es.client()); private GroupDto defaultGroup; @@ -104,12 +102,12 @@ public class CreateActionTest { // exists in index assertThat(es.client().search(EsClient.prepareSearch(UserIndexDefinition.TYPE_USER) - .source(new SearchSourceBuilder() - .query(boolQuery() - .must(termQuery(FIELD_LOGIN, "john")) - .must(termQuery(FIELD_NAME, "John")) - .must(termQuery(FIELD_EMAIL, "john@email.com")) - .must(termQuery(FIELD_SCM_ACCOUNTS, "jn"))))) + .source(new SearchSourceBuilder() + .query(boolQuery() + .must(termQuery(FIELD_LOGIN, "john")) + .must(termQuery(FIELD_NAME, "John")) + .must(termQuery(FIELD_EMAIL, "john@email.com")) + .must(termQuery(FIELD_SCM_ACCOUNTS, "jn"))))) .getHits().getHits()).hasSize(1); // exists in db @@ -206,106 +204,116 @@ public class CreateActionTest { logInAsSystemAdministrator(); UserDto user = db.users().insertUser(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(format("An active user with login '%s' already exists", user.getLogin())); - - call(CreateRequest.builder() - .setLogin(user.getLogin()) - .setName("John") - .setPassword("1234") - .build()); + assertThatThrownBy(() -> { + call(CreateRequest.builder() + .setLogin(user.getLogin()) + .setName("John") + .setPassword("1234") + .build()); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage(format("An active user with login '%s' already exists", user.getLogin())); } @Test public void fail_when_missing_login() { logInAsSystemAdministrator(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Login is mandatory and must not be empty"); - call(CreateRequest.builder() - .setLogin(null) - .setName("John") - .setPassword("1234") - .build()); + assertThatThrownBy(() -> { + call(CreateRequest.builder() + .setLogin(null) + .setName("John") + .setPassword("1234") + .build()); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Login is mandatory and must not be empty"); } @Test public void fail_when_login_is_too_short() { logInAsSystemAdministrator(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("'login' length (1) is shorter than the minimum authorized (2)"); - call(CreateRequest.builder() - .setLogin("a") - .setName("John") - .setPassword("1234") - .build()); + assertThatThrownBy(() -> { + call(CreateRequest.builder() + .setLogin("a") + .setName("John") + .setPassword("1234") + .build()); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("'login' length (1) is shorter than the minimum authorized (2)"); } @Test public void fail_when_missing_name() { logInAsSystemAdministrator(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Name is mandatory and must not be empty"); - call(CreateRequest.builder() - .setLogin("john") - .setName(null) - .setPassword("1234") - .build()); + assertThatThrownBy(() -> { + call(CreateRequest.builder() + .setLogin("john") + .setName(null) + .setPassword("1234") + .build()); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Name is mandatory and must not be empty"); } @Test public void fail_when_missing_password() { logInAsSystemAdministrator(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Password is mandatory and must not be empty"); - call(CreateRequest.builder() - .setLogin("john") - .setName("John") - .setPassword(null) - .build()); + assertThatThrownBy(() -> { + call(CreateRequest.builder() + .setLogin("john") + .setName("John") + .setPassword(null) + .build()); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Password is mandatory and must not be empty"); } @Test public void fail_when_password_is_set_on_none_local_user() { logInAsSystemAdministrator(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Password should only be set on local user"); - call(CreateRequest.builder() - .setLogin("john") - .setName("John") - .setPassword("1234") - .setLocal(false) - .build()); + assertThatThrownBy(() -> { + call(CreateRequest.builder() + .setLogin("john") + .setName("John") + .setPassword("1234") + .setLocal(false) + .build()); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Password should only be set on local user"); } @Test public void fail_when_email_is_invalid() { logInAsSystemAdministrator(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Email 'invalid-email' is not valid"); - - call(CreateRequest.builder() - .setLogin("pipo") - .setName("John") - .setPassword("1234") - .setEmail("invalid-email") - .build()); + assertThatThrownBy(() -> { + call(CreateRequest.builder() + .setLogin("pipo") + .setName("John") + .setPassword("1234") + .setEmail("invalid-email") + .build()); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Email 'invalid-email' is not valid"); } @Test public void throw_ForbiddenException_if_not_system_administrator() { userSessionRule.logIn().setNonSystemAdministrator(); - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage(""); - - expectedException.expect(ForbiddenException.class); - executeRequest("john"); + assertThatThrownBy(() -> executeRequest("john")) + .isInstanceOf(ForbiddenException.class) + .hasMessage("Insufficient privileges"); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/CurrentActionHomepageTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/CurrentActionHomepageTest.java index 2140e878133..303e6ca3dff 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/CurrentActionHomepageTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/CurrentActionHomepageTest.java @@ -26,7 +26,6 @@ import java.util.Optional; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.sonar.api.resources.Qualifiers; import org.sonar.api.resources.ResourceType; @@ -58,8 +57,6 @@ public class CurrentActionHomepageTest { public UserSessionRule userSessionRule = UserSessionRule.standalone(); @Rule public DbTester db = DbTester.create(System2.INSTANCE); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private final DbClient dbClient = db.getDbClient(); diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/DeactivateActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/DeactivateActionTest.java index 4bed9a39c92..e106abce134 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/DeactivateActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/DeactivateActionTest.java @@ -24,7 +24,6 @@ import javax.annotation.Nullable; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.impl.utils.AlwaysIncreasingSystem2; import org.sonar.api.utils.System2; import org.sonar.db.DbClient; @@ -59,6 +58,7 @@ import org.sonar.server.ws.WsActionTester; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.elasticsearch.index.query.QueryBuilders.boolQuery; import static org.elasticsearch.index.query.QueryBuilders.termQuery; import static org.sonar.api.web.UserRole.CODEVIEWER; @@ -75,8 +75,6 @@ public class DeactivateActionTest { private final System2 system2 = new AlwaysIncreasingSystem2(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester db = DbTester.create(system2); @Rule @@ -314,22 +312,24 @@ public class DeactivateActionTest { UserDto user = db.users().insertUser(); userSession.logIn(user.getLogin()).setSystemAdministrator(); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Self-deactivation is not possible"); - - deactivate(user.getLogin()); + assertThatThrownBy(() -> { + deactivate(user.getLogin()); - verifyThatUserExists(user.getLogin()); + verifyThatUserExists(user.getLogin()); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Self-deactivation is not possible"); } @Test public void deactivation_requires_to_be_logged_in() { createAdminUser(); - expectedException.expect(UnauthorizedException.class); - expectedException.expectMessage("Authentication is required"); - - deactivate("someone"); + assertThatThrownBy(() -> { + deactivate("someone"); + }) + .isInstanceOf(UnauthorizedException.class) + .hasMessage("Authentication is required"); } @Test @@ -337,10 +337,11 @@ public class DeactivateActionTest { createAdminUser(); userSession.logIn(); - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - - deactivate("someone"); + assertThatThrownBy(() -> { + deactivate("someone"); + }) + .isInstanceOf(ForbiddenException.class) + .hasMessage("Insufficient privileges"); } @Test @@ -348,10 +349,11 @@ public class DeactivateActionTest { createAdminUser(); logInAsSystemAdministrator(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("User 'someone' doesn't exist"); - - deactivate("someone"); + assertThatThrownBy(() -> { + deactivate("someone"); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("User 'someone' doesn't exist"); } @Test @@ -359,10 +361,11 @@ public class DeactivateActionTest { createAdminUser(); logInAsSystemAdministrator(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The 'login' parameter is missing"); - - deactivate(""); + assertThatThrownBy(() -> { + deactivate(""); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("The 'login' parameter is missing"); } @Test @@ -370,10 +373,11 @@ public class DeactivateActionTest { createAdminUser(); logInAsSystemAdministrator(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The 'login' parameter is missing"); - - deactivate(null); + assertThatThrownBy(() -> { + deactivate(null); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("The 'login' parameter is missing"); } @Test @@ -382,10 +386,11 @@ public class DeactivateActionTest { db.users().insertPermissionOnUser(admin, ADMINISTER); logInAsSystemAdministrator(); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("User is last administrator, and cannot be deactivated"); - - deactivate(admin.getLogin()); + assertThatThrownBy(() -> { + deactivate(admin.getLogin()); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("User is last administrator, and cannot be deactivated"); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/GroupsActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/GroupsActionTest.java index 4f79b727398..1e848c80684 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/GroupsActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/GroupsActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.user.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.api.server.ws.WebService.Param; import org.sonar.db.DbTester; @@ -38,6 +37,7 @@ import org.sonarqube.ws.Users.GroupsWsResponse; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.api.server.ws.WebService.SelectionMode.ALL; import static org.sonar.api.server.ws.WebService.SelectionMode.DESELECTED; @@ -51,8 +51,6 @@ public class GroupsActionTest { private static final String USER_LOGIN = "john"; - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester db = DbTester.create(); @@ -202,20 +200,22 @@ public class GroupsActionTest { GroupDto group = db.users().insertGroup("group1"); addUserToGroup(user, group); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Default group cannot be found"); - - call(ws.newRequest().setParam("login", USER_LOGIN)); + assertThatThrownBy(() -> { + call(ws.newRequest().setParam("login", USER_LOGIN)); + }) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Default group cannot be found"); } @Test public void fail_on_unknown_user() { insertDefaultGroup(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Unknown user: john"); - - call(ws.newRequest().setParam("login", USER_LOGIN)); + assertThatThrownBy(() -> { + call(ws.newRequest().setParam("login", USER_LOGIN)); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("Unknown user: john"); } @Test @@ -223,10 +223,11 @@ public class GroupsActionTest { UserDto userDto = db.users().insertUser(user -> user.setLogin("disabled").setActive(false)); insertDefaultGroup(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Unknown user: disabled"); - - call(ws.newRequest().setParam("login", userDto.getLogin())); + assertThatThrownBy(() -> { + call(ws.newRequest().setParam("login", userDto.getLogin())); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("Unknown user: disabled"); } @Test @@ -234,30 +235,33 @@ public class GroupsActionTest { UserDto user = insertUser(); insertDefaultGroup(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The 'ps' parameter must be less than 500"); - - call(ws.newRequest() - .setParam("login", user.getLogin()) - .setParam(Param.PAGE_SIZE, "501")); + assertThatThrownBy(() -> { + call(ws.newRequest() + .setParam("login", user.getLogin()) + .setParam(Param.PAGE_SIZE, "501")); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("The 'ps' parameter must be less than 500"); } @Test public void fail_on_missing_permission() { userSession.logIn().addPermission(SCAN); - expectedException.expect(ForbiddenException.class); - - call(ws.newRequest().setParam("login", USER_LOGIN)); + assertThatThrownBy(() -> { + call(ws.newRequest().setParam("login", USER_LOGIN)); + }) + .isInstanceOf(ForbiddenException.class); } @Test public void fail_when_no_permission() { userSession.logIn("not-admin"); - expectedException.expect(ForbiddenException.class); - - call(ws.newRequest().setParam("login", USER_LOGIN)); + assertThatThrownBy(() -> { + call(ws.newRequest().setParam("login", USER_LOGIN)); + }) + .isInstanceOf(ForbiddenException.class); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/IdentityProvidersActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/IdentityProvidersActionTest.java index 4391d6b30bd..78098d5832d 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/IdentityProvidersActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/IdentityProvidersActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.user.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.authentication.Display; import org.sonar.api.server.authentication.IdentityProvider; import org.sonar.api.server.ws.WebService; @@ -34,8 +33,6 @@ import static org.sonar.test.JsonAssert.assertJson; public class IdentityProvidersActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public IdentityProviderRepositoryRule identityProviderRepository = new IdentityProviderRepositoryRule() .addIdentityProvider(GITHUB) diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/SetHomepageActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/SetHomepageActionTest.java index f0010b1b71f..9ecbbf43e83 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/SetHomepageActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/SetHomepageActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.user.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbClient; import org.sonar.db.DbTester; @@ -35,6 +34,7 @@ import org.sonar.server.ws.WsActionTester; import static javax.servlet.http.HttpServletResponse.SC_NO_CONTENT; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.server.user.ws.SetHomepageAction.PARAM_COMPONENT; import static org.sonar.server.user.ws.SetHomepageAction.PARAM_TYPE; @@ -46,9 +46,6 @@ public class SetHomepageActionTest { @Rule public DbTester db = DbTester.create(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); - private final DbClient dbClient = db.getDbClient(); private final WsActionTester ws = new WsActionTester(new SetHomepageAction(userSession, dbClient, TestComponentFinder.from(db))); @@ -221,14 +218,12 @@ public class SetHomepageActionTest { UserDto user = db.users().insertUser(); userSession.logIn(user); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Type PROJECT requires a parameter"); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setMethod("POST") .setParam(PARAM_TYPE, "PROJECT") - .execute(); - + .execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Type PROJECT requires a parameter"); } @Test @@ -236,23 +231,22 @@ public class SetHomepageActionTest { UserDto user = db.users().insertUser(); userSession.logIn(user); - expectedException.expect(IllegalArgumentException.class); - expectedException - .expectMessage("Value of parameter 'type' (PIPO) must be one of: [PROJECT, PROJECTS, ISSUES, PORTFOLIOS, PORTFOLIO, APPLICATION]"); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setMethod("POST") .setParam(PARAM_TYPE, "PIPO") - .execute(); + .execute()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Value of parameter 'type' (PIPO) must be one of: [PROJECT, PROJECTS, ISSUES, PORTFOLIOS, PORTFOLIO, APPLICATION]"); } @Test public void fail_for_anonymous() { userSession.anonymous(); - expectedException.expect(UnauthorizedException.class); - expectedException.expectMessage("Authentication is required"); - - ws.newRequest().setMethod("POST").execute(); + assertThatThrownBy(() -> ws.newRequest() + .setMethod("POST") + .execute()) + .isInstanceOf(UnauthorizedException.class) + .hasMessageContaining("Authentication is required"); } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/SetSettingActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/SetSettingActionTest.java index 265c9c15b08..57006857bb7 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/SetSettingActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/SetSettingActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.user.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.db.DbTester; @@ -32,12 +31,11 @@ import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; public class SetSettingActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -100,12 +98,13 @@ public class SetSettingActionTest { @Test public void fail_when_not_authenticated() { - expectedException.expect(UnauthorizedException.class); - - ws.newRequest() - .setParam("key", "notifications.optOut") - .setParam("value", "true") - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam("key", "notifications.optOut") + .setParam("value", "true") + .execute(); + }) + .isInstanceOf(UnauthorizedException.class); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/SkipOnboardingTutorialActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/SkipOnboardingTutorialActionTest.java index de111e62272..7c200b264e1 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/SkipOnboardingTutorialActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/SkipOnboardingTutorialActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.user.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbTester; import org.sonar.db.user.UserDto; @@ -31,6 +30,7 @@ import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class SkipOnboardingTutorialActionTest { @@ -40,8 +40,6 @@ public class SkipOnboardingTutorialActionTest { @Rule public DbTester db = DbTester.create(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private WsActionTester ws = new WsActionTester(new SkipOnboardingTutorialAction(userSession, db.getDbClient())); @@ -73,10 +71,10 @@ public class SkipOnboardingTutorialActionTest { @Test public void fail_for_anonymous() { userSession.anonymous(); - expectedException.expect(UnauthorizedException.class); - expectedException.expectMessage("Authentication is required"); - call(); + assertThatThrownBy(() -> call()) + .isInstanceOf(UnauthorizedException.class) + .hasMessage("Authentication is required"); } @Test @@ -84,10 +82,9 @@ public class SkipOnboardingTutorialActionTest { db.users().insertUser(usert -> usert.setLogin("another")); userSession.logIn("obiwan.kenobi"); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("User login 'obiwan.kenobi' cannot be found"); - - call(); + assertThatThrownBy(() -> call()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("User login 'obiwan.kenobi' cannot be found"); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/UpdateActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/UpdateActionTest.java index 3beb0e68546..c9f8f34c311 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/UpdateActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/UpdateActionTest.java @@ -23,7 +23,6 @@ import java.util.Arrays; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; @@ -45,6 +44,7 @@ import org.sonar.server.ws.WsActionTester; import static com.google.common.collect.Lists.newArrayList; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.sonar.db.user.UserTesting.newUserDto; @@ -59,8 +59,6 @@ public class UpdateActionTest { public EsTester es = EsTester.create(); @Rule public UserSessionRule userSession = UserSessionRule.standalone().logIn().setSystemAdministrator(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private final DbClient dbClient = db.getDbClient(); private final DbSession dbSession = db.getSession(); @@ -91,26 +89,28 @@ public class UpdateActionTest { public void fail_on_update_name_non_local_user() { createUser(false); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Name cannot be updated for a non-local user"); - - ws.newRequest() - .setParam("login", "john") - .setParam("name", "Jean Neige") - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam("login", "john") + .setParam("name", "Jean Neige") + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Name cannot be updated for a non-local user"); } @Test public void fail_on_update_email_non_local_user() { createUser(false); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Email cannot be updated for a non-local user"); - - ws.newRequest() - .setParam("login", "john") - .setParam("email", "jean.neige@thegreatw.all") - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam("login", "john") + .setParam("email", "jean.neige@thegreatw.all") + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Email cannot be updated for a non-local user"); } @Test @@ -220,46 +220,50 @@ public class UpdateActionTest { createUser(); userSession.logIn("polop"); - expectedException.expect(ForbiddenException.class); - - ws.newRequest() - .setParam("login", "john") - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam("login", "john") + .execute(); + }) + .isInstanceOf(ForbiddenException.class); } @Test public void fail_on_unknown_user() { - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("User 'john' doesn't exist"); - - ws.newRequest() - .setParam("login", "john") - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam("login", "john") + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("User 'john' doesn't exist"); } @Test public void fail_on_disabled_user() { db.users().insertUser(u -> u.setLogin("john").setActive(false)); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("User 'john' doesn't exist"); - - ws.newRequest() - .setParam("login", "john") - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam("login", "john") + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("User 'john' doesn't exist"); } @Test public void fail_on_invalid_email() { createUser(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Email 'invalid-email' is not valid"); - - ws.newRequest() - .setParam("login", "john") - .setParam("email", "invalid-email") - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam("login", "john") + .setParam("email", "invalid-email") + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Email 'invalid-email' is not valid"); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/UpdateLoginActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/UpdateLoginActionTest.java index 7055fe9e3e8..5e54912f003 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/UpdateLoginActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/user/ws/UpdateLoginActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.user.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.api.server.ws.WebService.Param; import org.sonar.api.utils.System2; @@ -39,6 +38,7 @@ import org.sonar.server.ws.WsActionTester; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.Mockito.mock; @@ -52,8 +52,6 @@ public class UpdateLoginActionTest { public EsTester es = EsTester.create(); @Rule public UserSessionRule userSession = UserSessionRule.standalone().logIn().setSystemAdministrator(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private final WsActionTester ws = new WsActionTester(new UpdateLoginAction(db.getDbClient(), userSession, new UserUpdater(mock(NewUserNotifier.class), db.getDbClient(), new UserIndexer(db.getDbClient(), es.client()), null, null, null, null))); @@ -140,13 +138,14 @@ public class UpdateLoginActionTest { UserDto user = db.users().insertUser(); UserDto user2 = db.users().insertUser(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(format("A user with login '%s' already exists", user2.getLogin())); - - ws.newRequest() - .setParam("login", user.getLogin()) - .setParam("newLogin", user2.getLogin()) - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam("login", user.getLogin()) + .setParam("newLogin", user2.getLogin()) + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage(format("A user with login '%s' already exists", user2.getLogin())); } @Test @@ -154,38 +153,41 @@ public class UpdateLoginActionTest { userSession.logIn().setSystemAdministrator(); UserDto user = db.users().insertDisabledUser(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage(format("User '%s' doesn't exist", user.getLogin())); - - ws.newRequest() - .setParam("login", user.getLogin()) - .setParam("newLogin", "new_login") - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam("login", user.getLogin()) + .setParam("newLogin", "new_login") + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage(format("User '%s' doesn't exist", user.getLogin())); } @Test public void fail_with_NFE_when_login_does_not_match_existing_user() { userSession.logIn().setSystemAdministrator(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("User 'unknown' doesn't exist"); - - ws.newRequest() - .setParam("login", "unknown") - .setParam("newLogin", "new_login") - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam("login", "unknown") + .setParam("newLogin", "new_login") + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("User 'unknown' doesn't exist"); } @Test public void fail_when_not_system_administrator() { userSession.logIn(); - expectedException.expect(ForbiddenException.class); - - ws.newRequest() - .setParam("login", "old_login") - .setParam("newLogin", "new_login") - .execute(); + assertThatThrownBy(() -> { + ws.newRequest() + .setParam("login", "old_login") + .setParam("newLogin", "new_login") + .execute(); + }) + .isInstanceOf(ForbiddenException.class); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usergroups/ws/AddUserActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usergroups/ws/AddUserActionTest.java index dadea09e540..9a3953e29fc 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usergroups/ws/AddUserActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usergroups/ws/AddUserActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.usergroups.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.impl.utils.AlwaysIncreasingSystem2; import org.sonar.api.server.ws.Change; import org.sonar.api.server.ws.WebService.Action; @@ -38,6 +37,7 @@ import org.sonar.server.ws.WsActionTester; import static java.net.HttpURLConnection.HTTP_NO_CONTENT; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.db.permission.GlobalPermission.ADMINISTER; import static org.sonar.server.usergroups.ws.GroupWsSupport.PARAM_GROUP_NAME; @@ -49,8 +49,6 @@ public class AddUserActionTest { public DbTester db = DbTester.create(new AlwaysIncreasingSystem2()); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private final WsActionTester ws = new WsActionTester(new AddUserAction(db.getDbClient(), userSession, newGroupWsSupport())); @@ -167,13 +165,14 @@ public class AddUserActionTest { UserDto user = db.users().insertUser(); loginAsAdmin(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("No group with id '42'"); - - newRequest() - .setParam("id", "42") - .setParam("login", user.getLogin()) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam("id", "42") + .setParam("login", user.getLogin()) + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("No group with id '42'"); } @Test @@ -181,13 +180,14 @@ public class AddUserActionTest { GroupDto group = db.users().insertGroup("admins"); loginAsAdmin(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Could not find a user with login 'my-admin'"); - - newRequest() - .setParam("id", group.getUuid()) - .setParam("login", "my-admin") - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam("id", group.getUuid()) + .setParam("login", "my-admin") + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("Could not find a user with login 'my-admin'"); } @Test @@ -195,9 +195,10 @@ public class AddUserActionTest { GroupDto group = db.users().insertGroup(); UserDto user = db.users().insertUser(); - expectedException.expect(UnauthorizedException.class); - - executeRequest(group, user); + assertThatThrownBy(() -> { + executeRequest(group, user); + }) + .isInstanceOf(UnauthorizedException.class); } @Test @@ -206,13 +207,14 @@ public class AddUserActionTest { GroupDto defaultGroup = db.users().insertDefaultGroup(); loginAsAdmin(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Default group 'sonar-users' cannot be used to perform this action"); - - newRequest() - .setParam("id", defaultGroup.getUuid()) - .setParam(PARAM_LOGIN, user.getLogin()) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam("id", defaultGroup.getUuid()) + .setParam(PARAM_LOGIN, user.getLogin()) + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Default group 'sonar-users' cannot be used to perform this action"); } @Test @@ -221,13 +223,14 @@ public class AddUserActionTest { UserDto user = db.users().insertUser(); loginAsAdmin(); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Default group cannot be found"); - - newRequest() - .setParam(PARAM_LOGIN, user.getLogin()) - .setParam(PARAM_GROUP_NAME, group.getName()) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_LOGIN, user.getLogin()) + .setParam(PARAM_GROUP_NAME, group.getName()) + .execute(); + }) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Default group cannot be found"); } private void executeRequest(GroupDto groupDto, UserDto userDto) { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usergroups/ws/CreateActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usergroups/ws/CreateActionTest.java index 5950e3a45d0..388f5c4d78c 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usergroups/ws/CreateActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usergroups/ws/CreateActionTest.java @@ -22,7 +22,6 @@ package org.sonar.server.usergroups.ws; import org.apache.commons.lang.StringUtils; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.Change; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; @@ -36,6 +35,7 @@ import org.sonar.server.usergroups.DefaultGroupFinder; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.db.permission.GlobalPermission.ADMINISTER; @@ -44,8 +44,6 @@ public class CreateActionTest { public DbTester db = DbTester.create(System2.INSTANCE); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private final CreateAction underTest = new CreateAction(db.getDbClient(), userSession, newGroupWsSupport(), new SequenceUuidFactory()); private final WsActionTester tester = new WsActionTester(underTest); @@ -103,36 +101,49 @@ public class CreateActionTest { public void fail_if_not_administrator() { userSession.logIn("not-admin"); - expectedException.expect(ForbiddenException.class); - - tester.newRequest() - .setParam("name", "some-product-bu") - .setParam("description", "Business Unit for Some Awesome Product") - .execute(); + assertThatThrownBy(() -> { + tester.newRequest() + .setParam("name", "some-product-bu") + .setParam("description", "Business Unit for Some Awesome Product") + .execute(); + }) + .isInstanceOf(ForbiddenException.class); } - @Test(expected = IllegalArgumentException.class) + @Test public void fail_if_name_is_too_short() { loginAsAdmin(); - tester.newRequest() - .setParam("name", "") - .execute(); + + assertThatThrownBy(() -> { + tester.newRequest() + .setParam("name", "") + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class); } - @Test(expected = IllegalArgumentException.class) + @Test public void fail_if_name_is_too_long() { loginAsAdmin(); - tester.newRequest() - .setParam("name", StringUtils.repeat("a", 255 + 1)) - .execute(); + + assertThatThrownBy(() -> { + tester.newRequest() + .setParam("name", StringUtils.repeat("a", 255 + 1)) + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class); } - @Test(expected = IllegalArgumentException.class) + @Test public void fail_if_name_is_anyone() { loginAsAdmin(); - tester.newRequest() - .setParam("name", "AnYoNe") - .execute(); + + assertThatThrownBy(() -> { + tester.newRequest() + .setParam("name", "AnYoNe") + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class); } @Test @@ -140,21 +151,26 @@ public class CreateActionTest { GroupDto group = db.users().insertGroup(); loginAsAdmin(); - expectedException.expect(ServerException.class); - expectedException.expectMessage("Group '" + group.getName() + "' already exists"); - - tester.newRequest() - .setParam("name", group.getName()) - .execute(); + assertThatThrownBy(() -> { + tester.newRequest() + .setParam("name", group.getName()) + .execute(); + }) + .isInstanceOf(ServerException.class) + .hasMessage("Group '" + group.getName() + "' already exists"); } - @Test(expected = IllegalArgumentException.class) + @Test public void fail_if_description_is_too_long() { loginAsAdmin(); - tester.newRequest() - .setParam("name", "long-desc") - .setParam("description", StringUtils.repeat("a", 1_000)) - .execute(); + + assertThatThrownBy(() -> { + tester.newRequest() + .setParam("name", "long-desc") + .setParam("description", StringUtils.repeat("a", 1_000)) + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class); } private void loginAsAdmin() { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usergroups/ws/DeleteActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usergroups/ws/DeleteActionTest.java index 77ef3b3f027..86c2e44101b 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usergroups/ws/DeleteActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usergroups/ws/DeleteActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.usergroups.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.impl.utils.AlwaysIncreasingSystem2; import org.sonar.api.server.ws.Change; import org.sonar.api.server.ws.WebService.Action; @@ -29,7 +28,6 @@ import org.sonar.api.web.UserRole; import org.sonar.db.DbTester; import org.sonar.db.component.ComponentDbTester; import org.sonar.db.component.ComponentDto; -import org.sonar.db.component.ComponentTesting; import org.sonar.db.permission.template.PermissionTemplateDto; import org.sonar.db.permission.template.PermissionTemplateTesting; import org.sonar.db.qualitygate.QualityGateDto; @@ -44,6 +42,7 @@ import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.core.permission.GlobalPermissions.SYSTEM_ADMIN; import static org.sonar.db.permission.GlobalPermission.ADMINISTER; @@ -55,8 +54,6 @@ public class DeleteActionTest { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Rule public DbTester db = DbTester.create(new AlwaysIncreasingSystem2()); private final ComponentDbTester componentTester = new ComponentDbTester(db); @@ -205,12 +202,13 @@ public class DeleteActionTest { loginAsAdmin(); int groupId = 123; - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("No group with id '" + groupId + "'"); - - newRequest() - .setParam("id", String.valueOf(groupId)) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam("id", String.valueOf(groupId)) + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("No group with id '" + groupId + "'"); } @Test @@ -218,12 +216,13 @@ public class DeleteActionTest { loginAsAdmin(); GroupDto defaultGroup = db.users().insertDefaultGroup(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Default group 'sonar-users' cannot be used to perform this action"); - - newRequest() - .setParam("id", defaultGroup.getUuid()) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam("id", defaultGroup.getUuid()) + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Default group 'sonar-users' cannot be used to perform this action"); } @Test @@ -233,12 +232,13 @@ public class DeleteActionTest { db.users().insertPermissionOnGroup(group, SYSTEM_ADMIN); loginAsAdmin(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The last system admin group cannot be deleted"); - - newRequest() - .setParam(PARAM_GROUP_NAME, group.getName()) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam(PARAM_GROUP_NAME, group.getName()) + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("The last system admin group cannot be deleted"); } @Test @@ -251,10 +251,11 @@ public class DeleteActionTest { db.users().insertMember(adminGroup, bigBoss); loginAsAdmin(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The last system admin group cannot be deleted"); - - executeDeleteGroupRequest(adminGroup); + assertThatThrownBy(() -> { + executeDeleteGroupRequest(adminGroup); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("The last system admin group cannot be deleted"); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usergroups/ws/GroupWsRefTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usergroups/ws/GroupWsRefTest.java index 81a692a6dcc..4eb1322379f 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usergroups/ws/GroupWsRefTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usergroups/ws/GroupWsRefTest.java @@ -19,17 +19,13 @@ */ package org.sonar.server.usergroups.ws; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.server.usergroups.ws.GroupWsRef.fromName; public class GroupWsRefTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void test_ref_by_id() { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usergroups/ws/RemoveUserActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usergroups/ws/RemoveUserActionTest.java index fcbfd866a9d..bca61fa8028 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usergroups/ws/RemoveUserActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usergroups/ws/RemoveUserActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.usergroups.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.impl.utils.AlwaysIncreasingSystem2; import org.sonar.api.server.ws.Change; import org.sonar.api.server.ws.WebService.Action; @@ -40,6 +39,7 @@ import org.sonar.server.ws.WsActionTester; import static java.net.HttpURLConnection.HTTP_NO_CONTENT; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.db.permission.GlobalPermission.ADMINISTER; import static org.sonar.server.usergroups.ws.GroupWsSupport.PARAM_GROUP_NAME; @@ -51,8 +51,6 @@ public class RemoveUserActionTest { public DbTester db = DbTester.create(new AlwaysIncreasingSystem2()); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private final WsActionTester ws = new WsActionTester( new RemoveUserAction(db.getDbClient(), userSession, new GroupWsSupport(db.getDbClient(), new DefaultGroupFinder(db.getDbClient())))); @@ -164,13 +162,14 @@ public class RemoveUserActionTest { public void fail_if_unknown_group() { UserDto user = db.users().insertUser("my-admin"); - expectedException.expect(NotFoundException.class); - - loginAsAdmin(); - newRequest() - .setParam("id", "42") - .setParam("login", user.getLogin()) - .execute(); + assertThatThrownBy(() -> { + loginAsAdmin(); + newRequest() + .setParam("id", "42") + .setParam("login", user.getLogin()) + .execute(); + }) + .isInstanceOf(NotFoundException.class); } @Test @@ -178,13 +177,14 @@ public class RemoveUserActionTest { insertDefaultGroup(); GroupDto group = db.users().insertGroup("admins"); - expectedException.expect(NotFoundException.class); - - loginAsAdmin(); - newRequest() - .setParam("id", group.getUuid()) - .setParam("login", "my-admin") - .execute(); + assertThatThrownBy(() -> { + loginAsAdmin(); + newRequest() + .setParam("id", group.getUuid()) + .setParam("login", "my-admin") + .execute(); + }) + .isInstanceOf(NotFoundException.class); } @Test @@ -194,13 +194,14 @@ public class RemoveUserActionTest { db.users().insertMember(group, user); userSession.logIn("admin"); - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - - newRequest() - .setParam("id", group.getUuid()) - .setParam("login", user.getLogin()) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam("id", group.getUuid()) + .setParam("login", user.getLogin()) + .execute(); + }) + .isInstanceOf(ForbiddenException.class) + .hasMessage("Insufficient privileges"); } @Test @@ -212,13 +213,14 @@ public class RemoveUserActionTest { db.users().insertMember(adminGroup, adminUser); loginAsAdmin(); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("The last administrator user cannot be removed"); - - newRequest() - .setParam("id", adminGroup.getUuid()) - .setParam("login", adminUser.getLogin()) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam("id", adminGroup.getUuid()) + .setParam("login", adminUser.getLogin()) + .execute(); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("The last administrator user cannot be removed"); } @Test @@ -228,13 +230,14 @@ public class RemoveUserActionTest { db.users().insertMember(defaultGroup, user); loginAsAdmin(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Default group 'sonar-users' cannot be used to perform this action"); - - newRequest() - .setParam("id", defaultGroup.getUuid()) - .setParam(PARAM_LOGIN, user.getLogin()) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam("id", defaultGroup.getUuid()) + .setParam(PARAM_LOGIN, user.getLogin()) + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Default group 'sonar-users' cannot be used to perform this action"); } private TestRequest newRequest() { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usergroups/ws/SearchActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usergroups/ws/SearchActionTest.java index 31d706ed951..dc276194da3 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usergroups/ws/SearchActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usergroups/ws/SearchActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.usergroups.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.Change; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; @@ -38,6 +37,7 @@ import org.sonarqube.ws.MediaTypes; import static org.apache.commons.lang.StringUtils.capitalize; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.api.server.ws.WebService.Param.FIELDS; import static org.sonar.api.server.ws.WebService.Param.PAGE; @@ -57,8 +57,6 @@ public class SearchActionTest { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private final WsActionTester ws = new WsActionTester(new SearchAction(db.getDbClient(), userSession, new DefaultGroupFinder(db.getDbClient()))); @@ -189,8 +187,10 @@ public class SearchActionTest { public void fail_when_not_logged_in() { userSession.anonymous(); - expectedException.expect(UnauthorizedException.class); - call(ws.newRequest()); + assertThatThrownBy(() -> { + call(ws.newRequest()); + }) + .isInstanceOf(UnauthorizedException.class); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usergroups/ws/UpdateActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usergroups/ws/UpdateActionTest.java index 6ff21315b93..b1e1bf377c7 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usergroups/ws/UpdateActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usergroups/ws/UpdateActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.usergroups.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.Change; import org.sonar.api.server.ws.WebService.Action; import org.sonar.api.utils.System2; @@ -37,6 +36,7 @@ import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.db.permission.GlobalPermission.ADMINISTER; import static org.sonar.test.JsonAssert.assertJson; @@ -46,8 +46,6 @@ public class UpdateActionTest { public DbTester db = DbTester.create(System2.INSTANCE); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private final WsActionTester ws = new WsActionTester( new UpdateAction(db.getDbClient(), userSession, new GroupWsSupport(db.getDbClient(), new DefaultGroupFinder(db.getDbClient())))); @@ -172,13 +170,14 @@ public class UpdateActionTest { GroupDto group = db.users().insertGroup(); userSession.logIn("not-admin"); - expectedException.expect(ForbiddenException.class); - - newRequest() - .setParam("id", group.getUuid()) - .setParam("name", "some-product-bu") - .setParam("description", "Business Unit for Some Awesome Product") - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam("id", group.getUuid()) + .setParam("name", "some-product-bu") + .setParam("description", "Business Unit for Some Awesome Product") + .execute(); + }) + .isInstanceOf(ForbiddenException.class); } @Test @@ -187,38 +186,41 @@ public class UpdateActionTest { GroupDto group = db.users().insertGroup(); loginAsAdmin(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Group name cannot be empty"); - - newRequest() - .setParam("id", group.getUuid()) - .setParam("name", "") - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam("id", group.getUuid()) + .setParam("name", "") + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Group name cannot be empty"); } @Test public void fail_if_no_id_and_no_currentname_are_provided() { insertDefaultGroup(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Need to specify one and only one of 'id' or 'currentName'"); - - newRequest() - .setParam("name", "newname") - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam("name", "newname") + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Need to specify one and only one of 'id' or 'currentName'"); } @Test public void fail_if_both_id_and_currentname_are_provided() { insertDefaultGroup(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Need to specify one and only one of 'id' or 'currentName'"); - - newRequest() - .setParam("id", "id") - .setParam("currentName", "name") - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam("id", "id") + .setParam("currentName", "name") + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Need to specify one and only one of 'id' or 'currentName'"); } @Test @@ -227,13 +229,14 @@ public class UpdateActionTest { GroupDto group = db.users().insertGroup(); loginAsAdmin(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Anyone group cannot be used"); - - newRequest() - .setParam("id", group.getUuid()) - .setParam("name", "AnYoNe") - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam("id", group.getUuid()) + .setParam("name", "AnYoNe") + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Anyone group cannot be used"); } @Test @@ -244,37 +247,40 @@ public class UpdateActionTest { db.users().insertGroup(newName); loginAsAdmin(); - expectedException.expect(ServerException.class); - expectedException.expectMessage("Group 'new-name' already exists"); - - newRequest() - .setParam("id", groupToBeRenamed.getUuid()) - .setParam("name", newName) - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam("id", groupToBeRenamed.getUuid()) + .setParam("name", newName) + .execute(); + }) + .isInstanceOf(ServerException.class) + .hasMessage("Group 'new-name' already exists"); } @Test public void fail_if_unknown_group_id() { loginAsAdmin(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Could not find a user group with id '42'."); - - newRequest() - .setParam("id", "42") - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam("id", "42") + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("Could not find a user group with id '42'."); } @Test public void fail_if_unknown_group_name() { loginAsAdmin(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("Could not find a user group with name '42'."); - - newRequest() - .setParam("currentName", "42") - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam("currentName", "42") + .execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("Could not find a user group with name '42'."); } @Test @@ -282,13 +288,14 @@ public class UpdateActionTest { GroupDto group = db.users().insertDefaultGroup(); loginAsAdmin(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Default group 'sonar-users' cannot be used to perform this action"); - - newRequest() - .setParam("id", group.getUuid()) - .setParam("name", "new name") - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam("id", group.getUuid()) + .setParam("name", "new name") + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Default group 'sonar-users' cannot be used to perform this action"); } @Test @@ -296,13 +303,14 @@ public class UpdateActionTest { GroupDto group = db.users().insertDefaultGroup(); loginAsAdmin(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Default group 'sonar-users' cannot be used to perform this action"); - - newRequest() - .setParam("id", group.getUuid()) - .setParam("description", "new description") - .execute(); + assertThatThrownBy(() -> { + newRequest() + .setParam("id", group.getUuid()) + .setParam("description", "new description") + .execute(); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Default group 'sonar-users' cannot be used to perform this action"); } private TestRequest newRequest() { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usergroups/ws/UsersActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usergroups/ws/UsersActionTest.java index e1c9f97287b..4e08a9d288f 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usergroups/ws/UsersActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usergroups/ws/UsersActionTest.java @@ -21,7 +21,6 @@ package org.sonar.server.usergroups.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.Change; import org.sonar.api.server.ws.WebService.Action; import org.sonar.api.server.ws.WebService.Param; @@ -38,6 +37,7 @@ import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.db.permission.GlobalPermission.ADMINISTER; import static org.sonar.db.user.UserTesting.newUserDto; @@ -46,8 +46,6 @@ import static org.sonar.test.JsonAssert.assertJson; public class UsersActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public DbTester db = DbTester.create(System2.INSTANCE); @Rule @@ -70,12 +68,13 @@ public class UsersActionTest { public void fail_if_unknown_group_uuid() { loginAsAdmin(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("No group with id '42'"); - - newUsersRequest() - .setParam("id", "42") - .setParam("login", "john").execute(); + assertThatThrownBy(() -> { + newUsersRequest() + .setParam("id", "42") + .setParam("login", "john").execute(); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("No group with id '42'"); } @Test @@ -83,11 +82,12 @@ public class UsersActionTest { GroupDto group = db.users().insertGroup(); userSession.logIn("not-admin"); - expectedException.expect(ForbiddenException.class); - - newUsersRequest() - .setParam("id", group.getUuid()) - .setParam("login", "john").execute(); + assertThatThrownBy(() -> { + newUsersRequest() + .setParam("id", group.getUuid()) + .setParam("login", "john").execute(); + }) + .isInstanceOf(ForbiddenException.class); } @Test diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usertoken/ws/GenerateActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usertoken/ws/GenerateActionTest.java index 0519e961f60..db5da4ea651 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usertoken/ws/GenerateActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usertoken/ws/GenerateActionTest.java @@ -23,7 +23,6 @@ import javax.annotation.Nullable; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.db.DbTester; @@ -41,6 +40,7 @@ import org.sonarqube.ws.MediaTypes; import org.sonarqube.ws.UserTokens.GenerateWsResponse; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -56,8 +56,6 @@ public class GenerateActionTest { public DbTester db = DbTester.create(System2.INSTANCE); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private TokenGenerator tokenGenerator = mock(TokenGenerator.class); @@ -112,10 +110,11 @@ public class GenerateActionTest { public void fail_if_login_does_not_exist() { logInAsSystemAdministrator(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("User with login 'unknown-login' doesn't exist"); - - newRequest("unknown-login", "any-name"); + assertThatThrownBy(() -> { + newRequest("unknown-login", "any-name"); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("User with login 'unknown-login' doesn't exist"); } @Test @@ -123,10 +122,11 @@ public class GenerateActionTest { UserDto user = db.users().insertUser(); logInAsSystemAdministrator(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The 'name' parameter is missing"); - - newRequest(user.getLogin(), " "); + assertThatThrownBy(() -> { + newRequest(user.getLogin(), " "); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("The 'name' parameter is missing"); } @Test @@ -135,10 +135,11 @@ public class GenerateActionTest { logInAsSystemAdministrator(); db.users().insertToken(user, t -> t.setName(TOKEN_NAME)); - expectedException.expect(BadRequestException.class); - expectedException.expectMessage(String.format("A user token for login '%s' and name 'Third Party Application' already exists", user.getLogin())); - - newRequest(user.getLogin(), TOKEN_NAME); + assertThatThrownBy(() -> { + newRequest(user.getLogin(), TOKEN_NAME); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage(String.format("A user token for login '%s' and name 'Third Party Application' already exists", user.getLogin())); } @Test @@ -148,10 +149,11 @@ public class GenerateActionTest { when(tokenGenerator.hash(anyString())).thenReturn("987654321"); db.users().insertToken(user, t -> t.setTokenHash("987654321")); - expectedException.expect(ServerException.class); - expectedException.expectMessage("Error while generating token. Please try again."); - - newRequest(user.getLogin(), TOKEN_NAME); + assertThatThrownBy(() -> { + newRequest(user.getLogin(), TOKEN_NAME); + }) + .isInstanceOf(ServerException.class) + .hasMessage("Error while generating token. Please try again."); } @Test @@ -159,9 +161,10 @@ public class GenerateActionTest { UserDto user = db.users().insertUser(); userSession.logIn().setNonSystemAdministrator(); - expectedException.expect(ForbiddenException.class); - - newRequest(user.getLogin(), TOKEN_NAME); + assertThatThrownBy(() -> { + newRequest(user.getLogin(), TOKEN_NAME); + }) + .isInstanceOf(ForbiddenException.class); } @Test @@ -169,9 +172,10 @@ public class GenerateActionTest { UserDto user = db.users().insertUser(); userSession.anonymous(); - expectedException.expect(UnauthorizedException.class); - - newRequest(user.getLogin(), TOKEN_NAME); + assertThatThrownBy(() -> { + newRequest(user.getLogin(), TOKEN_NAME); + }) + .isInstanceOf(UnauthorizedException.class); } private GenerateWsResponse newRequest(@Nullable String login, String name) { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usertoken/ws/RevokeActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usertoken/ws/RevokeActionTest.java index 59a4dacc017..a527b9e1e9f 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usertoken/ws/RevokeActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usertoken/ws/RevokeActionTest.java @@ -22,7 +22,6 @@ package org.sonar.server.usertoken.ws; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.db.DbClient; @@ -38,6 +37,7 @@ import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.server.usertoken.ws.UserTokenSupport.PARAM_LOGIN; import static org.sonar.server.usertoken.ws.UserTokenSupport.PARAM_NAME; @@ -47,8 +47,6 @@ public class RevokeActionTest { public DbTester db = DbTester.create(System2.INSTANCE); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); private DbClient dbClient = db.getDbClient(); private DbSession dbSession = db.getSession(); @@ -115,9 +113,10 @@ public class RevokeActionTest { UserTokenDto token = db.users().insertToken(user); userSession.logIn(); - expectedException.expect(ForbiddenException.class); - - newRequest(user.getLogin(), token.getName()); + assertThatThrownBy(() -> { + newRequest(user.getLogin(), token.getName()); + }) + .isInstanceOf(ForbiddenException.class); } @Test @@ -126,19 +125,21 @@ public class RevokeActionTest { UserTokenDto token = db.users().insertToken(user); userSession.anonymous(); - expectedException.expect(UnauthorizedException.class); - - newRequest(user.getLogin(), token.getName()); + assertThatThrownBy(() -> { + newRequest(user.getLogin(), token.getName()); + }) + .isInstanceOf(UnauthorizedException.class); } @Test public void fail_if_login_does_not_exist() { logInAsSystemAdministrator(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("User with login 'unknown-login' doesn't exist"); - - newRequest("unknown-login", "any-name"); + assertThatThrownBy(() -> { + newRequest("unknown-login", "any-name"); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("User with login 'unknown-login' doesn't exist"); } private String newRequest(@Nullable String login, String name) { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usertoken/ws/SearchActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usertoken/ws/SearchActionTest.java index 98da7f5ea21..50989852db3 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usertoken/ws/SearchActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/usertoken/ws/SearchActionTest.java @@ -22,7 +22,6 @@ package org.sonar.server.usertoken.ws; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.db.DbClient; @@ -39,6 +38,7 @@ import org.sonarqube.ws.UserTokens.SearchWsResponse; import org.sonarqube.ws.UserTokens.SearchWsResponse.UserToken; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.api.utils.DateUtils.formatDateTime; import static org.sonar.server.usertoken.ws.UserTokenSupport.PARAM_LOGIN; @@ -46,8 +46,6 @@ import static org.sonar.test.JsonAssert.assertJson; public class SearchActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule @@ -117,10 +115,11 @@ public class SearchActionTest { public void fail_when_login_does_not_exist() { logInAsSystemAdministrator(); - expectedException.expect(NotFoundException.class); - expectedException.expectMessage("User with login 'unknown-login' doesn't exist"); - - newRequest("unknown-login"); + assertThatThrownBy(() -> { + newRequest("unknown-login"); + }) + .isInstanceOf(NotFoundException.class) + .hasMessage("User with login 'unknown-login' doesn't exist"); } @Test @@ -128,9 +127,10 @@ public class SearchActionTest { UserDto user = db.users().insertUser(); userSession.logIn(); - expectedException.expect(ForbiddenException.class); - - newRequest(user.getLogin()); + assertThatThrownBy(() -> { + newRequest(user.getLogin()); + }) + .isInstanceOf(ForbiddenException.class); } @Test @@ -138,9 +138,10 @@ public class SearchActionTest { UserDto user = db.users().insertUser(); userSession.anonymous(); - expectedException.expect(UnauthorizedException.class); - - newRequest(user.getLogin()); + assertThatThrownBy(() -> { + newRequest(user.getLogin()); + }) + .isInstanceOf(UnauthorizedException.class); } private SearchWsResponse newRequest(@Nullable String login) { diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/webhook/ws/WebhookDeliveryActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/webhook/ws/WebhookDeliveryActionTest.java index 6643c0dfd20..4737c266212 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/webhook/ws/WebhookDeliveryActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/webhook/ws/WebhookDeliveryActionTest.java @@ -22,15 +22,12 @@ package org.sonar.server.webhook.ws; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.api.web.UserRole; import org.sonar.db.DbClient; import org.sonar.db.DbTester; import org.sonar.db.component.ComponentDto; -import org.sonar.db.component.ComponentTesting; -import org.sonar.db.project.ProjectDto; import org.sonar.db.webhook.WebhookDeliveryDto; import org.sonar.server.component.ComponentFinder; import org.sonar.server.component.TestComponentFinder; @@ -43,14 +40,12 @@ import org.sonarqube.ws.MediaTypes; import org.sonarqube.ws.Webhooks; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.db.webhook.WebhookDeliveryTesting.newDto; import static org.sonar.test.JsonAssert.assertJson; public class WebhookDeliveryActionTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @@ -82,21 +77,19 @@ public class WebhookDeliveryActionTest { @Test public void throw_UnauthorizedException_if_anonymous() { - expectedException.expect(UnauthorizedException.class); - - ws.newRequest().execute(); + assertThatThrownBy(() -> ws.newRequest().execute()) + .isInstanceOf(UnauthorizedException.class); } @Test public void return_404_if_delivery_does_not_exist() { userSession.logIn(); - expectedException.expect(NotFoundException.class); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() .setMediaType(MediaTypes.PROTOBUF) .setParam("deliveryId", "does_not_exist") - .execute(); + .execute()) + .isInstanceOf(NotFoundException.class); } @Test @@ -174,11 +167,11 @@ public class WebhookDeliveryActionTest { db.commit(); userSession.logIn().addProjectPermission(UserRole.USER, project); - expectedException.expect(ForbiddenException.class); - expectedException.expectMessage("Insufficient privileges"); - - ws.newRequest() + assertThatThrownBy(() -> ws.newRequest() + .setMediaType(MediaTypes.PROTOBUF) .setParam("deliveryId", dto.getUuid()) - .execute(); + .execute()) + .isInstanceOf(ForbiddenException.class) + .hasMessageContaining("Insufficient privileges"); } } diff --git a/server/sonar-webserver-ws/src/test/java/org/sonar/server/ws/RemovedWebServiceHandlerTest.java b/server/sonar-webserver-ws/src/test/java/org/sonar/server/ws/RemovedWebServiceHandlerTest.java index e3add2a9306..9236b8d4087 100644 --- a/server/sonar-webserver-ws/src/test/java/org/sonar/server/ws/RemovedWebServiceHandlerTest.java +++ b/server/sonar-webserver-ws/src/test/java/org/sonar/server/ws/RemovedWebServiceHandlerTest.java @@ -19,9 +19,7 @@ */ package org.sonar.server.ws; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.Request; import org.sonar.server.exceptions.ServerException; @@ -32,8 +30,6 @@ import static org.mockito.Mockito.when; public class RemovedWebServiceHandlerTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Test public void throw_server_exception() { diff --git a/server/sonar-webserver-ws/src/test/java/org/sonar/server/ws/ServletRequestTest.java b/server/sonar-webserver-ws/src/test/java/org/sonar/server/ws/ServletRequestTest.java index 3938c553173..496bbd13bcc 100644 --- a/server/sonar-webserver-ws/src/test/java/org/sonar/server/ws/ServletRequestTest.java +++ b/server/sonar-webserver-ws/src/test/java/org/sonar/server/ws/ServletRequestTest.java @@ -28,9 +28,7 @@ import java.io.StringReader; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.Part; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonarqube.ws.MediaTypes; import static org.assertj.core.api.Assertions.assertThat; @@ -41,8 +39,6 @@ import static org.mockito.Mockito.when; public class ServletRequestTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private HttpServletRequest source = mock(HttpServletRequest.class); diff --git a/server/sonar-webserver-ws/src/test/java/org/sonar/server/ws/ServletResponseTest.java b/server/sonar-webserver-ws/src/test/java/org/sonar/server/ws/ServletResponseTest.java index 41c751e0de9..502ce2c7f14 100644 --- a/server/sonar-webserver-ws/src/test/java/org/sonar/server/ws/ServletResponseTest.java +++ b/server/sonar-webserver-ws/src/test/java/org/sonar/server/ws/ServletResponseTest.java @@ -22,9 +22,7 @@ package org.sonar.server.ws; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; @@ -36,8 +34,6 @@ import static org.sonarqube.ws.MediaTypes.XML; public class ServletResponseTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private ServletOutputStream output = mock(ServletOutputStream.class); private HttpServletResponse response = mock(HttpServletResponse.class); diff --git a/server/sonar-webserver-ws/src/test/java/org/sonar/server/ws/WsUtilsTest.java b/server/sonar-webserver-ws/src/test/java/org/sonar/server/ws/WsUtilsTest.java index 85eb1038af7..18b5d723721 100644 --- a/server/sonar-webserver-ws/src/test/java/org/sonar/server/ws/WsUtilsTest.java +++ b/server/sonar-webserver-ws/src/test/java/org/sonar/server/ws/WsUtilsTest.java @@ -21,7 +21,6 @@ package org.sonar.server.ws; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.utils.log.LogTester; import org.sonar.server.exceptions.BadRequestException; import org.sonarqube.ws.Issues; @@ -29,13 +28,10 @@ import org.sonarqube.ws.MediaTypes; import org.sonarqube.ws.Permissions; import static org.assertj.core.api.Assertions.assertThat; -import static org.sonar.test.ExceptionCauseMatcher.hasType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class WsUtilsTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Rule public LogTester logger = new LogTester(); @@ -74,11 +70,11 @@ public class WsUtilsTest { Permissions.Permission message = Permissions.Permission.newBuilder().setName("permission-name").build(); - expectedException.expect(IllegalStateException.class); - expectedException.expectCause(hasType(NullPointerException.class)); - expectedException.expectMessage("Error while writing protobuf message"); // provoke NullPointerException - WsUtils.writeProtobuf(message, null, new DumbResponse()); + assertThatThrownBy(() -> WsUtils.writeProtobuf(message, null, new DumbResponse())) + .isInstanceOf(IllegalStateException.class) + .hasCauseInstanceOf(NullPointerException.class) + .hasMessageContaining("Error while writing protobuf message"); } @Test @@ -89,10 +85,9 @@ public class WsUtilsTest { @Test public void checkRequest_ko() { - expectedException.expect(BadRequestException.class); - expectedException.expectMessage("Missing param: foo"); - - BadRequestException.checkRequest(false, "Missing param: %s", "foo"); + assertThatThrownBy(() -> BadRequestException.checkRequest(false, "Missing param: %s", "foo")) + .isInstanceOf(BadRequestException.class) + .hasMessageContaining("Missing param: foo"); } } diff --git a/server/sonar-webserver/src/test/java/org/sonar/server/app/StartupLogsTest.java b/server/sonar-webserver/src/test/java/org/sonar/server/app/StartupLogsTest.java index 84e1f2a52dd..53c446d4959 100644 --- a/server/sonar-webserver/src/test/java/org/sonar/server/app/StartupLogsTest.java +++ b/server/sonar-webserver/src/test/java/org/sonar/server/app/StartupLogsTest.java @@ -21,12 +21,11 @@ package org.sonar.server.app; import org.apache.catalina.connector.Connector; import org.apache.catalina.startup.Tomcat; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.Mockito; import org.sonar.api.utils.log.Logger; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -34,8 +33,6 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; public class StartupLogsTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private Tomcat tomcat = mock(Tomcat.class, Mockito.RETURNS_DEEP_STUBS); private Logger logger = mock(Logger.class); @@ -46,10 +43,9 @@ public class StartupLogsTest { Connector connector = newConnector("AJP/1.3", "ajp"); when(tomcat.getService().findConnectors()).thenReturn(new Connector[] {connector}); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Unsupported connector: Connector[AJP/1.3-1234]"); - - underTest.log(tomcat); + assertThatThrownBy(() -> underTest.log(tomcat)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Unsupported connector: Connector[AJP/1.3-1234]"); } @Test diff --git a/server/sonar-webserver/src/test/java/org/sonar/server/app/TomcatContextsTest.java b/server/sonar-webserver/src/test/java/org/sonar/server/app/TomcatContextsTest.java index 07255ec9c55..c0b90cf44e6 100644 --- a/server/sonar-webserver/src/test/java/org/sonar/server/app/TomcatContextsTest.java +++ b/server/sonar-webserver/src/test/java/org/sonar/server/app/TomcatContextsTest.java @@ -28,12 +28,12 @@ import org.apache.commons.io.FileUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.sonar.api.utils.MessageException; import org.sonar.process.Props; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doThrow; @@ -46,8 +46,6 @@ public class TomcatContextsTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); Tomcat tomcat = mock(Tomcat.class); @@ -97,13 +95,13 @@ public class TomcatContextsTest { @Test public void fail_if_static_directory_can_not_be_initialized() throws Exception { File dir = temp.newFolder(); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Fail to create or clean-up directory " + dir.getAbsolutePath()); TomcatContexts.Fs fs = mock(TomcatContexts.Fs.class); doThrow(new IOException()).when(fs).createOrCleanupDir(any(File.class)); - new TomcatContexts(fs).addStaticDir(tomcat, "/deploy", dir); + assertThatThrownBy(() -> new TomcatContexts(fs).addStaticDir(tomcat, "/deploy", dir)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Fail to create or clean-up directory " + dir.getAbsolutePath()); } @Test @@ -117,9 +115,9 @@ public class TomcatContextsTest { public void context_path_must_start_with_slash() { props.setProperty("sonar.web.context", "foo"); - expectedException.expect(MessageException.class); - expectedException.expectMessage("Value of 'sonar.web.context' must start with a forward slash: 'foo'"); - underTest.configure(tomcat, new Props(props)); + assertThatThrownBy(() -> underTest.configure(tomcat, new Props(props))) + .isInstanceOf(MessageException.class) + .hasMessageContaining("Value of 'sonar.web.context' must start with a forward slash: 'foo'"); } @Test diff --git a/server/sonar-webserver/src/test/java/org/sonar/server/platform/platformlevel/PlatformLevelTest.java b/server/sonar-webserver/src/test/java/org/sonar/server/platform/platformlevel/PlatformLevelTest.java index 00bacfe0481..be2cd9c0e11 100644 --- a/server/sonar-webserver/src/test/java/org/sonar/server/platform/platformlevel/PlatformLevelTest.java +++ b/server/sonar-webserver/src/test/java/org/sonar/server/platform/platformlevel/PlatformLevelTest.java @@ -21,17 +21,14 @@ package org.sonar.server.platform.platformlevel; import java.util.Random; import java.util.stream.IntStream; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.Mockito; import org.sonar.server.platform.WebServer; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class PlatformLevelTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private PlatformLevel underTest = new PlatformLevel("name") { @@ -43,10 +40,9 @@ public class PlatformLevelTest { @Test public void addIfStartupLeader_throws_ISE_if_container_does_not_have_WebServer_object() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("WebServer not available in Pico yet"); - - underTest.addIfStartupLeader(); + assertThatThrownBy(() -> underTest.addIfStartupLeader()) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("WebServer not available in Pico yet"); } @Test @@ -59,10 +55,9 @@ public class PlatformLevelTest { @Test public void addIfCluster_throws_ISE_if_container_does_not_have_WebServer_object() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("WebServer not available in Pico yet"); - - underTest.addIfCluster(); + assertThatThrownBy(() -> underTest.addIfCluster()) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("WebServer not available in Pico yet"); } @Test @@ -75,10 +70,9 @@ public class PlatformLevelTest { @Test public void addIfStandalone_throws_ISE_if_container_does_not_have_WebServer_object() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("WebServer not available in Pico yet"); - - underTest.addIfCluster(); + assertThatThrownBy(() -> underTest.addIfCluster()) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("WebServer not available in Pico yet"); } @Test diff --git a/server/sonar-webserver/src/test/java/org/sonar/server/platform/web/MasterServletFilterTest.java b/server/sonar-webserver/src/test/java/org/sonar/server/platform/web/MasterServletFilterTest.java index 99ce46255ac..9e1702ae063 100644 --- a/server/sonar-webserver/src/test/java/org/sonar/server/platform/web/MasterServletFilterTest.java +++ b/server/sonar-webserver/src/test/java/org/sonar/server/platform/web/MasterServletFilterTest.java @@ -31,7 +31,6 @@ import javax.servlet.http.HttpServletResponse; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.utils.log.LogTester; import org.sonar.api.utils.log.LoggerLevel; import org.sonar.api.web.ServletFilter; @@ -40,6 +39,7 @@ import org.sonar.api.web.ServletFilter.UrlPattern; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; @@ -48,8 +48,6 @@ import static org.mockito.Mockito.when; public class MasterServletFilterTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public LogTester logTester = new LogTester(); @@ -77,22 +75,22 @@ public class MasterServletFilterTest { public void servlet_container_should_instantiate_only_a_single_master_instance() { new MasterServletFilter(); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Servlet filter org.sonar.server.platform.web.MasterServletFilter is already instantiated"); - new MasterServletFilter(); + assertThatThrownBy(() -> new MasterServletFilter()) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Servlet filter org.sonar.server.platform.web.MasterServletFilter is already instantiated"); } @Test public void should_propagate_initialization_failure() throws Exception { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("foo"); - ServletFilter filter = createMockFilter(); doThrow(new IllegalStateException("foo")).when(filter).init(any(FilterConfig.class)); FilterConfig config = mock(FilterConfig.class); MasterServletFilter filters = new MasterServletFilter(); - filters.init(config, singletonList(filter)); + + assertThatThrownBy(() -> filters.init(config, singletonList(filter))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("foo"); } @Test diff --git a/server/sonar-webserver/src/test/java/org/sonar/server/platform/web/RootFilterTest.java b/server/sonar-webserver/src/test/java/org/sonar/server/platform/web/RootFilterTest.java index 4680073ff5a..d078ebe6980 100644 --- a/server/sonar-webserver/src/test/java/org/sonar/server/platform/web/RootFilterTest.java +++ b/server/sonar-webserver/src/test/java/org/sonar/server/platform/web/RootFilterTest.java @@ -30,12 +30,12 @@ import javax.servlet.http.HttpServletResponse; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; import org.sonar.api.utils.log.LogTester; import org.sonar.api.utils.log.LoggerLevel; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; @@ -45,8 +45,6 @@ import static org.mockito.Mockito.when; public class RootFilterTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Rule public LogTester logTester = new LogTester(); @@ -119,8 +117,9 @@ public class RootFilterTest { ArgumentCaptor requestArgumentCaptor = ArgumentCaptor.forClass(ServletRequest.class); verify(chain).doFilter(requestArgumentCaptor.capture(), any(ServletResponse.class)); - expectedException.expect(UnsupportedOperationException.class); - ((HttpServletRequest) requestArgumentCaptor.getValue()).getSession(); + + assertThatThrownBy(() -> ((HttpServletRequest) requestArgumentCaptor.getValue()).getSession()) + .isInstanceOf(UnsupportedOperationException.class); } @Test @@ -129,8 +128,8 @@ public class RootFilterTest { ArgumentCaptor requestArgumentCaptor = ArgumentCaptor.forClass(ServletRequest.class); verify(chain).doFilter(requestArgumentCaptor.capture(), any(ServletResponse.class)); - expectedException.expect(UnsupportedOperationException.class); - ((HttpServletRequest) requestArgumentCaptor.getValue()).getSession(true); + assertThatThrownBy(() -> ((HttpServletRequest) requestArgumentCaptor.getValue()).getSession(true)) + .isInstanceOf(UnsupportedOperationException.class); } private HttpServletRequest request(String method, String path, String query) { diff --git a/server/sonar-webserver/src/test/java/org/sonar/server/platform/web/WebPagesCacheTest.java b/server/sonar-webserver/src/test/java/org/sonar/server/platform/web/WebPagesCacheTest.java index 08b7e504400..dec8a8d4c8d 100644 --- a/server/sonar-webserver/src/test/java/org/sonar/server/platform/web/WebPagesCacheTest.java +++ b/server/sonar-webserver/src/test/java/org/sonar/server/platform/web/WebPagesCacheTest.java @@ -22,9 +22,7 @@ package org.sonar.server.platform.web; import java.io.InputStream; import javax.servlet.ServletContext; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.stubbing.Answer; import org.sonar.api.config.internal.MapSettings; import org.sonar.server.platform.OfficialDistribution; @@ -33,6 +31,7 @@ import org.sonar.server.platform.Platform; import static java.nio.charset.StandardCharsets.UTF_8; import static org.apache.commons.io.IOUtils.toInputStream; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.server.platform.Platform.Status.BOOTING; @@ -43,8 +42,6 @@ public class WebPagesCacheTest { private static final String TEST_CONTEXT = "/sonarqube"; - @Rule - public ExpectedException expectedException = ExpectedException.none(); private ServletContext servletContext = mock(ServletContext.class); @@ -151,10 +148,9 @@ public class WebPagesCacheTest { @Test public void fail_to_get_content_when_init_has_not_been_called() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("init has not been called"); - - underTest.getContent("/foo"); + assertThatThrownBy(() -> underTest.getContent("/foo")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("init has not been called"); } private void doInit() { diff --git a/server/sonar-webserver/src/test/java/org/sonar/server/platform/web/WebPagesFilterTest.java b/server/sonar-webserver/src/test/java/org/sonar/server/platform/web/WebPagesFilterTest.java index be262a47483..ecc8f9bc74d 100644 --- a/server/sonar-webserver/src/test/java/org/sonar/server/platform/web/WebPagesFilterTest.java +++ b/server/sonar-webserver/src/test/java/org/sonar/server/platform/web/WebPagesFilterTest.java @@ -26,9 +26,7 @@ import javax.servlet.WriteListener; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.RETURNS_MOCKS; @@ -40,8 +38,6 @@ import static org.mockito.Mockito.when; public class WebPagesFilterTest { private static final String TEST_CONTEXT = "/sonarqube"; - @Rule - public ExpectedException expectedException = ExpectedException.none(); private ServletContext servletContext = mock(ServletContext.class, RETURNS_MOCKS); private WebPagesCache webPagesCache = mock(WebPagesCache.class); diff --git a/server/sonar-webserver/src/test/java/org/sonar/server/platform/web/WebServiceFilterTest.java b/server/sonar-webserver/src/test/java/org/sonar/server/platform/web/WebServiceFilterTest.java index 29b55e8b373..a4de9f7d4ce 100644 --- a/server/sonar-webserver/src/test/java/org/sonar/server/platform/web/WebServiceFilterTest.java +++ b/server/sonar-webserver/src/test/java/org/sonar/server/platform/web/WebServiceFilterTest.java @@ -26,9 +26,7 @@ import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.RequestHandler; import org.sonar.api.server.ws.Response; @@ -47,8 +45,6 @@ public class WebServiceFilterTest { private static final String RUNTIME_VERSION = "7.1.0.1234"; - @Rule - public ExpectedException expectedException = ExpectedException.none(); private WebServiceEngine webServiceEngine = mock(WebServiceEngine.class); diff --git a/server/sonar-webserver/src/test/java/org/sonar/server/platform/web/WebServiceReroutingFilterTest.java b/server/sonar-webserver/src/test/java/org/sonar/server/platform/web/WebServiceReroutingFilterTest.java index 18d86fc9d64..1cd057f5bd4 100644 --- a/server/sonar-webserver/src/test/java/org/sonar/server/platform/web/WebServiceReroutingFilterTest.java +++ b/server/sonar-webserver/src/test/java/org/sonar/server/platform/web/WebServiceReroutingFilterTest.java @@ -23,9 +23,7 @@ import javax.servlet.FilterChain; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; import org.sonar.server.ws.ServletRequest; import org.sonar.server.ws.ServletResponse; @@ -38,8 +36,6 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class WebServiceReroutingFilterTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); private WebServiceEngine webServiceEngine = mock(WebServiceEngine.class); -- cgit v1.2.3