diff --git a/build.gradle b/build.gradle index 791c54c8d..5d98b2597 100644 --- a/build.gradle +++ b/build.gradle @@ -74,8 +74,6 @@ dependencies { implementation('com.squareup.okhttp3:logging-interceptor:4.12.0') testImplementation(platform('org.junit:junit-bom:5.11.3')) testImplementation('org.junit.jupiter:junit-jupiter') - testImplementation('junit:junit:4.13.2') - testRuntimeOnly('org.junit.vintage:junit-vintage-engine') } sourceSets.test.runtimeClasspath = configurations.customTestRuntime + sourceSets.test.runtimeClasspath diff --git a/src/main/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/ws/AlmTypeMapper.java b/src/main/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/ws/AlmTypeMapper.java deleted file mode 100644 index a390aaaf0..000000000 --- a/src/main/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/ws/AlmTypeMapper.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (C) 2020 Michael Clarke - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - */ -package com.github.mc1arke.sonarqube.plugin.server.pullrequest.ws; - -import org.sonar.db.alm.setting.ALM; -import org.sonarqube.ws.AlmSettings; - -public final class AlmTypeMapper { - - private AlmTypeMapper() { - super(); - } - - public static AlmSettings.Alm toAlmWs(ALM alm) { - switch (alm) { - case AZURE_DEVOPS: - return AlmSettings.Alm.azure; - case BITBUCKET: - return AlmSettings.Alm.bitbucket; - case GITHUB: - return AlmSettings.Alm.github; - case GITLAB: - return AlmSettings.Alm.gitlab; - default: - throw new IllegalStateException(String.format("Unknown ALM '%s'", alm.name())); - } - } -} diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/CommunityBranchAgentTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/CommunityBranchAgentTest.java index e5a1ca385..a6e2197ea 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/CommunityBranchAgentTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/CommunityBranchAgentTest.java @@ -67,7 +67,7 @@ void shouldRedefinePluginBootstrapIsAvailableForWebLaunch() throws ReflectiveOpe CommunityBranchAgent.premain("web", instrumentation); - ArgumentCaptor classFileTransformerArgumentCaptor = ArgumentCaptor.forClass(ClassFileTransformer.class); + ArgumentCaptor classFileTransformerArgumentCaptor = ArgumentCaptor.captor(); verify(instrumentation).retransformClasses(MultipleAlmFeature.class); verify(instrumentation, times(4)).addTransformer(classFileTransformerArgumentCaptor.capture()); @@ -92,7 +92,7 @@ void shouldRedefineMultipleAlmFeatureClassForWebLaunch() throws ReflectiveOperat CommunityBranchAgent.premain("web", instrumentation); - ArgumentCaptor classFileTransformerArgumentCaptor = ArgumentCaptor.forClass(ClassFileTransformer.class); + ArgumentCaptor classFileTransformerArgumentCaptor = ArgumentCaptor.captor(); verify(instrumentation).retransformClasses(MultipleAlmFeature.class); verify(instrumentation, times(4)).addTransformer(classFileTransformerArgumentCaptor.capture()); @@ -117,7 +117,7 @@ void shouldRedefineSetActionClassForWebLaunch() throws ReflectiveOperationExcept CommunityBranchAgent.premain("web", instrumentation); - ArgumentCaptor classFileTransformerArgumentCaptor = ArgumentCaptor.forClass(ClassFileTransformer.class); + ArgumentCaptor classFileTransformerArgumentCaptor = ArgumentCaptor.captor(); verify(instrumentation).retransformClasses(SetAction.class); verify(instrumentation, times(4)).addTransformer(classFileTransformerArgumentCaptor.capture()); @@ -150,7 +150,7 @@ void shouldRedefinesUnsetActionClassForWebLaunch() throws IOException, Unmodifia CommunityBranchAgent.premain("web", instrumentation); DocumentationLinkGenerator documentationLinkGenerator = mock(); - ArgumentCaptor classFileTransformerArgumentCaptor = ArgumentCaptor.forClass(ClassFileTransformer.class); + ArgumentCaptor classFileTransformerArgumentCaptor = ArgumentCaptor.captor(); verify(instrumentation).retransformClasses(UnsetAction.class); verify(instrumentation, times(4)).addTransformer(classFileTransformerArgumentCaptor.capture()); @@ -180,7 +180,7 @@ void shouldSkipNonTargetClasForWebLaunch() throws UnmodifiableClassException, Cl CommunityBranchAgent.premain("web", instrumentation); - ArgumentCaptor classFileTransformerArgumentCaptor = ArgumentCaptor.forClass(ClassFileTransformer.class); + ArgumentCaptor classFileTransformerArgumentCaptor = ArgumentCaptor.captor(); verify(instrumentation).retransformClasses(MultipleAlmFeature.class); verify(instrumentation, times(4)).addTransformer(classFileTransformerArgumentCaptor.capture()); @@ -196,7 +196,7 @@ void shouldSkipNonTargetClassForCeLunch() throws UnmodifiableClassException, Cla CommunityBranchAgent.premain("ce", instrumentation); - ArgumentCaptor classFileTransformerArgumentCaptor = ArgumentCaptor.forClass(ClassFileTransformer.class); + ArgumentCaptor classFileTransformerArgumentCaptor = ArgumentCaptor.captor(); verify(instrumentation).retransformClasses(PlatformEditionProvider.class); verify(instrumentation, times(3)).addTransformer(classFileTransformerArgumentCaptor.capture()); @@ -212,7 +212,7 @@ void shouldRedefineTargetClassesForCeLaunch() throws ReflectiveOperationExceptio CommunityBranchAgent.premain("ce", instrumentation); - ArgumentCaptor classFileTransformerArgumentCaptor = ArgumentCaptor.forClass(ClassFileTransformer.class); + ArgumentCaptor classFileTransformerArgumentCaptor = ArgumentCaptor.captor(); verify(instrumentation).retransformClasses(MultipleAlmFeature.class); verify(instrumentation).retransformClasses(PlatformEditionProvider.class); verify(instrumentation, times(3)).addTransformer(classFileTransformerArgumentCaptor.capture()); diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/almclient/azuredevops/AzureDevopsRestClientTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/almclient/azuredevops/AzureDevopsRestClientTest.java index 93e0bf081..e14def20f 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/almclient/azuredevops/AzureDevopsRestClientTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/almclient/azuredevops/AzureDevopsRestClientTest.java @@ -1,3 +1,21 @@ +/* + * Copyright (C) 2021-2024 Michael Clarke + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ package com.github.mc1arke.sonarqube.plugin.almclient.azuredevops; import com.fasterxml.jackson.databind.ObjectMapper; @@ -29,27 +47,27 @@ class AzureDevopsRestClientTest { - private final ObjectMapper objectMapper = mock(ObjectMapper.class); - private final CloseableHttpClient closeableHttpClient = mock(CloseableHttpClient.class); + private final ObjectMapper objectMapper = mock(); + private final CloseableHttpClient closeableHttpClient = mock(); @Test void checkErrorThrownOnNonSuccessResponseStatus() throws IOException { AzureDevopsRestClient underTest = new AzureDevopsRestClient("http://url.test/api", "token", objectMapper, () -> closeableHttpClient); - CloseableHttpResponse closeableHttpResponse = mock(CloseableHttpResponse.class); - StatusLine statusLine = mock(StatusLine.class); + CloseableHttpResponse closeableHttpResponse = mock(); + StatusLine statusLine = mock(); when(statusLine.getStatusCode()).thenReturn(500); when(closeableHttpResponse.getStatusLine()).thenReturn(statusLine); when(closeableHttpClient.execute(any())).thenReturn(closeableHttpResponse); when(objectMapper.writeValueAsString(any())).thenReturn("json"); - GitPullRequestStatus gitPullRequestStatus = mock(GitPullRequestStatus.class); + GitPullRequestStatus gitPullRequestStatus = mock(); assertThatThrownBy(() -> underTest.submitPullRequestStatus("project", "repo", 101, gitPullRequestStatus)) .isExactlyInstanceOf(IllegalStateException.class) .hasMessage("An unexpected response code was returned from the Azure Devops API - Expected: 200, Got: 500") .hasNoCause(); - ArgumentCaptor requestArgumentCaptor = ArgumentCaptor.forClass(HttpUriRequest.class); + ArgumentCaptor requestArgumentCaptor = ArgumentCaptor.captor(); verify(closeableHttpClient).execute(requestArgumentCaptor.capture()); RequestBuilder request = RequestBuilder.copy(requestArgumentCaptor.getValue()); @@ -63,8 +81,8 @@ void checkErrorThrownOnNonSuccessResponseStatus() throws IOException { void checkSubmitPullRequestStatusSubmitsCorrectContent() throws IOException { AzureDevopsRestClient underTest = new AzureDevopsRestClient("http://url.test/api", "token", objectMapper, () -> closeableHttpClient); - CloseableHttpResponse closeableHttpResponse = mock(CloseableHttpResponse.class); - StatusLine statusLine = mock(StatusLine.class); + CloseableHttpResponse closeableHttpResponse = mock(); + StatusLine statusLine = mock(); when(statusLine.getStatusCode()).thenReturn(200); when(closeableHttpResponse.getStatusLine()).thenReturn(statusLine); when(closeableHttpClient.execute(any())).thenReturn(closeableHttpResponse); @@ -72,7 +90,7 @@ void checkSubmitPullRequestStatusSubmitsCorrectContent() throws IOException { underTest.submitPullRequestStatus("project Id With Spaces", "repository Name With Spaces", 123, new GitPullRequestStatus(GitStatusState.SUCCEEDED, "description", new GitStatusContext("name", "genre"), "url")); - ArgumentCaptor requestArgumentCaptor = ArgumentCaptor.forClass(HttpUriRequest.class); + ArgumentCaptor requestArgumentCaptor = ArgumentCaptor.captor(); verify(closeableHttpClient).execute(requestArgumentCaptor.capture()); RequestBuilder request = RequestBuilder.copy(requestArgumentCaptor.getValue()); @@ -86,8 +104,8 @@ void checkSubmitPullRequestStatusSubmitsCorrectContent() throws IOException { void checkAddCommentToThreadSubmitsCorrectContent() throws IOException { AzureDevopsRestClient underTest = new AzureDevopsRestClient("http://test.url", "authToken", objectMapper, () -> closeableHttpClient); - CloseableHttpResponse closeableHttpResponse = mock(CloseableHttpResponse.class); - StatusLine statusLine = mock(StatusLine.class); + CloseableHttpResponse closeableHttpResponse = mock(); + StatusLine statusLine = mock(); when(statusLine.getStatusCode()).thenReturn(200); when(closeableHttpResponse.getStatusLine()).thenReturn(statusLine); when(closeableHttpClient.execute(any())).thenReturn(closeableHttpResponse); @@ -95,7 +113,7 @@ void checkAddCommentToThreadSubmitsCorrectContent() throws IOException { underTest.addCommentToThread("projectId", "repository Name", 123, 321, new CreateCommentRequest("comment")); - ArgumentCaptor requestArgumentCaptor = ArgumentCaptor.forClass(HttpUriRequest.class); + ArgumentCaptor requestArgumentCaptor = ArgumentCaptor.captor(); verify(closeableHttpClient).execute(requestArgumentCaptor.capture()); RequestBuilder request = RequestBuilder.copy(requestArgumentCaptor.getValue()); @@ -109,18 +127,18 @@ void checkAddCommentToThreadSubmitsCorrectContent() throws IOException { void checkRetrievePullRequestReturnsCorrectContent() throws IOException { AzureDevopsRestClient underTest = new AzureDevopsRestClient("http://test.url", "authToken", objectMapper, () -> closeableHttpClient); - CloseableHttpResponse closeableHttpResponse = mock(CloseableHttpResponse.class); - StatusLine statusLine = mock(StatusLine.class); + CloseableHttpResponse closeableHttpResponse = mock(); + StatusLine statusLine = mock(); when(statusLine.getStatusCode()).thenReturn(200); when(closeableHttpResponse.getStatusLine()).thenReturn(statusLine); when(closeableHttpResponse.getEntity()).thenReturn(new StringEntity("content", StandardCharsets.UTF_8)); when(closeableHttpClient.execute(any())).thenReturn(closeableHttpResponse); - PullRequest pullRequest = mock(PullRequest.class); + PullRequest pullRequest = mock(); when(objectMapper.readValue(any(String.class), eq(PullRequest.class))).thenReturn(pullRequest); PullRequest result = underTest.retrievePullRequest("projectId", "repository Name", 123); - ArgumentCaptor requestArgumentCaptor = ArgumentCaptor.forClass(HttpUriRequest.class); + ArgumentCaptor requestArgumentCaptor = ArgumentCaptor.captor(); verify(closeableHttpClient).execute(requestArgumentCaptor.capture()); RequestBuilder request = RequestBuilder.copy(requestArgumentCaptor.getValue()); diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/almclient/bitbucket/BitbucketCloudClientUnitTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/almclient/bitbucket/BitbucketCloudClientUnitTest.java index f844c6d33..ae207b72d 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/almclient/bitbucket/BitbucketCloudClientUnitTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/almclient/bitbucket/BitbucketCloudClientUnitTest.java @@ -71,10 +71,10 @@ void setup() { @Test void testUploadReport() throws IOException { // given - CodeInsightsReport report = mock(CodeInsightsReport.class); - Call call = mock(Call.class); - Response response = mock(Response.class); - ArgumentCaptor captor = ArgumentCaptor.forClass(Request.class); + CodeInsightsReport report = mock(); + Call call = mock(); + Response response = mock(); + ArgumentCaptor captor = ArgumentCaptor.captor(); when(client.newCall(any())).thenReturn(call); when(call.execute()).thenReturn(response); @@ -95,9 +95,9 @@ void testUploadReport() throws IOException { @Test void testDeleteReport() throws IOException { // given - Call call = mock(Call.class); - Response response = mock(Response.class); - ArgumentCaptor captor = ArgumentCaptor.forClass(Request.class); + Call call = mock(); + Response response = mock(); + ArgumentCaptor captor = ArgumentCaptor.captor(); when(client.newCall(any())).thenReturn(call); when(call.execute()).thenReturn(response); @@ -115,11 +115,11 @@ void testDeleteReport() throws IOException { @Test void testUploadAnnotations() throws IOException { // given - CodeInsightsAnnotation annotation = mock(CloudAnnotation.class); + CloudAnnotation annotation = mock(); Set annotations = Sets.newHashSet(annotation); - Call call = mock(Call.class); - Response response = mock(Response.class); - ArgumentCaptor captor = ArgumentCaptor.forClass(Request.class); + Call call = mock(); + Response response = mock(); + ArgumentCaptor captor = ArgumentCaptor.captor(); when(client.newCall(any())).thenReturn(call); when(call.execute()).thenReturn(response); @@ -151,10 +151,10 @@ void testUploadLimit() { @Test void testUploadReportFailsWithMessage() throws IOException { // given - CodeInsightsReport report = mock(CodeInsightsReport.class); - Call call = mock(Call.class); - Response response = mock(Response.class); - ResponseBody responseBody = mock(ResponseBody.class); + CodeInsightsReport report = mock(); + Call call = mock(); + Response response = mock(); + ResponseBody responseBody = mock(); when(client.newCall(any())).thenReturn(call); when(call.execute()).thenReturn(response); diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/almclient/bitbucket/BitbucketExceptionTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/almclient/bitbucket/BitbucketExceptionTest.java index 95bcd81d0..8bac6a4c3 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/almclient/bitbucket/BitbucketExceptionTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/almclient/bitbucket/BitbucketExceptionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2020-2021 Michael Clarke + * Copyright (C) 2020-2024 Michael Clarke * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -18,15 +18,16 @@ */ package com.github.mc1arke.sonarqube.plugin.almclient.bitbucket; -import com.github.mc1arke.sonarqube.plugin.almclient.bitbucket.model.server.ErrorResponse; -import org.junit.Test; - import static org.assertj.core.api.Assertions.assertThat; -public class BitbucketExceptionTest { +import org.junit.jupiter.api.Test; + +import com.github.mc1arke.sonarqube.plugin.almclient.bitbucket.model.server.ErrorResponse; + +class BitbucketExceptionTest { @Test - public void verifyMessageReturnedWhenErrorResponseContainsNoErrors() { + void verifyMessageReturnedWhenErrorResponseContainsNoErrors() { BitbucketException testCase = new BitbucketException(401, new ErrorResponse(null)); assertThat(testCase.getMessage()).isEqualTo("Bitbucket responded with an error status (401)"); } diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/almclient/bitbucket/BitbucketServerClientUnitTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/almclient/bitbucket/BitbucketServerClientUnitTest.java index 0c2fcd6e8..41972713d 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/almclient/bitbucket/BitbucketServerClientUnitTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/almclient/bitbucket/BitbucketServerClientUnitTest.java @@ -71,10 +71,10 @@ void testSupportsCodeInsightsIsFalse() throws IOException { // given ServerProperties serverProperties = new ServerProperties("5.0"); - Call call = mock(Call.class); - Response response = mock(Response.class); - ObjectReader reader = mock(ObjectReader.class); - ResponseBody responseBody = mock(ResponseBody.class); + Call call = mock(); + Response response = mock(); + ObjectReader reader = mock(); + ResponseBody responseBody = mock(); when(client.newCall(any())).thenReturn(call); when(call.execute()).thenReturn(response); @@ -98,10 +98,10 @@ void testSupportsCodeInsightsIsTrueWhenVersionEqual() throws IOException { // given ServerProperties serverProperties = new ServerProperties("5.15"); - Call call = mock(Call.class); - Response response = mock(Response.class); - ObjectReader reader = mock(ObjectReader.class); - ResponseBody responseBody = mock(ResponseBody.class); + Call call = mock(); + Response response = mock(); + ObjectReader reader = mock(); + ResponseBody responseBody = mock(); when(client.newCall(any())).thenReturn(call); when(call.execute()).thenReturn(response); @@ -125,10 +125,10 @@ void testSupportsCodeInsightsIsTrueIfVersionIsHigher() throws IOException { // given ServerProperties serverProperties = new ServerProperties("6.0"); - Call call = mock(Call.class); - Response response = mock(Response.class); - ObjectReader reader = mock(ObjectReader.class); - ResponseBody responseBody = mock(ResponseBody.class); + Call call = mock(); + Response response = mock(); + ObjectReader reader = mock(); + ResponseBody responseBody = mock(); when(client.newCall(any())).thenReturn(call); when(call.execute()).thenReturn(response); @@ -150,7 +150,7 @@ void testSupportsCodeInsightsIsTrueIfVersionIsHigher() throws IOException { @Test void testSupportsCodeInsightsIsFalseWhenException() throws IOException { // given - Call call = mock(Call.class); + Call call = mock(); when(client.newCall(any())).thenReturn(call); when(call.execute()).thenThrow(new IOException()); @@ -166,11 +166,11 @@ void testGetServerProperties() throws IOException { // given ServerProperties serverProperties = new ServerProperties("5.0"); - Call call = mock(Call.class); - Response response = mock(Response.class); - ObjectReader reader = mock(ObjectReader.class); - ResponseBody responseBody = mock(ResponseBody.class); - ArgumentCaptor captor = ArgumentCaptor.forClass(Request.class); + Call call = mock(); + Response response = mock(); + ObjectReader reader = mock(); + ResponseBody responseBody = mock(); + ArgumentCaptor captor = ArgumentCaptor.captor(); when(client.newCall(any())).thenReturn(call); when(call.execute()).thenReturn(response); @@ -196,9 +196,9 @@ void testGetServerProperties() throws IOException { @Test void testGetServerPropertiesError() throws IOException { // given - Call call = mock(Call.class); - Response response = mock(Response.class); - ObjectReader reader = mock(ObjectReader.class); + Call call = mock(); + Response response = mock(); + ObjectReader reader = mock(); when(client.newCall(any())).thenReturn(call); when(call.execute()).thenReturn(response); @@ -216,10 +216,10 @@ void testGetServerPropertiesError() throws IOException { @Test void testUploadReport() throws IOException { // given - CodeInsightsReport report = mock(CodeInsightsReport.class); - Call call = mock(Call.class); - Response response = mock(Response.class); - ArgumentCaptor captor = ArgumentCaptor.forClass(Request.class); + CodeInsightsReport report = mock(); + Call call = mock(); + Response response = mock(); + ArgumentCaptor captor = ArgumentCaptor.captor(); when(client.newCall(any())).thenReturn(call); when(call.execute()).thenReturn(response); @@ -240,9 +240,9 @@ void testUploadReport() throws IOException { @Test void testUploadReportFails() throws IOException { // given - CodeInsightsReport report = mock(CodeInsightsReport.class); - Call call = mock(Call.class); - Response response = mock(Response.class); + CodeInsightsReport report = mock(); + Call call = mock(); + Response response = mock(); when(client.newCall(any())).thenReturn(call); when(call.execute()).thenReturn(response); @@ -262,11 +262,11 @@ void testUploadReportFailsWithMessage() throws IOException { ErrorResponse.Error error = new ErrorResponse.Error("error!"); ErrorResponse errorResponse = new ErrorResponse(Sets.newHashSet(error)); - CodeInsightsReport report = mock(CodeInsightsReport.class); - Call call = mock(Call.class); - Response response = mock(Response.class); - ResponseBody responseBody = mock(ResponseBody.class); - ObjectReader reader = mock(ObjectReader.class); + CodeInsightsReport report = mock(); + Call call = mock(); + Response response = mock(); + ResponseBody responseBody = mock(); + ObjectReader reader = mock(); when(client.newCall(any())).thenReturn(call); when(call.execute()).thenReturn(response); @@ -293,7 +293,7 @@ void testUploadReportFailsWithMessage() throws IOException { @Test void testUploadAnnotations() throws IOException { // given - Annotation annotation = mock(Annotation.class); + Annotation annotation = mock(); when(annotation.getLine()).thenReturn(12); when(annotation.getMessage()).thenReturn("hello"); when(annotation.getSeverity()).thenReturn("severe"); @@ -302,9 +302,9 @@ void testUploadAnnotations() throws IOException { when(annotation.getLink()).thenReturn("link"); when(annotation.getType()).thenReturn("type"); Set annotations = Sets.newHashSet(annotation); - Call call = mock(Call.class); - Response response = mock(Response.class); - ArgumentCaptor captor = ArgumentCaptor.forClass(Request.class); + Call call = mock(); + Response response = mock(); + ArgumentCaptor captor = ArgumentCaptor.captor(); when(client.newCall(any())).thenReturn(call); when(call.execute()).thenReturn(response); @@ -340,9 +340,9 @@ void testUploadAnnotationsWithEmptyAnnotations() throws IOException { @Test void testDeleteAnnotations() throws IOException { // given - Call call = mock(Call.class); - Response response = mock(Response.class); - ArgumentCaptor captor = ArgumentCaptor.forClass(Request.class); + Call call = mock(); + Response response = mock(); + ArgumentCaptor captor = ArgumentCaptor.captor(); when(client.newCall(any())).thenReturn(call); when(call.execute()).thenReturn(response); diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/almclient/bitbucket/DefaultBitbucketClientFactoryUnitTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/almclient/bitbucket/DefaultBitbucketClientFactoryUnitTest.java index 7abd10fba..67b28d362 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/almclient/bitbucket/DefaultBitbucketClientFactoryUnitTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/almclient/bitbucket/DefaultBitbucketClientFactoryUnitTest.java @@ -1,10 +1,29 @@ +/* + * Copyright (C) 2020-2024 Marvin Wichmann, Michael Clarke + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ package com.github.mc1arke.sonarqube.plugin.almclient.bitbucket; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.ResponseBody; -import org.junit.Test; + +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import org.sonar.api.config.internal.Encryption; @@ -15,17 +34,17 @@ import java.io.IOException; -import static org.junit.Assert.assertTrue; +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.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -public class DefaultBitbucketClientFactoryUnitTest { +class DefaultBitbucketClientFactoryUnitTest { @Test - public void testCreateClientIsCloudIfCloudConfig() throws IOException { + void testCreateClientIsCloudIfCloudConfig() throws IOException { // given AlmSettingDto almSettingDto = new AlmSettingDto().setAlm(ALM.BITBUCKET_CLOUD) .setClientId("clientId") @@ -36,33 +55,33 @@ public void testCreateClientIsCloudIfCloudConfig() throws IOException { OkHttpClient.Builder builder = mock(OkHttpClient.Builder.class, Mockito.RETURNS_DEEP_STUBS); when(builder.addInterceptor(any())).thenReturn(builder); - ResponseBody responseBody = mock(ResponseBody.class); + ResponseBody responseBody = mock(); when(responseBody.string()).thenReturn("{\"access_token\": \"dummy\"}"); when(builder.build().newCall(any()).execute().body()).thenReturn(responseBody); - Settings settings = mock(Settings.class); - Encryption encryption = mock(Encryption.class); + Settings settings = mock(); + Encryption encryption = mock(); // when when(settings.getEncryption()).thenReturn(encryption); - HttpClientBuilderFactory httpClientBuilderFactory = mock(HttpClientBuilderFactory.class); + HttpClientBuilderFactory httpClientBuilderFactory = mock(); when(httpClientBuilderFactory.createClientBuilder()).then(i -> builder); BitbucketClient client = new DefaultBitbucketClientFactory(settings, httpClientBuilderFactory).createClient(projectAlmSettingDto, almSettingDto); // then - assertTrue(client instanceof BitbucketCloudClient); + assertThat(client).isInstanceOf(BitbucketCloudClient.class); - ArgumentCaptor interceptorArgumentCaptor = ArgumentCaptor.forClass(Interceptor.class); + ArgumentCaptor interceptorArgumentCaptor = ArgumentCaptor.captor(); verify(builder, times(2)).addInterceptor(interceptorArgumentCaptor.capture()); - Interceptor.Chain chain = mock(Interceptor.Chain.class); - Request request = mock(Request.class); + Interceptor.Chain chain = mock(); + Request request = mock(); when(chain.request()).thenReturn(request); - Request.Builder requestBuilder = mock(Request.Builder.class); + Request.Builder requestBuilder = mock(); when(requestBuilder.addHeader(any(), any())).thenReturn(requestBuilder); when(request.newBuilder()).thenReturn(requestBuilder); - Request request2 = mock(Request.class); + Request request2 = mock(); when(requestBuilder.build()).thenReturn(request2); interceptorArgumentCaptor.getValue().intercept(chain); @@ -73,7 +92,7 @@ public void testCreateClientIsCloudIfCloudConfig() throws IOException { } @Test - public void testCreateClientIfNotCloudConfig() { + void testCreateClientIfNotCloudConfig() { // given AlmSettingDto almSettingDto = new AlmSettingDto().setAlm(ALM.BITBUCKET) .setUrl("url") @@ -82,17 +101,17 @@ public void testCreateClientIfNotCloudConfig() { .setAlmRepo("almRepo") .setAlmSlug("almSlug"); - Settings settings = mock(Settings.class); - Encryption encryption = mock(Encryption.class); + Settings settings = mock(); + Encryption encryption = mock(); // when when(settings.getEncryption()).thenReturn(encryption); - HttpClientBuilderFactory httpClientBuilderFactory = mock(HttpClientBuilderFactory.class); + HttpClientBuilderFactory httpClientBuilderFactory = mock(); when(httpClientBuilderFactory.createClientBuilder()).then(i -> mock(OkHttpClient.Builder.class, Mockito.RETURNS_DEEP_STUBS)); BitbucketClient client = new DefaultBitbucketClientFactory(settings, httpClientBuilderFactory).createClient(projectAlmSettingDto, almSettingDto); // then - assertTrue(client instanceof BitbucketServerClient); + assertThat(client).isInstanceOf(BitbucketServerClient.class); } diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/almclient/gitlab/GitlabRestClientTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/almclient/gitlab/GitlabRestClientTest.java index 7182e145b..c98eaa9fb 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/almclient/gitlab/GitlabRestClientTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/almclient/gitlab/GitlabRestClientTest.java @@ -40,21 +40,21 @@ class GitlabRestClientTest { - private final CloseableHttpClient closeableHttpClient = mock(CloseableHttpClient.class); - private final LinkHeaderReader linkHeaderReader = mock(LinkHeaderReader.class); - private final ObjectMapper objectMapper = mock(ObjectMapper.class); + private final CloseableHttpClient closeableHttpClient = mock(); + private final LinkHeaderReader linkHeaderReader = mock(); + private final ObjectMapper objectMapper = mock(); @Test void checkErrorThrownOnNonSuccessResponseStatus() throws IOException { GitlabRestClient underTest = new GitlabRestClient("http://url.test/api", "token", linkHeaderReader, objectMapper, () -> closeableHttpClient); - CloseableHttpResponse closeableHttpResponse = mock(CloseableHttpResponse.class); - StatusLine statusLine = mock(StatusLine.class); + CloseableHttpResponse closeableHttpResponse = mock(); + StatusLine statusLine = mock(); when(statusLine.getStatusCode()).thenReturn(500); when(closeableHttpResponse.getStatusLine()).thenReturn(statusLine); when(closeableHttpClient.execute(any())).thenReturn(closeableHttpResponse); - MergeRequestNote mergeRequestNote = mock(MergeRequestNote.class); + MergeRequestNote mergeRequestNote = mock(); when(mergeRequestNote.getContent()).thenReturn("note"); assertThatThrownBy(() -> underTest.addMergeRequestDiscussion(101, 99, mergeRequestNote)) @@ -62,7 +62,7 @@ void checkErrorThrownOnNonSuccessResponseStatus() throws IOException { .hasMessage("An unexpected response code was returned from the Gitlab API - Expected: 201, Got: 500") .hasNoCause(); - ArgumentCaptor requestArgumentCaptor = ArgumentCaptor.forClass(HttpUriRequest.class); + ArgumentCaptor requestArgumentCaptor = ArgumentCaptor.captor(); verify(closeableHttpClient).execute(requestArgumentCaptor.capture()); HttpEntityEnclosingRequest request = (HttpEntityEnclosingRequest) requestArgumentCaptor.getValue(); @@ -74,11 +74,11 @@ void checkErrorThrownOnNonSuccessResponseStatus() throws IOException { @Test void checkCorrectEncodingUsedOnMergeRequestDiscussion() throws IOException { - CloseableHttpResponse closeableHttpResponse = mock(CloseableHttpResponse.class); - StatusLine statusLine = mock(StatusLine.class); + CloseableHttpResponse closeableHttpResponse = mock(); + StatusLine statusLine = mock(); when(statusLine.getStatusCode()).thenReturn(201); when(closeableHttpResponse.getStatusLine()).thenReturn(statusLine); - HttpEntity httpEntity = mock(HttpEntity.class); + HttpEntity httpEntity = mock(); when(closeableHttpResponse.getEntity()).thenReturn(httpEntity); when(closeableHttpClient.execute(any())).thenReturn(closeableHttpResponse); @@ -87,7 +87,7 @@ void checkCorrectEncodingUsedOnMergeRequestDiscussion() throws IOException { GitlabRestClient underTest = new GitlabRestClient("http://api.url", "token", linkHeaderReader, objectMapper, () -> closeableHttpClient); underTest.addMergeRequestDiscussion(123, 321, mergeRequestNote); - ArgumentCaptor requestArgumentCaptor = ArgumentCaptor.forClass(HttpUriRequest.class); + ArgumentCaptor requestArgumentCaptor = ArgumentCaptor.captor(); verify(closeableHttpClient).execute(requestArgumentCaptor.capture()); HttpEntityEnclosingRequest request = (HttpEntityEnclosingRequest) requestArgumentCaptor.getValue(); diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/CommunityBranchLoaderDelegateTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/CommunityBranchLoaderDelegateTest.java index 95d9705e6..466151554 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/CommunityBranchLoaderDelegateTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/CommunityBranchLoaderDelegateTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2020-2023 Michael Clarke + * Copyright (C) 2020-2024 Michael Clarke * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -18,10 +18,7 @@ */ package com.github.mc1arke.sonarqube.plugin.ce; -import org.hamcrest.core.IsEqual; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.sonar.ce.task.projectanalysis.analysis.Branch; import org.sonar.ce.task.projectanalysis.analysis.MutableAnalysisMetadataHolder; @@ -36,9 +33,8 @@ import java.util.ArrayList; import java.util.Optional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; +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; @@ -49,40 +45,31 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; -/** - * @author Michael Clarke - */ -public class CommunityBranchLoaderDelegateTest { +class CommunityBranchLoaderDelegateTest { - private final ExpectedException expectedException = ExpectedException.none(); - private final MutableAnalysisMetadataHolder metadataHolder = mock(MutableAnalysisMetadataHolder.class); - private final DbClient dbClient = mock(DbClient.class); + private final MutableAnalysisMetadataHolder metadataHolder = mock(); + private final DbClient dbClient = mock(); private final BranchLoaderDelegate testCase = new CommunityBranchLoaderDelegate(dbClient, metadataHolder); - @Rule - public ExpectedException expectedException() { - return expectedException; - } - @Test - public void testNoBranchDetailsNoExistingBranchThrowsException() { + void testNoBranchDetailsNoExistingBranchThrowsException() { - BranchDao branchDao = mock(BranchDao.class); + BranchDao branchDao = mock(); when(branchDao.selectByBranchKey(any(), any(), any())).thenReturn(Optional.empty()); ScannerReport.Metadata metadata = ScannerReport.Metadata.getDefaultInstance(); when(dbClient.branchDao()).thenReturn(branchDao); when(metadataHolder.getProject()).thenReturn(new Project("uuid", "key", "name", "description", new ArrayList<>())); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage(IsEqual.equalTo("Could not find main branch")); - - testCase.load(metadata); + assertThatThrownBy(() -> testCase.load(metadata)) + .isExactlyInstanceOf(IllegalStateException.class) + .hasMessage("Could not find main branch") + .hasNoCause(); } @Test - public void testNoBranchDetailsExistingBranchMatch() { - BranchDto branchDto = mock(BranchDto.class); + void testNoBranchDetailsExistingBranchMatch() { + BranchDto branchDto = mock(); when(branchDto.getBranchType()).thenReturn(BranchType.BRANCH); when(branchDto.getKey()).thenReturn("branchKey"); when(branchDto.getMergeBranchUuid()).thenReturn("mergeBranchUuid"); @@ -90,7 +77,7 @@ public void testNoBranchDetailsExistingBranchMatch() { when(branchDto.getUuid()).thenReturn("branchUuid"); when(branchDto.isMain()).thenReturn(false); - BranchDao branchDao = mock(BranchDao.class); + BranchDao branchDao = mock(); when(branchDao.selectMainBranchByProjectUuid(any(), any())).thenReturn(Optional.of(branchDto)); ScannerReport.Metadata metadata = ScannerReport.Metadata.getDefaultInstance(); @@ -99,15 +86,15 @@ public void testNoBranchDetailsExistingBranchMatch() { testCase.load(metadata); - ArgumentCaptor branchArgumentCaptor = ArgumentCaptor.forClass(Branch.class); + ArgumentCaptor branchArgumentCaptor = ArgumentCaptor.captor(); verify(metadataHolder).setBranch(branchArgumentCaptor.capture()); - assertEquals(BranchType.BRANCH, branchArgumentCaptor.getValue().getType()); - assertNull(branchArgumentCaptor.getValue().getTargetBranchName()); - assertEquals("branchKey", branchArgumentCaptor.getValue().getName()); - assertFalse(branchArgumentCaptor.getValue().isMain()); - assertFalse(branchArgumentCaptor.getValue().supportsCrossProjectCpd()); - assertNull(branchArgumentCaptor.getValue().getReferenceBranchUuid()); + assertThat(branchArgumentCaptor.getValue().getType()).isEqualTo(BranchType.BRANCH); + assertThat(branchArgumentCaptor.getValue().getTargetBranchName()).isNull(); + assertThat(branchArgumentCaptor.getValue().getName()).isEqualTo("branchKey"); + assertThat(branchArgumentCaptor.getValue().isMain()).isFalse(); + assertThat(branchArgumentCaptor.getValue().supportsCrossProjectCpd()).isFalse(); + assertThat(branchArgumentCaptor.getValue().getReferenceBranchUuid()).isNull(); verify(metadataHolder).getProject(); verify(metadataHolder).setPullRequestKey(anyString()); @@ -123,9 +110,9 @@ public void testNoBranchDetailsExistingBranchMatch() { } @Test - public void testBranchNameNoMatchingBranch() { + void testBranchNameNoMatchingBranch() { - BranchDao branchDao = mock(BranchDao.class); + BranchDao branchDao = mock(); when(branchDao.selectByBranchKey(any(), any(), any())).thenReturn(Optional.empty()); ScannerReport.Metadata metadata = @@ -135,22 +122,22 @@ public void testBranchNameNoMatchingBranch() { when(metadataHolder.getProject()).thenReturn(new Project("uuid", "key", "name", "description", new ArrayList<>())); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage(IsEqual.equalTo("Invalid branch type 'UNSET'")); - - testCase.load(metadata); + assertThatThrownBy(() -> testCase.load(metadata)) + .isExactlyInstanceOf(IllegalStateException.class) + .hasMessage("Invalid branch type 'UNSET'") + .hasNoCause(); } @Test - public void testBranchNameMatchingBranch() { - BranchDto branchDto = mock(BranchDto.class); + void testBranchNameMatchingBranch() { + BranchDto branchDto = mock(); when(branchDto.getBranchType()).thenReturn(BranchType.BRANCH); when(branchDto.getKey()).thenReturn("branchKey"); when(branchDto.getMergeBranchUuid()).thenReturn("mergeBranchUuid"); when(branchDto.getProjectUuid()).thenReturn("projectUuid"); when(branchDto.getUuid()).thenReturn("branchUuid"); - BranchDao branchDao = mock(BranchDao.class); + BranchDao branchDao = mock(); when(branchDao.selectByBranchKey(any(), eq("projectUuid"), eq("branch"))).thenReturn(Optional.of(branchDto)); ScannerReport.Metadata metadata = @@ -163,14 +150,14 @@ public void testBranchNameMatchingBranch() { testCase.load(metadata); - ArgumentCaptor branchArgumentCaptor = ArgumentCaptor.forClass(Branch.class); + ArgumentCaptor branchArgumentCaptor = ArgumentCaptor.captor(); verify(metadataHolder).setBranch(branchArgumentCaptor.capture()); - assertEquals(BranchType.BRANCH, branchArgumentCaptor.getValue().getType()); - assertEquals("projectUuid", branchArgumentCaptor.getValue().getReferenceBranchUuid()); - assertEquals("branch", branchArgumentCaptor.getValue().getName()); - assertFalse(branchArgumentCaptor.getValue().isMain()); - assertFalse(branchArgumentCaptor.getValue().supportsCrossProjectCpd()); + assertThat(branchArgumentCaptor.getValue().getType()).isEqualTo(BranchType.BRANCH); + assertThat(branchArgumentCaptor.getValue().getReferenceBranchUuid()).isEqualTo("projectUuid"); + assertThat(branchArgumentCaptor.getValue().getName()).isEqualTo("branch"); + assertThat(branchArgumentCaptor.getValue().isMain()).isFalse(); + assertThat(branchArgumentCaptor.getValue().supportsCrossProjectCpd()).isFalse(); verify(metadataHolder).getProject(); verify(metadataHolder).setPullRequestKey(anyString()); @@ -186,14 +173,14 @@ public void testBranchNameMatchingBranch() { } @Test - public void testBranchNamePullRequest() { - BranchDto branchDto = mock(BranchDto.class); + void testBranchNamePullRequest() { + BranchDto branchDto = mock(); when(branchDto.getBranchType()).thenReturn(BranchType.BRANCH); when(branchDto.getKey()).thenReturn("branchKey"); when(branchDto.getUuid()).thenReturn("mergeBranchUuid"); when(branchDto.getProjectUuid()).thenReturn("projectUuid"); - BranchDao branchDao = mock(BranchDao.class); + BranchDao branchDao = mock(); when(branchDao.selectByBranchKey(any(), eq("projectUuid"), eq("branch"))).thenReturn(Optional.of(branchDto)); ScannerReport.Metadata metadata = @@ -209,15 +196,15 @@ public void testBranchNamePullRequest() { testCase.load(metadata); - ArgumentCaptor branchArgumentCaptor = ArgumentCaptor.forClass(Branch.class); + ArgumentCaptor branchArgumentCaptor = ArgumentCaptor.captor(); verify(metadataHolder).setBranch(branchArgumentCaptor.capture()); - assertEquals(BranchType.PULL_REQUEST, branchArgumentCaptor.getValue().getType()); - assertEquals("mergeBranchUuid", branchArgumentCaptor.getValue().getReferenceBranchUuid()); - assertEquals("sourceBranch", branchArgumentCaptor.getValue().getName()); - assertFalse(branchArgumentCaptor.getValue().isMain()); - assertFalse(branchArgumentCaptor.getValue().supportsCrossProjectCpd()); - assertEquals("branch", branchArgumentCaptor.getValue().getTargetBranchName()); + assertThat(branchArgumentCaptor.getValue().getType()).isEqualTo(BranchType.PULL_REQUEST); + assertThat(branchArgumentCaptor.getValue().getReferenceBranchUuid()).isEqualTo("mergeBranchUuid"); + assertThat(branchArgumentCaptor.getValue().getName()).isEqualTo("sourceBranch"); + assertThat(branchArgumentCaptor.getValue().isMain()).isFalse(); + assertThat(branchArgumentCaptor.getValue().supportsCrossProjectCpd()).isFalse(); + assertThat(branchArgumentCaptor.getValue().getTargetBranchName()).isEqualTo("branch"); verify(metadataHolder).getProject(); @@ -234,8 +221,8 @@ public void testBranchNamePullRequest() { } @Test - public void testBranchNamePullRequestNoSuchTarget() { - BranchDao branchDao = mock(BranchDao.class); + void testBranchNamePullRequestNoSuchTarget() { + BranchDao branchDao = mock(); when(branchDao.selectByBranchKey(any(), eq("projectUuid"), eq("branch"))).thenReturn(Optional.empty()); ScannerReport.Metadata metadata = @@ -247,31 +234,30 @@ public void testBranchNamePullRequestNoSuchTarget() { when(metadataHolder.getProject()).thenReturn(new Project("projectUuid", "key", "name", "description", new ArrayList<>())); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage(IsEqual.equalTo("Could not find target branch 'branch' in project")); - - - testCase.load(metadata); + assertThatThrownBy(() -> testCase.load(metadata)) + .isExactlyInstanceOf(IllegalStateException.class) + .hasMessage("Could not find target branch 'branch' in project") + .hasNoCause(); } @Test - public void testBranchNameMatchingBranchWithTargetBranch() { - BranchDto sourceBranchDto = mock(BranchDto.class); + void testBranchNameMatchingBranchWithTargetBranch() { + BranchDto sourceBranchDto = mock(); when(sourceBranchDto.getBranchType()).thenReturn(BranchType.BRANCH); when(sourceBranchDto.getKey()).thenReturn("branchKey"); when(sourceBranchDto.getMergeBranchUuid()).thenReturn("mergeBranchUuid"); when(sourceBranchDto.getProjectUuid()).thenReturn("projectUuid"); when(sourceBranchDto.getUuid()).thenReturn("branchUuid"); - BranchDto targetBranchDto = mock(BranchDto.class); + BranchDto targetBranchDto = mock(); when(targetBranchDto.getBranchType()).thenReturn(BranchType.BRANCH); when(targetBranchDto.getKey()).thenReturn("targetBranchKey"); when(targetBranchDto.getMergeBranchUuid()).thenReturn("targetMergeBranchUuid"); when(targetBranchDto.getProjectUuid()).thenReturn("projectUuid"); when(targetBranchDto.getUuid()).thenReturn("targetBranchUuid"); - BranchDao branchDao = mock(BranchDao.class); + BranchDao branchDao = mock(); when(branchDao.selectByBranchKey(any(), eq("projectUuid"), eq("branch"))) .thenReturn(Optional.of(sourceBranchDto)); when(branchDao.selectByBranchKey(any(), eq("projectUuid"), eq("mergeBranchName"))) @@ -290,14 +276,14 @@ public void testBranchNameMatchingBranchWithTargetBranch() { testCase.load(metadata); - ArgumentCaptor branchArgumentCaptor = ArgumentCaptor.forClass(Branch.class); + ArgumentCaptor branchArgumentCaptor = ArgumentCaptor.captor(); verify(metadataHolder).setBranch(branchArgumentCaptor.capture()); - assertEquals(BranchType.BRANCH, branchArgumentCaptor.getValue().getType()); - assertEquals("targetBranchUuid", branchArgumentCaptor.getValue().getReferenceBranchUuid()); - assertEquals("branch", branchArgumentCaptor.getValue().getName()); - assertFalse(branchArgumentCaptor.getValue().isMain()); - assertFalse(branchArgumentCaptor.getValue().supportsCrossProjectCpd()); + assertThat(branchArgumentCaptor.getValue().getType()).isEqualTo(BranchType.BRANCH); + assertThat(branchArgumentCaptor.getValue().getReferenceBranchUuid()).isEqualTo("targetBranchUuid"); + assertThat(branchArgumentCaptor.getValue().getName()).isEqualTo("branch"); + assertThat(branchArgumentCaptor.getValue().isMain()).isFalse(); + assertThat(branchArgumentCaptor.getValue().supportsCrossProjectCpd()).isFalse(); verify(metadataHolder).getProject(); @@ -314,15 +300,15 @@ public void testBranchNameMatchingBranchWithTargetBranch() { } @Test - public void testBranchNameMatchingBranchWithTargetBranchMissingTargetBranch() { - BranchDto sourceBranchDto = mock(BranchDto.class); + void testBranchNameMatchingBranchWithTargetBranchMissingTargetBranch() { + BranchDto sourceBranchDto = mock(); when(sourceBranchDto.getBranchType()).thenReturn(BranchType.BRANCH); when(sourceBranchDto.getKey()).thenReturn("branchKey"); when(sourceBranchDto.getMergeBranchUuid()).thenReturn("mergeBranchUuid"); when(sourceBranchDto.getProjectUuid()).thenReturn("projectUuid"); when(sourceBranchDto.getUuid()).thenReturn("branchUuid"); - BranchDao branchDao = mock(BranchDao.class); + BranchDao branchDao = mock(); when(branchDao.selectByBranchKey(any(), eq("projectUuid"), eq("branch"))) .thenReturn(Optional.of(sourceBranchDto)); when(branchDao.selectByBranchKey(any(), eq("projectUuid"), eq("mergeBranchName"))).thenReturn(Optional.empty()); @@ -337,11 +323,10 @@ public void testBranchNameMatchingBranchWithTargetBranchMissingTargetBranch() { when(metadataHolder.getProject()).thenReturn(new Project("projectUuid", "key", "name", "description", new ArrayList<>())); - - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage(IsEqual.equalTo("Could not find target branch 'mergeBranchName' in project")); - - testCase.load(metadata); + assertThatThrownBy(() -> testCase.load(metadata)) + .isExactlyInstanceOf(IllegalStateException.class) + .hasMessage("Could not find target branch 'mergeBranchName' in project") + .hasNoCause(); } } diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/AnalysisDetailsTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/AnalysisDetailsTest.java index 3e4a50ffd..dfd26a54d 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/AnalysisDetailsTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/AnalysisDetailsTest.java @@ -49,9 +49,9 @@ class AnalysisDetailsTest { @Test void shouldReturnStatusFromQualityGate() { - QualityGate qualityGate = mock(QualityGate.class); + QualityGate qualityGate = mock(); doReturn(QualityGate.Status.ERROR).when(qualityGate).getStatus(); - PostProjectAnalysisTask.ProjectAnalysis projectAnalysis = mock(PostProjectAnalysisTask.ProjectAnalysis.class); + PostProjectAnalysisTask.ProjectAnalysis projectAnalysis = mock(); AnalysisDetails testCase = new AnalysisDetails("pullRequestKey", "commitHash", new ArrayList<>(), qualityGate, projectAnalysis); @@ -61,9 +61,9 @@ void shouldReturnStatusFromQualityGate() { @Test void shouldGetDateFromAnalysis() { - QualityGate qualityGate = mock(QualityGate.class); - Analysis analysis = mock(Analysis.class); - PostProjectAnalysisTask.ProjectAnalysis projectAnalysis = mock(PostProjectAnalysisTask.ProjectAnalysis.class); + QualityGate qualityGate = mock(); + Analysis analysis = mock(); + PostProjectAnalysisTask.ProjectAnalysis projectAnalysis = mock(); doReturn(Optional.of(analysis)).when(projectAnalysis).getAnalysis(); doReturn(new Date()).when(analysis).getDate(); @@ -75,9 +75,9 @@ void shouldGetDateFromAnalysis() { @Test void shouldGetIdFromAnalysis() { - QualityGate qualityGate = mock(QualityGate.class); - Analysis analysis = mock(Analysis.class); - PostProjectAnalysisTask.ProjectAnalysis projectAnalysis = mock(PostProjectAnalysisTask.ProjectAnalysis.class); + QualityGate qualityGate = mock(); + Analysis analysis = mock(); + PostProjectAnalysisTask.ProjectAnalysis projectAnalysis = mock(); doReturn(Optional.of(analysis)).when(projectAnalysis).getAnalysis(); doReturn("Analysis ID").when(analysis).getAnalysisUuid(); @@ -89,9 +89,9 @@ void shouldGetIdFromAnalysis() { @Test void shouldGetProjectKeyFromUnderlyingProject() { - QualityGate qualityGate = mock(QualityGate.class); - PostProjectAnalysisTask.ProjectAnalysis projectAnalysis = mock(PostProjectAnalysisTask.ProjectAnalysis.class); - Project project = mock(Project.class); + QualityGate qualityGate = mock(); + PostProjectAnalysisTask.ProjectAnalysis projectAnalysis = mock(); + Project project = mock(); when(project.getKey()).thenReturn("Project Key"); when(projectAnalysis.getProject()).thenReturn(project); @@ -103,9 +103,9 @@ void shouldGetProjectKeyFromUnderlyingProject() { @Test void shouldGetProjectNameFromUnderlyingProject() { - QualityGate qualityGate = mock(QualityGate.class); - PostProjectAnalysisTask.ProjectAnalysis projectAnalysis = mock(PostProjectAnalysisTask.ProjectAnalysis.class); - Project project = mock(Project.class); + QualityGate qualityGate = mock(); + PostProjectAnalysisTask.ProjectAnalysis projectAnalysis = mock(); + Project project = mock(); when(project.getName()).thenReturn("Project Name"); when(projectAnalysis.getProject()).thenReturn(project); @@ -117,85 +117,85 @@ void shouldGetProjectNameFromUnderlyingProject() { @Test void shouldOnlyReturnNonClosedFileIssuesWithScmInfo() { - PostAnalysisIssueVisitor.LightIssue lightIssue1 = mock(PostAnalysisIssueVisitor.LightIssue.class); + PostAnalysisIssueVisitor.LightIssue lightIssue1 = mock(); when(lightIssue1.issueStatus()).thenReturn(IssueStatus.OPEN); - Component component1 = mock(Component.class); + Component component1 = mock(); when(component1.getType()).thenReturn(Component.Type.FILE); - ReportAttributes reportAttributes1 = mock(ReportAttributes.class); + ReportAttributes reportAttributes1 = mock(); when(reportAttributes1.getScmPath()).thenReturn(Optional.of("path")); when(component1.getReportAttributes()).thenReturn(reportAttributes1); PostAnalysisIssueVisitor.ComponentIssue componentIssue1 = new PostAnalysisIssueVisitor.ComponentIssue(component1, lightIssue1); - PostAnalysisIssueVisitor.LightIssue lightIssue2 = mock(PostAnalysisIssueVisitor.LightIssue.class); + PostAnalysisIssueVisitor.LightIssue lightIssue2 = mock(); when(lightIssue2.issueStatus()).thenReturn(IssueStatus.OPEN); - Component component2 = mock(Component.class); + Component component2 = mock(); when(component2.getType()).thenReturn(Component.Type.FILE); - ReportAttributes reportAttributes2 = mock(ReportAttributes.class); + ReportAttributes reportAttributes2 = mock(); when(reportAttributes2.getScmPath()).thenReturn(Optional.empty()); when(component2.getReportAttributes()).thenReturn(reportAttributes2); PostAnalysisIssueVisitor.ComponentIssue componentIssue2 = new PostAnalysisIssueVisitor.ComponentIssue(component2, lightIssue2); - PostAnalysisIssueVisitor.LightIssue lightIssue3 = mock(PostAnalysisIssueVisitor.LightIssue.class); + PostAnalysisIssueVisitor.LightIssue lightIssue3 = mock(); when(lightIssue3.issueStatus()).thenReturn(IssueStatus.OPEN); - Component component3 = mock(Component.class); + Component component3 = mock(); when(component3.getType()).thenReturn(Component.Type.PROJECT); - ReportAttributes reportAttributes3 = mock(ReportAttributes.class); + ReportAttributes reportAttributes3 = mock(); when(reportAttributes3.getScmPath()).thenReturn(Optional.of("path")); when(component3.getReportAttributes()).thenReturn(reportAttributes3); PostAnalysisIssueVisitor.ComponentIssue componentIssue3 = new PostAnalysisIssueVisitor.ComponentIssue(component3, lightIssue3); - PostAnalysisIssueVisitor.LightIssue lightIssue4 = mock(PostAnalysisIssueVisitor.LightIssue.class); + PostAnalysisIssueVisitor.LightIssue lightIssue4 = mock(); when(lightIssue4.issueStatus()).thenReturn(IssueStatus.FIXED); - Component component4 = mock(Component.class); + Component component4 = mock(); when(component4.getType()).thenReturn(Component.Type.FILE); - ReportAttributes reportAttributes4 = mock(ReportAttributes.class); + ReportAttributes reportAttributes4 = mock(); when(reportAttributes4.getScmPath()).thenReturn(Optional.of("path")); when(component4.getReportAttributes()).thenReturn(reportAttributes4); PostAnalysisIssueVisitor.ComponentIssue componentIssue4 = new PostAnalysisIssueVisitor.ComponentIssue(component4, lightIssue4); - PostAnalysisIssueVisitor postAnalysisIssueVisitor = mock(PostAnalysisIssueVisitor.class); + PostAnalysisIssueVisitor postAnalysisIssueVisitor = mock(); when(postAnalysisIssueVisitor.getIssues()).thenReturn(Arrays.asList(componentIssue1, componentIssue2, componentIssue3, componentIssue4)); AnalysisDetails underTest = new AnalysisDetails("pullRequest", "commmitId", Arrays.asList(componentIssue1, componentIssue2, componentIssue3, componentIssue4), - mock(QualityGate.class), mock(PostProjectAnalysisTask.ProjectAnalysis.class)); + mock(), mock()); assertThat(underTest.getScmReportableIssues()).usingRecursiveFieldByFieldElementComparator().containsOnly(componentIssue1); } @Test void shouldOnlyReturnQualityGateConditionsInErrorState() { - QualityGate qualityGate = mock(QualityGate.class); + QualityGate qualityGate = mock(); - QualityGate.Condition condition1 = mock(QualityGate.Condition.class); + QualityGate.Condition condition1 = mock(); when(condition1.getStatus()).thenReturn(QualityGate.EvaluationStatus.OK); - QualityGate.Condition condition2 = mock(QualityGate.Condition.class); + QualityGate.Condition condition2 = mock(); when(condition2.getStatus()).thenReturn(QualityGate.EvaluationStatus.ERROR); - QualityGate.Condition condition3 = mock(QualityGate.Condition.class); + QualityGate.Condition condition3 = mock(); when(condition3.getStatus()).thenReturn(QualityGate.EvaluationStatus.NO_VALUE); - QualityGate.Condition condition4 = mock(QualityGate.Condition.class); + QualityGate.Condition condition4 = mock(); when(condition4.getStatus()).thenReturn(QualityGate.EvaluationStatus.ERROR); when(qualityGate.getConditions()).thenReturn(List.of(condition1, condition2, condition3, condition4)); - AnalysisDetails underTest = new AnalysisDetails("pullRequest", "commit", List.of(), qualityGate, mock(PostProjectAnalysisTask.ProjectAnalysis.class)); + AnalysisDetails underTest = new AnalysisDetails("pullRequest", "commit", List.of(), qualityGate, mock()); assertThat(underTest.findFailedQualityGateConditions()).isEqualTo(List.of(condition2, condition4)); } @Test void shouldFilterOnQualityGateConditionName() { - QualityGate qualityGate = mock(QualityGate.class); + QualityGate qualityGate = mock(); List conditions = IntStream.range(0, 10).mapToObj(i -> { - QualityGate.Condition condition = mock(QualityGate.Condition.class); + QualityGate.Condition condition = mock(); when(condition.getMetricKey()).thenReturn("key" + i); return condition; }).collect(Collectors.toList()); when(qualityGate.getConditions()).thenReturn(conditions); - AnalysisDetails underTest = new AnalysisDetails("pullRequest", "commit", List.of(), qualityGate, mock(PostProjectAnalysisTask.ProjectAnalysis.class)); + AnalysisDetails underTest = new AnalysisDetails("pullRequest", "commit", List.of(), qualityGate, mock()); assertThat(underTest.findQualityGateCondition("key2")).contains(conditions.get(2)); } @@ -205,12 +205,12 @@ void shouldRetrievePropertyFromScannerProperties() { Map scannerProperties = mock(); when(scannerProperties.get(anyString())).thenReturn("world"); - ScannerContext scannerContext = mock(ScannerContext.class); + ScannerContext scannerContext = mock(); when(scannerContext.getProperties()).thenReturn(scannerProperties); - PostProjectAnalysisTask.ProjectAnalysis projectAnalysis = mock(PostProjectAnalysisTask.ProjectAnalysis.class); + PostProjectAnalysisTask.ProjectAnalysis projectAnalysis = mock(); when(projectAnalysis.getScannerContext()).thenReturn(scannerContext); - AnalysisDetails underTest = new AnalysisDetails("PullRequest", "Commit", List.of(), mock(QualityGate.class), projectAnalysis); + AnalysisDetails underTest = new AnalysisDetails("PullRequest", "Commit", List.of(), mock(), projectAnalysis); assertThat(underTest.getScannerProperty("hello")).contains("world"); @@ -219,7 +219,7 @@ void shouldRetrievePropertyFromScannerProperties() { @Test void shouldReturnPullRequestId() { - AnalysisDetails underTest = new AnalysisDetails("pull-request-id", "commit-id", List.of(), mock(QualityGate.class), mock(PostProjectAnalysisTask.ProjectAnalysis.class)); + AnalysisDetails underTest = new AnalysisDetails("pull-request-id", "commit-id", List.of(), mock(), mock()); assertThat(underTest.getPullRequestId()).isEqualTo("pull-request-id"); } @@ -227,7 +227,7 @@ void shouldReturnPullRequestId() { @Test void shouldReturnCommitSha() { - AnalysisDetails underTest = new AnalysisDetails("pull-request-id", "commit-id", List.of(), mock(QualityGate.class), mock(PostProjectAnalysisTask.ProjectAnalysis.class)); + AnalysisDetails underTest = new AnalysisDetails("pull-request-id", "commit-id", List.of(), mock(), mock()); assertThat(underTest.getCommitSha()).isEqualTo("commit-id"); } diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/PostAnalysisIssueVisitorTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/PostAnalysisIssueVisitorTest.java index 2997f331b..53f36c84b 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/PostAnalysisIssueVisitorTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/PostAnalysisIssueVisitorTest.java @@ -19,8 +19,6 @@ package com.github.mc1arke.sonarqube.plugin.ce.pullrequest; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -32,7 +30,7 @@ import java.util.Map; import java.util.Optional; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.sonar.api.issue.IssueStatus; import org.sonar.api.issue.impact.Severity; import org.sonar.api.issue.impact.SoftwareQuality; @@ -42,7 +40,7 @@ import org.sonar.core.issue.DefaultIssue; import org.sonar.db.protobuf.DbIssues; -public class PostAnalysisIssueVisitorTest { +class PostAnalysisIssueVisitorTest { private static final String EXAMPLE_ISSUE_KEY = "key"; private static final int EXAMPLE_ISSUE_LINE = 1000; @@ -54,13 +52,13 @@ public class PostAnalysisIssueVisitorTest { private static final DbIssues.Locations EXAMPLE_ISSUE_LOCATIONS = DbIssues.Locations.getDefaultInstance(); @Test - public void checkAllIssuesCollected() { + void checkAllIssuesCollected() { PostAnalysisIssueVisitor testCase = new PostAnalysisIssueVisitor(); List expected = new ArrayList<>(); for (int i = 0; i < 100; i++) { - DefaultIssue issue = mock(DefaultIssue.class); - Component component = mock(Component.class); + DefaultIssue issue = mock(); + Component component = mock(); expected.add(new PostAnalysisIssueVisitor.ComponentIssue(component, new PostAnalysisIssueVisitor.LightIssue(issue))); testCase.onIssue(component, issue); @@ -75,7 +73,7 @@ public void checkAllIssuesCollected() { } private DefaultIssue exampleDefaultIssue() { - DefaultIssue defaultIssue = mock(DefaultIssue.class); + DefaultIssue defaultIssue = mock(); when(defaultIssue.key()).thenReturn(EXAMPLE_ISSUE_KEY); when(defaultIssue.getLine()).thenReturn(EXAMPLE_ISSUE_LINE); when(defaultIssue.getMessage()).thenReturn(EXAMPLE_ISSUE_MESSAGE); @@ -88,10 +86,10 @@ private DefaultIssue exampleDefaultIssue() { } @Test - public void testLightIssueMapping() { + void testLightIssueMapping() { // mock a DefaultIssue DefaultIssue defaultIssue = exampleDefaultIssue(); - Component component = mock(Component.class); + Component component = mock(); // map the DefaultIssue into a LightIssue (using PostAnalysisIssueVisitor to workaround private constructor) PostAnalysisIssueVisitor visitor = new PostAnalysisIssueVisitor(); @@ -123,9 +121,9 @@ public void testLightIssueMapping() { } @Test - public void testEqualLightIssues() { + void shouldReturnEqualsForSameIssueContents() { DefaultIssue defaultIssue = exampleDefaultIssue(); - Component component = mock(Component.class); + Component component = mock(); // map the DefaultIssue into two equal LightIssues PostAnalysisIssueVisitor visitor = new PostAnalysisIssueVisitor(); @@ -135,18 +133,18 @@ public void testEqualLightIssues() { PostAnalysisIssueVisitor.LightIssue lightIssue2 = visitor.getIssues().get(1).getIssue(); // assert equality - assertEquals(lightIssue1, lightIssue2); - assertEquals(lightIssue1.hashCode(), lightIssue2.hashCode()); + assertThat(lightIssue1).isEqualTo(lightIssue2) + .hasSameHashCodeAs(lightIssue2) // also assert equality on identity - assertEquals(lightIssue1, lightIssue1); - assertEquals(lightIssue1.hashCode(), lightIssue1.hashCode()); + .isEqualTo(lightIssue1) + .hasSameHashCodeAs(lightIssue1); } @Test - public void testDifferentLightIssues() { + void shouldNotReturnEqualsForDifferentIssueContents() { DefaultIssue defaultIssue = exampleDefaultIssue(); - Component component = mock(Component.class); + Component component = mock(); // map the DefaultIssue into a first LightIssue PostAnalysisIssueVisitor visitor = new PostAnalysisIssueVisitor(); @@ -159,52 +157,52 @@ public void testDifferentLightIssues() { PostAnalysisIssueVisitor.LightIssue lightIssue2 = visitor.getIssues().get(1).getIssue(); // assert difference - assertNotEquals(lightIssue1, lightIssue2); - assertNotEquals(lightIssue1.hashCode(), lightIssue2.hashCode()); + assertThat(lightIssue1).isNotEqualTo(lightIssue2) + .doesNotHaveSameHashCodeAs(lightIssue2) // also assert difference with unrelated objects, and null - assertNotEquals(lightIssue1, new Object()); - assertNotEquals(lightIssue1, null); + .isNotEqualTo(new Object()) + .isNotEqualTo(null); } @Test - public void shouldReturnScmInfoForFileComponent() { - Component component = mock(Component.class); + void shouldReturnScmInfoForFileComponent() { + Component component = mock(); when(component.getType()).thenReturn(Component.Type.FILE); - ReportAttributes reportAttributes = mock(ReportAttributes.class); + ReportAttributes reportAttributes = mock(); when(reportAttributes.getScmPath()).thenReturn(Optional.of("path")); when(component.getReportAttributes()).thenReturn(reportAttributes); - PostAnalysisIssueVisitor.LightIssue issue = mock(PostAnalysisIssueVisitor.LightIssue.class); + PostAnalysisIssueVisitor.LightIssue issue = mock(); PostAnalysisIssueVisitor.ComponentIssue underTest = new PostAnalysisIssueVisitor.ComponentIssue(component, issue); assertThat(underTest.getScmPath()).contains("path"); } @Test - public void shouldReturnNoScmInfoForNonFileComponent() { - Component component = mock(Component.class); + void shouldReturnNoScmInfoForNonFileComponent() { + Component component = mock(); when(component.getType()).thenReturn(Component.Type.PROJECT); - ReportAttributes reportAttributes = mock(ReportAttributes.class); + ReportAttributes reportAttributes = mock(); when(reportAttributes.getScmPath()).thenReturn(Optional.of("path")); when(component.getReportAttributes()).thenReturn(reportAttributes); - PostAnalysisIssueVisitor.LightIssue issue = mock(PostAnalysisIssueVisitor.LightIssue.class); + PostAnalysisIssueVisitor.LightIssue issue = mock(); PostAnalysisIssueVisitor.ComponentIssue underTest = new PostAnalysisIssueVisitor.ComponentIssue(component, issue); assertThat(underTest.getScmPath()).isEmpty(); } @Test - public void shouldReturnNoScmInfoForFileComponentWithNoInfo() { - Component component = mock(Component.class); + void shouldReturnNoScmInfoForFileComponentWithNoInfo() { + Component component = mock(); when(component.getType()).thenReturn(Component.Type.FILE); - ReportAttributes reportAttributes = mock(ReportAttributes.class); + ReportAttributes reportAttributes = mock(); when(reportAttributes.getScmPath()).thenReturn(Optional.empty()); when(component.getReportAttributes()).thenReturn(reportAttributes); - PostAnalysisIssueVisitor.LightIssue issue = mock(PostAnalysisIssueVisitor.LightIssue.class); + PostAnalysisIssueVisitor.LightIssue issue = mock(); PostAnalysisIssueVisitor.ComponentIssue underTest = new PostAnalysisIssueVisitor.ComponentIssue(component, issue); assertThat(underTest.getScmPath()).isEmpty(); diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/PullRequestFixedIssuesIssueVisitorTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/PullRequestFixedIssuesIssueVisitorTest.java index 42e6aceef..e7a7bfb6b 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/PullRequestFixedIssuesIssueVisitorTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/PullRequestFixedIssuesIssueVisitorTest.java @@ -119,7 +119,7 @@ void shouldPassFixedAndRemovedIssuesToRepository() { } private static DefaultIssue mockIssue(IssueStatus issueStatus) { - DefaultIssue issue = mock(DefaultIssue.class); + DefaultIssue issue = mock(); when(issue.issueStatus()).thenReturn(issueStatus); return issue; } diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/PullRequestPostAnalysisTaskTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/PullRequestPostAnalysisTaskTest.java index e1bc20be6..908926443 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/PullRequestPostAnalysisTaskTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/PullRequestPostAnalysisTaskTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2020-2022 Michael Clarke + * Copyright (C) 2020-2024 Michael Clarke * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -59,16 +59,17 @@ class PullRequestPostAnalysisTaskTest { - private final PostProjectAnalysisTask.ProjectAnalysis projectAnalysis = mock(PostProjectAnalysisTask.ProjectAnalysis.class); - private final Branch branch = mock(Branch.class); - private final ScannerContext scannerContext = mock(ScannerContext.class); + private final PostProjectAnalysisTask.ProjectAnalysis projectAnalysis = mock(); + private final Branch branch = mock(); + private final ScannerContext scannerContext = mock(); private final List pullRequestBuildStatusDecorators = new ArrayList<>(); - private final PostAnalysisIssueVisitor postAnalysisIssueVisitor = mock(PostAnalysisIssueVisitor.class); - private final PostProjectAnalysisTask.Context context = mock(PostProjectAnalysisTask.Context.class); - private final DbClient dbClient = mock(DbClient.class); - private final Project project = mock(Project.class); - private final List componentIssues = List.of(mock(PostAnalysisIssueVisitor.ComponentIssue.class)); + private final PostAnalysisIssueVisitor postAnalysisIssueVisitor = mock(); + private final PostProjectAnalysisTask.Context context = mock(); + private final DbClient dbClient = mock(); + private final Project project = mock(); + private final PostAnalysisIssueVisitor.ComponentIssue componentIssue = mock(); + private final List componentIssues = List.of(componentIssue); private final PullRequestPostAnalysisTask testCase = new PullRequestPostAnalysisTask(pullRequestBuildStatusDecorators, @@ -110,19 +111,19 @@ void testFinishedNoProviderSet() { doReturn(Branch.Type.PULL_REQUEST).when(branch).getType(); doReturn(Optional.of("branchName")).when(branch).getName(); - ProjectAlmSettingDto projectAlmSettingDto = mock(ProjectAlmSettingDto.class); + ProjectAlmSettingDto projectAlmSettingDto = mock(); when(projectAlmSettingDto.getAlmSlug()).thenReturn("dummy/repo"); when(projectAlmSettingDto.getAlmSettingUuid()).thenReturn("almUuid"); - AlmSettingDto almSettingDto = mock(AlmSettingDto.class); + AlmSettingDto almSettingDto = mock(); when(almSettingDto.getUrl()).thenReturn("http://host.name"); when(almSettingDto.getAppId()).thenReturn("app id"); when(almSettingDto.getDecryptedPrivateKey(any())).thenReturn("private key"); when(almSettingDto.getAlm()).thenReturn(ALM.GITHUB); - when(dbClient.openSession(anyBoolean())).thenReturn(mock(DbSession.class)); - AlmSettingDao almSettingDao = mock(AlmSettingDao.class); + when(dbClient.openSession(anyBoolean())).thenReturn(mock()); + AlmSettingDao almSettingDao = mock(); when(almSettingDao.selectByUuid(any(), any())).thenReturn(Optional.of(almSettingDto)); when(dbClient.almSettingDao()).thenReturn(almSettingDao); - ProjectAlmSettingDao projectAlmSettingDao = mock(ProjectAlmSettingDao.class); + ProjectAlmSettingDao projectAlmSettingDao = mock(); when(projectAlmSettingDao.selectByProject(any(), anyString())).thenReturn(Optional.of(projectAlmSettingDto)); when(dbClient.projectAlmSettingDao()).thenReturn(projectAlmSettingDao); @@ -138,27 +139,27 @@ void testFinishedNoProviderMatchingName() { doReturn(Branch.Type.PULL_REQUEST).when(branch).getType(); doReturn(Optional.of("branchName")).when(branch).getName(); - PullRequestBuildStatusDecorator decorator1 = mock(PullRequestBuildStatusDecorator.class); + PullRequestBuildStatusDecorator decorator1 = mock(); doReturn(Collections.singletonList(ALM.BITBUCKET)).when(decorator1).alm(); pullRequestBuildStatusDecorators.add(decorator1); - PullRequestBuildStatusDecorator decorator2 = mock(PullRequestBuildStatusDecorator.class); + PullRequestBuildStatusDecorator decorator2 = mock(); doReturn(Collections.singletonList(ALM.GITHUB)).when(decorator2).alm(); pullRequestBuildStatusDecorators.add(decorator2); - ProjectAlmSettingDto projectAlmSettingDto = mock(ProjectAlmSettingDto.class); + ProjectAlmSettingDto projectAlmSettingDto = mock(); when(projectAlmSettingDto.getAlmSlug()).thenReturn("dummy/repo"); when(projectAlmSettingDto.getAlmSettingUuid()).thenReturn("almUuid"); - AlmSettingDto almSettingDto = mock(AlmSettingDto.class); + AlmSettingDto almSettingDto = mock(); when(almSettingDto.getUrl()).thenReturn("http://host.name"); when(almSettingDto.getAppId()).thenReturn("app id"); when(almSettingDto.getDecryptedPrivateKey(any())).thenReturn("private key"); when(almSettingDto.getAlm()).thenReturn(ALM.AZURE_DEVOPS); - when(dbClient.openSession(anyBoolean())).thenReturn(mock(DbSession.class)); - AlmSettingDao almSettingDao = mock(AlmSettingDao.class); + when(dbClient.openSession(anyBoolean())).thenReturn(mock()); + AlmSettingDao almSettingDao = mock(); when(almSettingDao.selectByUuid(any(), any())).thenReturn(Optional.of(almSettingDto)); when(dbClient.almSettingDao()).thenReturn(almSettingDao); - ProjectAlmSettingDao projectAlmSettingDao = mock(ProjectAlmSettingDao.class); + ProjectAlmSettingDao projectAlmSettingDao = mock(); when(projectAlmSettingDao.selectByProject(any(), anyString())).thenReturn(Optional.of(projectAlmSettingDto)); when(dbClient.projectAlmSettingDao()).thenReturn(projectAlmSettingDao); @@ -176,27 +177,27 @@ void testFinishedNoAnalysis() { doReturn(Optional.empty()).when(projectAnalysis).getAnalysis(); - PullRequestBuildStatusDecorator decorator1 = mock(PullRequestBuildStatusDecorator.class); + PullRequestBuildStatusDecorator decorator1 = mock(); doReturn(Collections.singletonList(ALM.AZURE_DEVOPS)).when(decorator1).alm(); pullRequestBuildStatusDecorators.add(decorator1); - PullRequestBuildStatusDecorator decorator2 = mock(PullRequestBuildStatusDecorator.class); + PullRequestBuildStatusDecorator decorator2 = mock(); doReturn(Collections.singletonList(ALM.GITHUB)).when(decorator2).alm(); pullRequestBuildStatusDecorators.add(decorator2); - ProjectAlmSettingDto projectAlmSettingDto = mock(ProjectAlmSettingDto.class); + ProjectAlmSettingDto projectAlmSettingDto = mock(); when(projectAlmSettingDto.getAlmSlug()).thenReturn("dummy/repo"); when(projectAlmSettingDto.getAlmSettingUuid()).thenReturn("almUuid"); - AlmSettingDto almSettingDto = mock(AlmSettingDto.class); + AlmSettingDto almSettingDto = mock(); when(almSettingDto.getUrl()).thenReturn("http://host.name"); when(almSettingDto.getAppId()).thenReturn("app id"); when(almSettingDto.getDecryptedPrivateKey(any())).thenReturn("private key"); when(almSettingDto.getAlm()).thenReturn(ALM.GITHUB); - when(dbClient.openSession(anyBoolean())).thenReturn(mock(DbSession.class)); - AlmSettingDao almSettingDao = mock(AlmSettingDao.class); + when(dbClient.openSession(anyBoolean())).thenReturn(mock()); + AlmSettingDao almSettingDao = mock(); when(almSettingDao.selectByUuid(any(), any())).thenReturn(Optional.of(almSettingDto)); when(dbClient.almSettingDao()).thenReturn(almSettingDao); - ProjectAlmSettingDao projectAlmSettingDao = mock(ProjectAlmSettingDao.class); + ProjectAlmSettingDao projectAlmSettingDao = mock(); when(projectAlmSettingDao.selectByProject(any(), anyString())).thenReturn(Optional.of(projectAlmSettingDto)); when(dbClient.projectAlmSettingDao()).thenReturn(projectAlmSettingDao); @@ -212,31 +213,31 @@ void testFinishedAnalysisWithNoRevision() { doReturn(Branch.Type.PULL_REQUEST).when(branch).getType(); doReturn(Optional.of("pull-request")).when(branch).getName(); - Analysis analysis = mock(Analysis.class); + Analysis analysis = mock(); doReturn(Optional.empty()).when(analysis).getRevision(); doReturn(Optional.of(analysis)).when(projectAnalysis).getAnalysis(); - PullRequestBuildStatusDecorator decorator1 = mock(PullRequestBuildStatusDecorator.class); + PullRequestBuildStatusDecorator decorator1 = mock(); doReturn(Collections.singletonList(ALM.BITBUCKET)).when(decorator1).alm(); pullRequestBuildStatusDecorators.add(decorator1); - PullRequestBuildStatusDecorator decorator2 = mock(PullRequestBuildStatusDecorator.class); + PullRequestBuildStatusDecorator decorator2 = mock(); doReturn(Collections.singletonList(ALM.GITHUB)).when(decorator2).alm(); pullRequestBuildStatusDecorators.add(decorator2); - ProjectAlmSettingDto projectAlmSettingDto = mock(ProjectAlmSettingDto.class); + ProjectAlmSettingDto projectAlmSettingDto = mock(); when(projectAlmSettingDto.getAlmSlug()).thenReturn("dummy/repo"); when(projectAlmSettingDto.getAlmSettingUuid()).thenReturn("almUuid"); - AlmSettingDto almSettingDto = mock(AlmSettingDto.class); + AlmSettingDto almSettingDto = mock(); when(almSettingDto.getUrl()).thenReturn("http://host.name"); when(almSettingDto.getAppId()).thenReturn("app id"); when(almSettingDto.getDecryptedPrivateKey(any())).thenReturn("private key"); when(almSettingDto.getAlm()).thenReturn(ALM.GITHUB); - when(dbClient.openSession(anyBoolean())).thenReturn(mock(DbSession.class)); - AlmSettingDao almSettingDao = mock(AlmSettingDao.class); + when(dbClient.openSession(anyBoolean())).thenReturn(mock()); + AlmSettingDao almSettingDao = mock(); when(almSettingDao.selectByUuid(any(), any())).thenReturn(Optional.of(almSettingDto)); when(dbClient.almSettingDao()).thenReturn(almSettingDao); - ProjectAlmSettingDao projectAlmSettingDao = mock(ProjectAlmSettingDao.class); + ProjectAlmSettingDao projectAlmSettingDao = mock(); when(projectAlmSettingDao.selectByProject(any(), anyString())).thenReturn(Optional.of(projectAlmSettingDto)); when(dbClient.projectAlmSettingDao()).thenReturn(projectAlmSettingDao); @@ -252,34 +253,33 @@ void testFinishedAnalysisWithNoQualityGate() { doReturn(Branch.Type.PULL_REQUEST).when(branch).getType(); doReturn(Optional.of("pull-request")).when(branch).getName(); - Analysis analysis = mock(Analysis.class); + Analysis analysis = mock(); doReturn(Optional.of("revision")).when(analysis).getRevision(); doReturn(Optional.of(analysis)).when(projectAnalysis).getAnalysis(); - ProjectAlmSettingDto projectAlmSettingDto = mock(ProjectAlmSettingDto.class); + ProjectAlmSettingDto projectAlmSettingDto = mock(); when(projectAlmSettingDto.getAlmSlug()).thenReturn("dummy/repo"); when(projectAlmSettingDto.getAlmSettingUuid()).thenReturn("almUuid"); - AlmSettingDto almSettingDto = mock(AlmSettingDto.class); + AlmSettingDto almSettingDto = mock(); when(almSettingDto.getUrl()).thenReturn("http://host.name"); when(almSettingDto.getAppId()).thenReturn("app id"); when(almSettingDto.getDecryptedPrivateKey(any())).thenReturn("private key"); when(almSettingDto.getAlm()).thenReturn(ALM.GITHUB); - when(dbClient.openSession(anyBoolean())).thenReturn(mock(DbSession.class)); - AlmSettingDao almSettingDao = mock(AlmSettingDao.class); + when(dbClient.openSession(anyBoolean())).thenReturn(mock()); + AlmSettingDao almSettingDao = mock(); when(almSettingDao.selectByUuid(any(), any())).thenReturn(Optional.of(almSettingDto)); when(dbClient.almSettingDao()).thenReturn(almSettingDao); - ProjectAlmSettingDao projectAlmSettingDao = mock(ProjectAlmSettingDao.class); + ProjectAlmSettingDao projectAlmSettingDao = mock(); when(projectAlmSettingDao.selectByProject(any(), anyString())).thenReturn(Optional.of(projectAlmSettingDto)); when(dbClient.projectAlmSettingDao()).thenReturn(projectAlmSettingDao); - ScannerContext scannerContext = mock(ScannerContext.class); doReturn(scannerContext).when(projectAnalysis).getScannerContext(); - PullRequestBuildStatusDecorator decorator1 = mock(PullRequestBuildStatusDecorator.class); + PullRequestBuildStatusDecorator decorator1 = mock(); doReturn(Collections.singletonList(ALM.GITLAB)).when(decorator1).alm(); pullRequestBuildStatusDecorators.add(decorator1); - PullRequestBuildStatusDecorator decorator2 = mock(PullRequestBuildStatusDecorator.class); + PullRequestBuildStatusDecorator decorator2 = mock(); doReturn(Collections.singletonList(ALM.GITHUB)).when(decorator2).alm(); pullRequestBuildStatusDecorators.add(decorator2); @@ -295,50 +295,49 @@ void testFinishedAnalysisDecorationRequest() { doReturn(Branch.Type.PULL_REQUEST).when(branch).getType(); doReturn(Optional.of("pull-request")).when(branch).getName(); - PostProjectAnalysisTask.Context context = mock(PostProjectAnalysisTask.Context.class); doReturn(projectAnalysis).when(context).getProjectAnalysis(); - Analysis analysis = mock(Analysis.class); + Analysis analysis = mock(); doReturn(Optional.of("revision")).when(analysis).getRevision(); doReturn(new Date()).when(analysis).getDate(); doReturn(Optional.of(analysis)).when(projectAnalysis).getAnalysis(); - QualityGate qualityGate = mock(QualityGate.class); + QualityGate qualityGate = mock(); doReturn(qualityGate).when(projectAnalysis).getQualityGate(); - PullRequestBuildStatusDecorator decorator1 = mock(PullRequestBuildStatusDecorator.class); + PullRequestBuildStatusDecorator decorator1 = mock(); doReturn(Collections.singletonList(ALM.BITBUCKET)).when(decorator1).alm(); pullRequestBuildStatusDecorators.add(decorator1); - PullRequestBuildStatusDecorator decorator2 = mock(PullRequestBuildStatusDecorator.class); + PullRequestBuildStatusDecorator decorator2 = mock(); doReturn(Collections.singletonList(ALM.GITHUB)).when(decorator2).alm(); doReturn(DecorationResult.builder().build()).when(decorator2).decorateQualityGateStatus(any(), any(), any()); pullRequestBuildStatusDecorators.add(decorator2); - ProjectAlmSettingDto projectAlmSettingDto = mock(ProjectAlmSettingDto.class); - AlmSettingDto almSettingDto = mock(AlmSettingDto.class); + ProjectAlmSettingDto projectAlmSettingDto = mock(); + AlmSettingDto almSettingDto = mock(); doReturn(ALM.GITHUB).when(almSettingDto).getAlm(); - when(dbClient.openSession(anyBoolean())).thenReturn(mock(DbSession.class)); - AlmSettingDao almSettingDao = mock(AlmSettingDao.class); + when(dbClient.openSession(anyBoolean())).thenReturn(mock()); + AlmSettingDao almSettingDao = mock(); when(almSettingDao.selectByUuid(any(), any())).thenReturn(Optional.of(almSettingDto)); when(dbClient.almSettingDao()).thenReturn(almSettingDao); - ProjectAlmSettingDao projectAlmSettingDao = mock(ProjectAlmSettingDao.class); + ProjectAlmSettingDao projectAlmSettingDao = mock(); when(projectAlmSettingDao.selectByProject(any(), anyString())).thenReturn(Optional.of(projectAlmSettingDto)); when(dbClient.projectAlmSettingDao()).thenReturn(projectAlmSettingDao); - DbSession dbSession = mock(DbSession.class); + DbSession dbSession = mock(); doReturn(dbSession).when(dbClient).openSession(anyBoolean()); - BranchDao branchDao = mock(BranchDao.class); + BranchDao branchDao = mock(); doReturn(branchDao).when(dbClient).branchDao(); - BranchDto branchDto = mock(BranchDto.class); + BranchDto branchDto = mock(); doReturn(Optional.empty()).when(branchDao).selectByPullRequestKey(any(), any(), any()); doReturn(DbProjectBranches.PullRequestData.newBuilder().build()).when(branchDto).getPullRequestData(); testCase.finished(context); - ArgumentCaptor analysisDetailsArgumentCaptor = ArgumentCaptor.forClass(AnalysisDetails.class); + ArgumentCaptor analysisDetailsArgumentCaptor = ArgumentCaptor.captor(); verify(projectAnalysis).getAnalysis(); verify(projectAnalysis).getQualityGate(); @@ -355,43 +354,42 @@ void testFinishedAnalysisDecorationRequestPullRequestLinkSaved() { doReturn(Branch.Type.PULL_REQUEST).when(branch).getType(); doReturn(Optional.of("pull-request")).when(branch).getName(); - Project project = mock(Project.class); doReturn("uuid").when(project).getUuid(); doReturn(project).when(projectAnalysis).getProject(); - Analysis analysis = mock(Analysis.class); + Analysis analysis = mock(); doReturn(Optional.of("revision")).when(analysis).getRevision(); doReturn(new Date()).when(analysis).getDate(); doReturn(Optional.of(analysis)).when(projectAnalysis).getAnalysis(); - QualityGate qualityGate = mock(QualityGate.class); + QualityGate qualityGate = mock(); doReturn(qualityGate).when(projectAnalysis).getQualityGate(); - PullRequestBuildStatusDecorator decorator1 = mock(PullRequestBuildStatusDecorator.class); + PullRequestBuildStatusDecorator decorator1 = mock(); doReturn(Collections.singletonList(ALM.GITHUB)).when(decorator1).alm(); pullRequestBuildStatusDecorators.add(decorator1); - PullRequestBuildStatusDecorator decorator2 = mock(PullRequestBuildStatusDecorator.class); + PullRequestBuildStatusDecorator decorator2 = mock(); doReturn(Collections.singletonList(ALM.BITBUCKET)).when(decorator2).alm(); doReturn(DecorationResult.builder().withPullRequestUrl("pullRequestUrl").build()).when(decorator2).decorateQualityGateStatus(any(), any(), any()); pullRequestBuildStatusDecorators.add(decorator2); - ProjectAlmSettingDto projectAlmSettingDto = mock(ProjectAlmSettingDto.class); - AlmSettingDto almSettingDto = mock(AlmSettingDto.class); + ProjectAlmSettingDto projectAlmSettingDto = mock(); + AlmSettingDto almSettingDto = mock(); doReturn(ALM.BITBUCKET).when(almSettingDto).getAlm(); - DbSession dbSession = mock(DbSession.class); + DbSession dbSession = mock(); doReturn(dbSession).when(dbClient).openSession(anyBoolean()); - BranchDao branchDao = mock(BranchDao.class); + BranchDao branchDao = mock(); doReturn(branchDao).when(dbClient).branchDao(); - BranchDto branchDto = mock(BranchDto.class); + BranchDto branchDto = mock(); doReturn(Optional.of(branchDto)).when(branchDao).selectByPullRequestKey(any(), any(), any()); doReturn(DbProjectBranches.PullRequestData.newBuilder().build()).when(branchDto).getPullRequestData(); - ProjectAlmSettingDao projectAlmSettingDao = mock(ProjectAlmSettingDao.class); + ProjectAlmSettingDao projectAlmSettingDao = mock(); doReturn(Optional.of(projectAlmSettingDto)).when(projectAlmSettingDao).selectByProject(dbSession, "uuid"); doReturn("setting-uuid").when(projectAlmSettingDto).getAlmSettingUuid(); - AlmSettingDao almSettingDao = mock(AlmSettingDao.class); + AlmSettingDao almSettingDao = mock(); doReturn(Optional.of(almSettingDto)).when(almSettingDao).selectByUuid(dbSession, "setting-uuid"); doReturn(projectAlmSettingDao).when(dbClient).projectAlmSettingDao(); @@ -399,7 +397,7 @@ void testFinishedAnalysisDecorationRequestPullRequestLinkSaved() { testCase.finished(context); - ArgumentCaptor analysisDetailsArgumentCaptor = ArgumentCaptor.forClass(AnalysisDetails.class); + ArgumentCaptor analysisDetailsArgumentCaptor = ArgumentCaptor.captor(); verify(projectAnalysis).getAnalysis(); verify(projectAnalysis).getQualityGate(); verify(dbClient, times(2)).openSession(false); @@ -407,8 +405,7 @@ void testFinishedAnalysisDecorationRequestPullRequestLinkSaved() { verify(branchDao).selectByPullRequestKey(dbSession, "uuid", "pull-request"); verify(decorator2).decorateQualityGateStatus(analysisDetailsArgumentCaptor.capture(), eq(almSettingDto), eq(projectAlmSettingDto)); - ArgumentCaptor pullRequestDataArgumentCaptor = ArgumentCaptor.forClass( - DbProjectBranches.PullRequestData.class); + ArgumentCaptor pullRequestDataArgumentCaptor = ArgumentCaptor.captor(); verify(branchDto).setPullRequestData(pullRequestDataArgumentCaptor.capture()); assertThat(pullRequestDataArgumentCaptor.getValue().getUrl()).isEqualTo("pullRequestUrl"); @@ -426,56 +423,55 @@ void testFinishedAnalysisDecorationRequestPullRequestLinkNotSavedIfBranchDtoMiss doReturn(Branch.Type.PULL_REQUEST).when(branch).getType(); doReturn(Optional.of("pull-request")).when(branch).getName(); - Project project = mock(Project.class); doReturn("uuid").when(project).getUuid(); doReturn(project).when(projectAnalysis).getProject(); - Analysis analysis = mock(Analysis.class); + Analysis analysis = mock(); doReturn(Optional.of("revision")).when(analysis).getRevision(); doReturn(new Date()).when(analysis).getDate(); doReturn(Optional.of(analysis)).when(projectAnalysis).getAnalysis(); - QualityGate qualityGate = mock(QualityGate.class); + QualityGate qualityGate = mock(); doReturn(qualityGate).when(projectAnalysis).getQualityGate(); - PullRequestBuildStatusDecorator decorator1 = mock(PullRequestBuildStatusDecorator.class); + PullRequestBuildStatusDecorator decorator1 = mock(); doReturn(Collections.singletonList(ALM.GITHUB)).when(decorator1).alm(); doReturn(DecorationResult.builder().withPullRequestUrl("pullRequestUrl").build()).when(decorator1).decorateQualityGateStatus(any(), any(), any()); pullRequestBuildStatusDecorators.add(decorator1); - PullRequestBuildStatusDecorator decorator2 = mock(PullRequestBuildStatusDecorator.class); + PullRequestBuildStatusDecorator decorator2 = mock(); pullRequestBuildStatusDecorators.add(decorator2); - ProjectAlmSettingDto projectAlmSettingDto = mock(ProjectAlmSettingDto.class); + ProjectAlmSettingDto projectAlmSettingDto = mock(); when(projectAlmSettingDto.getAlmSlug()).thenReturn("dummy/repo"); when(projectAlmSettingDto.getAlmSettingUuid()).thenReturn("almUuid"); - AlmSettingDto almSettingDto = mock(AlmSettingDto.class); + AlmSettingDto almSettingDto = mock(); when(almSettingDto.getUrl()).thenReturn("http://host.name"); when(almSettingDto.getAppId()).thenReturn("app id"); when(almSettingDto.getDecryptedPrivateKey(any())).thenReturn("private key"); when(almSettingDto.getAlm()).thenReturn(ALM.GITHUB); - when(dbClient.openSession(anyBoolean())).thenReturn(mock(DbSession.class)); - AlmSettingDao almSettingDao = mock(AlmSettingDao.class); + when(dbClient.openSession(anyBoolean())).thenReturn(mock()); + AlmSettingDao almSettingDao = mock(); when(almSettingDao.selectByUuid(any(), any())).thenReturn(Optional.of(almSettingDto)); when(dbClient.almSettingDao()).thenReturn(almSettingDao); - ProjectAlmSettingDao projectAlmSettingDao = mock(ProjectAlmSettingDao.class); + ProjectAlmSettingDao projectAlmSettingDao = mock(); when(projectAlmSettingDao.selectByProject(any(), anyString())).thenReturn(Optional.of(projectAlmSettingDto)); when(dbClient.projectAlmSettingDao()).thenReturn(projectAlmSettingDao); - DbSession dbSession = mock(DbSession.class); + DbSession dbSession = mock(); doReturn(dbSession).when(dbClient).openSession(anyBoolean()); - BranchDao branchDao = mock(BranchDao.class); + BranchDao branchDao = mock(); doReturn(branchDao).when(dbClient).branchDao(); - BranchDto branchDto = mock(BranchDto.class); + BranchDto branchDto = mock(); doReturn(Optional.empty()).when(branchDao).selectByPullRequestKey(any(), any(), any()); doReturn(DbProjectBranches.PullRequestData.newBuilder().build()).when(branchDto).getPullRequestData(); testCase.finished(context); - ArgumentCaptor analysisDetailsArgumentCaptor = ArgumentCaptor.forClass(AnalysisDetails.class); - ArgumentCaptor almSettingDtoArgumentCaptor = ArgumentCaptor.forClass(AlmSettingDto.class); + ArgumentCaptor analysisDetailsArgumentCaptor = ArgumentCaptor.captor(); + ArgumentCaptor almSettingDtoArgumentCaptor = ArgumentCaptor.captor(); ArgumentCaptor projectAlmSettingDtoArgumentCaptor = - ArgumentCaptor.forClass(ProjectAlmSettingDto.class); + ArgumentCaptor.captor(); verify(projectAnalysis).getAnalysis(); verify(projectAnalysis).getQualityGate(); diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/azuredevops/AzureDevOpsPullRequestDecoratorIntegrationTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/azuredevops/AzureDevOpsPullRequestDecoratorIntegrationTest.java index 5df561e86..7e5ddac99 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/azuredevops/AzureDevOpsPullRequestDecoratorIntegrationTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/azuredevops/AzureDevOpsPullRequestDecoratorIntegrationTest.java @@ -74,25 +74,25 @@ class AzureDevOpsPullRequestDecoratorIntegrationTest { private final String issueKeyVal = "issueKeyVal"; private final String projectName = "Project Name"; - private final ProjectAlmSettingDto projectAlmSettingDto = mock(ProjectAlmSettingDto.class); - private final AlmSettingDto almSettingDto = mock(AlmSettingDto.class); - private final ScmInfoRepository scmInfoRepository = mock(ScmInfoRepository.class); - private final Settings settings = mock(Settings.class); - private final Encryption encryption = mock(Encryption.class); - private final ReportGenerator reportGenerator = mock(ReportGenerator.class); - private final MarkdownFormatterFactory formatterFactory = mock(MarkdownFormatterFactory.class); + private final ProjectAlmSettingDto projectAlmSettingDto = mock(); + private final AlmSettingDto almSettingDto = mock(); + private final ScmInfoRepository scmInfoRepository = mock(); + private final Settings settings = mock(); + private final Encryption encryption = mock(); + private final ReportGenerator reportGenerator = mock(); + private final MarkdownFormatterFactory formatterFactory = mock(); private final AzureDevOpsPullRequestDecorator pullRequestDecorator = new AzureDevOpsPullRequestDecorator(scmInfoRepository, new DefaultAzureDevopsClientFactory(settings), reportGenerator, formatterFactory); - private final AnalysisDetails analysisDetails = mock(AnalysisDetails.class); + private final AnalysisDetails analysisDetails = mock(); - private final PostAnalysisIssueVisitor.ComponentIssue componentIssue = mock(PostAnalysisIssueVisitor.ComponentIssue.class); - private final PostAnalysisIssueVisitor.LightIssue defaultIssue = mock(PostAnalysisIssueVisitor.LightIssue.class); - private final Component component = mock(Component.class); + private final PostAnalysisIssueVisitor.ComponentIssue componentIssue = mock(); + private final PostAnalysisIssueVisitor.LightIssue defaultIssue = mock(); + private final Component component = mock(); @BeforeEach void setUp() { when(settings.getEncryption()).thenReturn(encryption); - when(reportGenerator.createAnalysisIssueSummary(any(), any())).thenReturn(mock(AnalysisIssueSummary.class)); - when(reportGenerator.createAnalysisSummary(any())).thenReturn(mock(AnalysisSummary.class)); + when(reportGenerator.createAnalysisIssueSummary(any(), any())).thenReturn(mock()); + when(reportGenerator.createAnalysisSummary(any())).thenReturn(mock()); } private void configureTestDefaults() { @@ -106,16 +106,16 @@ private void configureTestDefaults() { when(analysisDetails.getPullRequestId()).thenReturn(Integer.toString(pullRequestId)); when(analysisDetails.getIssues()).thenReturn(List.of(componentIssue)); - AnalysisSummary analysisSummary = mock(AnalysisSummary.class); + AnalysisSummary analysisSummary = mock(); when(analysisSummary.format(any())).thenReturn("analysis summary"); when(analysisSummary.getDashboardUrl()).thenReturn("http://sonar:9000/sonar/dashboard?id=" + sonarProject + "&pullRequest=" + pullRequestId); - AnalysisIssueSummary analysisIssueSummary = mock(AnalysisIssueSummary.class); + AnalysisIssueSummary analysisIssueSummary = mock(); when(reportGenerator.createAnalysisSummary(any())).thenReturn(analysisSummary); when(reportGenerator.createAnalysisIssueSummary(any(), any())).thenReturn(analysisIssueSummary); DbIssues.Locations locate = DbIssues.Locations.newBuilder().build(); - RuleKey ruleKey = mock(RuleKey.class); + RuleKey ruleKey = mock(); when(componentIssue.getIssue()).thenReturn(defaultIssue); when(componentIssue.getComponent()).thenReturn(component); when(componentIssue.getScmPath()).thenReturn(Optional.of("scmPath")); @@ -127,9 +127,9 @@ private void configureTestDefaults() { when(defaultIssue.getMessage()).thenReturn(issueMessage); when(defaultIssue.getRuleKey()).thenReturn(ruleKey); when(defaultIssue.key()).thenReturn(issueKeyVal); - Changeset changeset = mock(Changeset.class); + Changeset changeset = mock(); when(changeset.getRevision()).thenReturn("revisionId"); - ScmInfo scmInfo = mock(ScmInfo.class); + ScmInfo scmInfo = mock(); when(scmInfo.hasChangesetForLine(anyInt())).thenReturn(true); when(scmInfo.getChangesetForLine(anyInt())).thenReturn(changeset); when(scmInfoRepository.getScmInfo(component)).thenReturn(Optional.of(scmInfo)); diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/azuredevops/AzureDevOpsPullRequestDecoratorTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/azuredevops/AzureDevOpsPullRequestDecoratorTest.java index 761950165..7b713b846 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/azuredevops/AzureDevOpsPullRequestDecoratorTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/azuredevops/AzureDevOpsPullRequestDecoratorTest.java @@ -114,9 +114,9 @@ void testDecorateQualityGatePRBranchException() { void shouldRemoveUserInfoFromRepositoryUrlForLinking() { AzureDevOpsPullRequestDecorator underTest = new AzureDevOpsPullRequestDecorator(scmInfoRepository, azureDevopsClientFactory, reportGenerator, markdownFormatterFactory); - Repository repository = mock(Repository.class); + Repository repository = mock(); when(repository.getRemoteUrl()).thenReturn("https://user@domain.com/path/to/repo"); - PullRequest pullRequest = mock(PullRequest.class); + PullRequest pullRequest = mock(); when(pullRequest.getRepository()).thenReturn(repository); when(pullRequest.getId()).thenReturn(999); @@ -126,7 +126,7 @@ void shouldRemoveUserInfoFromRepositoryUrlForLinking() { @Test void testName() { - assertThat(new AzureDevOpsPullRequestDecorator(mock(ScmInfoRepository.class), mock(AzureDevopsClientFactory.class), mock(ReportGenerator.class), mock(MarkdownFormatterFactory.class)).alm()).isEqualTo(Collections.singletonList(ALM.AZURE_DEVOPS)); + assertThat(new AzureDevOpsPullRequestDecorator(mock(), mock(), mock(), mock()).alm()).isEqualTo(Collections.singletonList(ALM.AZURE_DEVOPS)); } @Test diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/bitbucket/BitbucketPullRequestDecoratorTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/bitbucket/BitbucketPullRequestDecoratorTest.java index 3eb6fc45e..3132eb36d 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/bitbucket/BitbucketPullRequestDecoratorTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/bitbucket/BitbucketPullRequestDecoratorTest.java @@ -74,15 +74,15 @@ class BitbucketPullRequestDecoratorTest { private static final String DASHBOARD_URL = "https://dashboard-url"; private static final String IMAGE_URL = "https://image-url"; - private final AnalysisDetails analysisDetails = mock(AnalysisDetails.class); - private final ReportGenerator reportGenerator = mock(ReportGenerator.class); - private final BitbucketClient client = mock(BitbucketClient.class); - private final BitbucketClientFactory bitbucketClientFactory = mock(BitbucketClientFactory.class); + private final AnalysisDetails analysisDetails = mock(); + private final ReportGenerator reportGenerator = mock(); + private final BitbucketClient client = mock(); + private final BitbucketClientFactory bitbucketClientFactory = mock(); private final BitbucketPullRequestDecorator underTest = new BitbucketPullRequestDecorator(bitbucketClientFactory, reportGenerator); - private final AlmSettingDto almSettingDto = mock(AlmSettingDto.class); - private final ProjectAlmSettingDto projectAlmSettingDto = mock(ProjectAlmSettingDto.class); - private final AnalysisSummary analysisSummary = mock(AnalysisSummary.class); + private final AlmSettingDto almSettingDto = mock(); + private final ProjectAlmSettingDto projectAlmSettingDto = mock(); + private final AnalysisSummary analysisSummary = mock(); @BeforeEach void setUp() { @@ -184,25 +184,25 @@ private void mockValidAnalysis() { when(analysisDetails.getAnalysisDate()).thenReturn(Date.from(Instant.now())); - ReportAttributes reportAttributes = mock(ReportAttributes.class); + ReportAttributes reportAttributes = mock(); when(reportAttributes.getScmPath()).thenReturn(Optional.of(ISSUE_PATH)); - Component component = mock(Component.class); + Component component = mock(); when(component.getType()).thenReturn(Component.Type.FILE); when(component.getReportAttributes()).thenReturn(reportAttributes); - PostAnalysisIssueVisitor.LightIssue defaultIssue = mock(PostAnalysisIssueVisitor.LightIssue.class); + PostAnalysisIssueVisitor.LightIssue defaultIssue = mock(); when(defaultIssue.issueStatus()).thenReturn(IssueStatus.OPEN); when(defaultIssue.impacts()).thenReturn(Map.of(SoftwareQuality.RELIABILITY, Severity.HIGH)); when(defaultIssue.getLine()).thenReturn(ISSUE_LINE); when(defaultIssue.key()).thenReturn(ISSUE_KEY); when(defaultIssue.getMessage()).thenReturn(ISSUE_MESSAGE); - PostAnalysisIssueVisitor.ComponentIssue componentIssue = mock(PostAnalysisIssueVisitor.ComponentIssue.class); + PostAnalysisIssueVisitor.ComponentIssue componentIssue = mock(); when(componentIssue.getIssue()).thenReturn(defaultIssue); when(componentIssue.getComponent()).thenReturn(component); - AnalysisIssueSummary analysisIssueSummary = mock(AnalysisIssueSummary.class); + AnalysisIssueSummary analysisIssueSummary = mock(); when(analysisIssueSummary.getIssueUrl()).thenReturn("https://issue-link"); when(reportGenerator.createAnalysisIssueSummary(any(), any())).thenReturn(analysisIssueSummary); diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/github/GithubPullRequestDecoratorTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/github/GithubPullRequestDecoratorTest.java index 883384626..585591e7e 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/github/GithubPullRequestDecoratorTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/github/GithubPullRequestDecoratorTest.java @@ -94,11 +94,11 @@ void setUp() throws IOException { when(analysisDetails.getQualityGateStatus()).thenReturn(QualityGate.Status.OK); when(analysisDetails.getCommitSha()).thenReturn("commit-sha"); List reportableIssues = IntStream.range(0, 20).mapToObj(i -> { - PostAnalysisIssueVisitor.ComponentIssue componentIssue = mock(PostAnalysisIssueVisitor.ComponentIssue.class); - Component component = mock(Component.class); + PostAnalysisIssueVisitor.ComponentIssue componentIssue = mock(); + Component component = mock(); when(componentIssue.getScmPath()).thenReturn(Optional.of("path" + i)); when(componentIssue.getComponent()).thenReturn(component); - PostAnalysisIssueVisitor.LightIssue lightIssue = mock(PostAnalysisIssueVisitor.LightIssue.class); + PostAnalysisIssueVisitor.LightIssue lightIssue = mock(); when(lightIssue.getMessage()).thenReturn("issue message " + i); when(lightIssue.getLine()).thenReturn(i); when(lightIssue.impacts()).thenReturn(Map.of(SoftwareQuality.values()[i % SoftwareQuality.values().length], Severity.values()[i % Severity.values().length])); diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/gitlab/GitlabMergeRequestDecoratorIntegrationTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/gitlab/GitlabMergeRequestDecoratorIntegrationTest.java index f15050c5f..62060bf69 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/gitlab/GitlabMergeRequestDecoratorIntegrationTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/gitlab/GitlabMergeRequestDecoratorIntegrationTest.java @@ -59,7 +59,6 @@ import com.github.mc1arke.sonarqube.plugin.almclient.gitlab.LinkHeaderReader; import com.github.mc1arke.sonarqube.plugin.ce.pullrequest.AnalysisDetails; import com.github.mc1arke.sonarqube.plugin.ce.pullrequest.PostAnalysisIssueVisitor; -import com.github.mc1arke.sonarqube.plugin.ce.pullrequest.markup.MarkdownFormatterFactory; import com.github.mc1arke.sonarqube.plugin.ce.pullrequest.report.AnalysisIssueSummary; import com.github.mc1arke.sonarqube.plugin.ce.pullrequest.report.AnalysisSummary; import com.github.mc1arke.sonarqube.plugin.ce.pullrequest.report.ReportGenerator; @@ -95,12 +94,12 @@ private void decorateQualityGateStatus(QualityGate.Status status) { long sourceProjectId = 1234; int lineNumber = 5; - ProjectAlmSettingDto projectAlmSettingDto = mock(ProjectAlmSettingDto.class); - AlmSettingDto almSettingDto = mock(AlmSettingDto.class); + ProjectAlmSettingDto projectAlmSettingDto = mock(); + AlmSettingDto almSettingDto = mock(); when(almSettingDto.getDecryptedPersonalAccessToken(any())).thenReturn("token"); when(almSettingDto.getUrl()).thenReturn(wireMockExtension.baseUrl() + "/api/v4"); - AnalysisDetails analysisDetails = mock(AnalysisDetails.class); + AnalysisDetails analysisDetails = mock(); when(almSettingDto.getUrl()).thenReturn(wireMockExtension.baseUrl() + "/api/v4"); when(projectAlmSettingDto.getAlmRepo()).thenReturn(repositorySlug); when(projectAlmSettingDto.getMonorepo()).thenReturn(true); @@ -109,21 +108,21 @@ private void decorateQualityGateStatus(QualityGate.Status status) { when(analysisDetails.getPullRequestId()).thenReturn(Long.toString(mergeRequestIid)); when(analysisDetails.getCommitSha()).thenReturn(commitSha); - ScmInfoRepository scmInfoRepository = mock(ScmInfoRepository.class); + ScmInfoRepository scmInfoRepository = mock(); List issues = new ArrayList<>(); for (int i = 0; i < 2; i++) { - PostAnalysisIssueVisitor.ComponentIssue componentIssue = mock(PostAnalysisIssueVisitor.ComponentIssue.class); - PostAnalysisIssueVisitor.LightIssue defaultIssue = mock(PostAnalysisIssueVisitor.LightIssue.class); + PostAnalysisIssueVisitor.ComponentIssue componentIssue = mock(); + PostAnalysisIssueVisitor.LightIssue defaultIssue = mock(); when(defaultIssue.issueStatus()).thenReturn(IssueStatus.OPEN); when(defaultIssue.getLine()).thenReturn(lineNumber); when(defaultIssue.key()).thenReturn("issueKey" + i); when(componentIssue.getIssue()).thenReturn(defaultIssue); - Component component = mock(Component.class); + Component component = mock(); when(componentIssue.getComponent()).thenReturn(component); when(componentIssue.getScmPath()).thenReturn(Optional.of(filePath)); - ScmInfo scmInfo = mock(ScmInfo.class); + ScmInfo scmInfo = mock(); when(scmInfo.hasChangesetForLine(anyInt())).thenReturn(true); when(scmInfo.getChangesetForLine(anyInt())).thenReturn(Changeset.newChangesetBuilder() .setDate(0L) @@ -135,14 +134,14 @@ private void decorateQualityGateStatus(QualityGate.Status status) { } when(analysisDetails.getScmReportableIssues()).thenReturn(issues); - ReportGenerator reportGenerator = mock(ReportGenerator.class); - AnalysisSummary analysisSummary = mock(AnalysisSummary.class); + ReportGenerator reportGenerator = mock(); + AnalysisSummary analysisSummary = mock(); when(analysisSummary.getNewCoverage()).thenReturn(BigDecimal.TEN); when(analysisSummary.getDashboardUrl()).thenReturn(sonarRootUrl + "/dashboard?id=" + projectKey + "&pullRequest=" + mergeRequestIid); when(analysisSummary.format(any())).thenReturn("summary commént\n\n[link text]"); when(reportGenerator.createAnalysisSummary(any())).thenReturn(analysisSummary); - AnalysisIssueSummary analysisIssueSummary = mock(AnalysisIssueSummary.class); + AnalysisIssueSummary analysisIssueSummary = mock(); when(analysisIssueSummary.format(any())).thenReturn("issué"); when(reportGenerator.createAnalysisIssueSummary(any(), any())).thenReturn(analysisIssueSummary); @@ -245,12 +244,12 @@ private void decorateQualityGateStatus(QualityGate.Status status) { .willReturn(ok()) ); - LinkHeaderReader linkHeaderReader = mock(LinkHeaderReader.class); - Settings settings = mock(Settings.class); - Encryption encryption = mock(Encryption.class); + LinkHeaderReader linkHeaderReader = mock(); + Settings settings = mock(); + Encryption encryption = mock(); when(settings.getEncryption()).thenReturn(encryption); GitlabMergeRequestDecorator pullRequestDecorator = - new GitlabMergeRequestDecorator(scmInfoRepository, new DefaultGitlabClientFactory(linkHeaderReader, settings), reportGenerator, mock(MarkdownFormatterFactory.class)); + new GitlabMergeRequestDecorator(scmInfoRepository, new DefaultGitlabClientFactory(linkHeaderReader, settings), reportGenerator, mock()); assertThat(pullRequestDecorator.decorateQualityGateStatus(analysisDetails, almSettingDto, projectAlmSettingDto).getPullRequestUrl()).isEqualTo(Optional.of("http://gitlab.example.com/my-group/my-project/merge_requests/1")); diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/gitlab/GitlabMergeRequestDecoratorTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/gitlab/GitlabMergeRequestDecoratorTest.java index fb6b4c8a8..71f89b3bf 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/gitlab/GitlabMergeRequestDecoratorTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/gitlab/GitlabMergeRequestDecoratorTest.java @@ -88,18 +88,18 @@ class GitlabMergeRequestDecoratorTest { "the discussion is not being being closed automatically. " + "Please manually resolve this discussion once the other comments have been reviewed."; - private final GitlabClient gitlabClient = mock(GitlabClient.class); - private final GitlabClientFactory gitlabClientFactory = mock(GitlabClientFactory.class); - private final ScmInfoRepository scmInfoRepository = mock(ScmInfoRepository.class); - private final AnalysisDetails analysisDetails = mock(AnalysisDetails.class); - private final AlmSettingDto almSettingDto = mock(AlmSettingDto.class); - private final ProjectAlmSettingDto projectAlmSettingDto = mock(ProjectAlmSettingDto.class); - private final MergeRequest mergeRequest = mock(MergeRequest.class); - private final User sonarqubeUser = mock(User.class); - private final DiffRefs diffRefs = mock(DiffRefs.class); - private final ReportGenerator reportGenerator = mock(ReportGenerator.class); - private final MarkdownFormatterFactory markdownFormatterFactory = mock(MarkdownFormatterFactory.class); - private final AnalysisSummary analysisSummary = mock(AnalysisSummary.class); + private final GitlabClient gitlabClient = mock(); + private final GitlabClientFactory gitlabClientFactory = mock(); + private final ScmInfoRepository scmInfoRepository = mock(); + private final AnalysisDetails analysisDetails = mock(); + private final AlmSettingDto almSettingDto = mock(); + private final ProjectAlmSettingDto projectAlmSettingDto = mock(); + private final MergeRequest mergeRequest = mock(); + private final User sonarqubeUser = mock(); + private final DiffRefs diffRefs = mock(); + private final ReportGenerator reportGenerator = mock(); + private final MarkdownFormatterFactory markdownFormatterFactory = mock(); + private final AnalysisSummary analysisSummary = mock(); private final GitlabMergeRequestDecorator underTest = new GitlabMergeRequestDecorator(scmInfoRepository, gitlabClientFactory, reportGenerator, markdownFormatterFactory); @@ -107,7 +107,7 @@ class GitlabMergeRequestDecoratorTest { void setUp() throws IOException { when(analysisSummary.format(any())).thenReturn("Summary Comment"); when(reportGenerator.createAnalysisSummary(any())).thenReturn(analysisSummary); - AnalysisIssueSummary analysisIssueSummary = mock(AnalysisIssueSummary.class); + AnalysisIssueSummary analysisIssueSummary = mock(); when(analysisIssueSummary.format(any())).thenReturn("Issue Summary"); when(reportGenerator.createAnalysisIssueSummary(any(), any())).thenReturn(analysisIssueSummary); when(gitlabClientFactory.createClient(any(), any())).thenReturn(gitlabClient); @@ -185,12 +185,12 @@ void shouldThrowErrorWhenGitlabMergeRequestDiscussionRetrievalFails() throws IOE @Test void shouldCloseDiscussionWithSingleResolvableNoteFromSonarqubeUserButNoIssueIdInBody() throws IOException { - Note note = mock(Note.class); + Note note = mock(); when(note.getAuthor()).thenReturn(sonarqubeUser); when(note.getBody()).thenReturn("Post with no issue ID"); when(note.isResolvable()).thenReturn(true); - Discussion discussion = mock(Discussion.class); + Discussion discussion = mock(); when(discussion.getId()).thenReturn("discussionId"); when(discussion.getNotes()).thenReturn(Collections.singletonList(note)); @@ -198,7 +198,7 @@ void shouldCloseDiscussionWithSingleResolvableNoteFromSonarqubeUserButNoIssueIdI underTest.decorateQualityGateStatus(analysisDetails, almSettingDto, projectAlmSettingDto); - ArgumentCaptor mergeRequestNoteArgumentCaptor = ArgumentCaptor.forClass(MergeRequestNote.class); + ArgumentCaptor mergeRequestNoteArgumentCaptor = ArgumentCaptor.captor(); verify(gitlabClient, never()).resolveMergeRequestDiscussion(anyLong(), anyLong(), any()); verify(gitlabClient).addMergeRequestDiscussion(anyLong(), anyLong(), mergeRequestNoteArgumentCaptor.capture()); @@ -206,12 +206,12 @@ void shouldCloseDiscussionWithSingleResolvableNoteFromSonarqubeUserButNoIssueIdI @Test void shouldNotCloseDiscussionWithSingleNonResolvableNoteFromSonarqubeUserButNoIssueIdInBody() throws IOException { - Note note = mock(Note.class); + Note note = mock(); when(note.getAuthor()).thenReturn(sonarqubeUser); when(note.getBody()).thenReturn("Post with no issue ID"); when(note.isResolvable()).thenReturn(false); - Discussion discussion = mock(Discussion.class); + Discussion discussion = mock(); when(discussion.getId()).thenReturn("discussionId"); when(discussion.getNotes()).thenReturn(Collections.singletonList(note)); @@ -224,18 +224,18 @@ void shouldNotCloseDiscussionWithSingleNonResolvableNoteFromSonarqubeUserButNoIs @Test void shouldNotCloseDiscussionWithMultipleResolvableNotesFromSonarqubeUserButNoId() throws IOException { - Note note = mock(Note.class); + Note note = mock(); when(note.getAuthor()).thenReturn(sonarqubeUser); when(note.getBody()).thenReturn("Another post with no issue ID\nbut containing a new line"); when(note.isResolvable()).thenReturn(true); - Note note2 = mock(Note.class); + Note note2 = mock(); when(note2.getAuthor()).thenReturn(sonarqubeUser); when(note2.getBody()).thenReturn("Additional post from user"); when(note2.isResolvable()).thenReturn(true); - Discussion discussion = mock(Discussion.class); + Discussion discussion = mock(); when(discussion.getId()).thenReturn("discussionId2"); when(discussion.getNotes()).thenReturn(Arrays.asList(note, note2)); @@ -243,7 +243,7 @@ void shouldNotCloseDiscussionWithMultipleResolvableNotesFromSonarqubeUserButNoId underTest.decorateQualityGateStatus(analysisDetails, almSettingDto, projectAlmSettingDto); - ArgumentCaptor mergeRequestNoteArgumentCaptor = ArgumentCaptor.forClass(MergeRequestNote.class); + ArgumentCaptor mergeRequestNoteArgumentCaptor = ArgumentCaptor.captor(); verify(gitlabClient, never()).resolveMergeRequestDiscussion(anyLong(), anyLong(), any()); verify(gitlabClient).addMergeRequestDiscussion(anyLong(), anyLong(), mergeRequestNoteArgumentCaptor.capture()); @@ -252,21 +252,21 @@ void shouldNotCloseDiscussionWithMultipleResolvableNotesFromSonarqubeUserButNoId @Test void shouldCloseDiscussionWithResolvableNoteFromSonarqubeUserAndOnlySystemNoteFromOtherUser() throws IOException { - User otherUser = mock(User.class); + User otherUser = mock(); when(otherUser.getUsername()).thenReturn("other.user@gitlab.dummy"); - Note note = mock(Note.class); + Note note = mock(); when(note.getAuthor()).thenReturn(sonarqubeUser); when(note.getBody()).thenReturn("[View in SonarQube](http://host.domain/issue?issues=issueId&id=" + PROJECT_KEY + ")"); when(note.isResolvable()).thenReturn(true); - Note note2 = mock(Note.class); + Note note2 = mock(); when(note2.getAuthor()).thenReturn(otherUser); when(note2.getBody()).thenReturn("System post on behalf of user"); when(note2.isSystem()).thenReturn(true); - Discussion discussion = mock(Discussion.class); + Discussion discussion = mock(); when(discussion.getId()).thenReturn("discussionId2"); when(discussion.getNotes()).thenReturn(Arrays.asList(note, note2)); @@ -274,7 +274,7 @@ void shouldCloseDiscussionWithResolvableNoteFromSonarqubeUserAndOnlySystemNoteFr underTest.decorateQualityGateStatus(analysisDetails, almSettingDto, projectAlmSettingDto); - ArgumentCaptor discussionIdArgumentCaptor = ArgumentCaptor.forClass(String.class); + ArgumentCaptor discussionIdArgumentCaptor = ArgumentCaptor.captor(); verify(gitlabClient).resolveMergeRequestDiscussion(eq(PROJECT_ID), eq(MERGE_REQUEST_IID), discussionIdArgumentCaptor.capture()); assertThat(discussionIdArgumentCaptor.getValue()).isEqualTo(discussion.getId()); @@ -282,20 +282,20 @@ void shouldCloseDiscussionWithResolvableNoteFromSonarqubeUserAndOnlySystemNoteFr @Test void shouldNotAttemptCloseOfDiscussionWithMultipleResolvableNotesFromSonarqubeUserAndAnotherUserWithNoId() throws IOException { - User otherUser = mock(User.class); + User otherUser = mock(); when(otherUser.getUsername()).thenReturn("other.user@gitlab.dummy"); - Note note = mock(Note.class); + Note note = mock(); when(note.getAuthor()).thenReturn(sonarqubeUser); when(note.getBody()).thenReturn("Yet another post with no issue ID"); when(note.isResolvable()).thenReturn(true); - Note note2 = mock(Note.class); + Note note2 = mock(); when(note2.getAuthor()).thenReturn(otherUser); when(note2.getBody()).thenReturn("Post from another user"); when(note2.isResolvable()).thenReturn(true); - Discussion discussion = mock(Discussion.class); + Discussion discussion = mock(); when(discussion.getId()).thenReturn("discussionId3"); when(discussion.getNotes()).thenReturn(Arrays.asList(note, note2)); @@ -304,7 +304,7 @@ void shouldNotAttemptCloseOfDiscussionWithMultipleResolvableNotesFromSonarqubeUs underTest.decorateQualityGateStatus(analysisDetails, almSettingDto, projectAlmSettingDto); verify(gitlabClient, never()).resolveMergeRequestDiscussion(anyLong(), anyLong(), any()); - ArgumentCaptor mergeRequestNoteArgumentCaptor = ArgumentCaptor.forClass(MergeRequestNote.class); + ArgumentCaptor mergeRequestNoteArgumentCaptor = ArgumentCaptor.captor(); verify(gitlabClient, never()).resolveMergeRequestDiscussion(anyLong(), anyLong(), any()); verify(gitlabClient).addMergeRequestDiscussion(anyLong(), anyLong(), mergeRequestNoteArgumentCaptor.capture()); @@ -313,22 +313,22 @@ void shouldNotAttemptCloseOfDiscussionWithMultipleResolvableNotesFromSonarqubeUs @Test void shouldNotCommentOrAttemptCloseOfDiscussionWithMultipleResolvableNotesFromSonarqubeUserAndACloseMessageWithNoId() throws IOException { - Note note = mock(Note.class); + Note note = mock(); when(note.getAuthor()).thenReturn(sonarqubeUser); when(note.getBody()).thenReturn("And another post with no issue ID\nNo View in SonarQube link"); when(note.isResolvable()).thenReturn(true); - Note note2 = mock(Note.class); + Note note2 = mock(); when(note2.getAuthor()).thenReturn(sonarqubeUser); when(note2.getBody()).thenReturn("dummy"); when(note2.isResolvable()).thenReturn(true); - Note note3 = mock(Note.class); + Note note3 = mock(); when(note3.getAuthor()).thenReturn(sonarqubeUser); when(note3.getBody()).thenReturn("other comment"); when(note3.isResolvable()).thenReturn(true); - Discussion discussion = mock(Discussion.class); + Discussion discussion = mock(); when(discussion.getId()).thenReturn("discussionId4"); when(discussion.getNotes()).thenReturn(Arrays.asList(note, note2, note3)); @@ -342,20 +342,20 @@ void shouldNotCommentOrAttemptCloseOfDiscussionWithMultipleResolvableNotesFromSo @Test void shouldCommentAboutCloseOfDiscussionWithMultipleResolvableNotesFromSonarqubeUserAndAnotherUserWithIssuedId() throws IOException { - User otherUser = mock(User.class); + User otherUser = mock(); when(otherUser.getUsername()).thenReturn("other.user@gitlab.dummy"); - Note note = mock(Note.class); + Note note = mock(); when(note.getAuthor()).thenReturn(sonarqubeUser); when(note.getBody()).thenReturn("Sonarqube reported issue\n[View in SonarQube](https://dummy.url.with.subdomain/path/to/sonarqube?paramters=many&values=complex%20and+encoded&issues=new-issue&id=" + PROJECT_KEY + ")"); when(note.isResolvable()).thenReturn(true); - Note note2 = mock(Note.class); + Note note2 = mock(); when(note2.getAuthor()).thenReturn(otherUser); when(note2.getBody()).thenReturn("Message from another user"); when(note2.isResolvable()).thenReturn(true); - Discussion discussion = mock(Discussion.class); + Discussion discussion = mock(); when(discussion.getId()).thenReturn("discussionId5"); when(discussion.getNotes()).thenReturn(Arrays.asList(note, note2)); @@ -364,8 +364,8 @@ void shouldCommentAboutCloseOfDiscussionWithMultipleResolvableNotesFromSonarqube underTest.decorateQualityGateStatus(analysisDetails, almSettingDto, projectAlmSettingDto); verify(gitlabClient, never()).resolveMergeRequestDiscussion(anyLong(), anyLong(), any()); - ArgumentCaptor discussionIdArgumentCaptor = ArgumentCaptor.forClass(String.class); - ArgumentCaptor noteContentArgumentCaptor = ArgumentCaptor.forClass(String.class); + ArgumentCaptor discussionIdArgumentCaptor = ArgumentCaptor.captor(); + ArgumentCaptor noteContentArgumentCaptor = ArgumentCaptor.captor(); verify(gitlabClient).addMergeRequestDiscussionNote(eq(PROJECT_ID), eq(MERGE_REQUEST_IID), discussionIdArgumentCaptor.capture(), noteContentArgumentCaptor.capture()); assertThat(discussionIdArgumentCaptor.getValue()).isEqualTo(discussion.getId()); @@ -374,20 +374,20 @@ void shouldCommentAboutCloseOfDiscussionWithMultipleResolvableNotesFromSonarqube @Test void shouldThrowErrorIfUnableToCleanUpDiscussionOnGitlab() throws IOException { - User otherUser = mock(User.class); + User otherUser = mock(); when(otherUser.getUsername()).thenReturn("other.user@gitlab.dummy"); - Note note = mock(Note.class); + Note note = mock(); when(note.getAuthor()).thenReturn(sonarqubeUser); when(note.getBody()).thenReturn("Sonarqube reported issue\n[View in SonarQube](https://dummy.url.with.subdomain/path/to/sonarqube?paramters=many&values=complex%20and+encoded&issues=issuedId&id=" + PROJECT_KEY + ")"); when(note.isResolvable()).thenReturn(true); - Note note2 = mock(Note.class); + Note note2 = mock(); when(note2.getAuthor()).thenReturn(otherUser); when(note2.getBody()).thenReturn("Message from another user"); when(note2.isResolvable()).thenReturn(true); - Discussion discussion = mock(Discussion.class); + Discussion discussion = mock(); when(discussion.getId()).thenReturn("discussionId5"); when(discussion.getNotes()).thenReturn(Arrays.asList(note, note2)); @@ -399,8 +399,8 @@ void shouldThrowErrorIfUnableToCleanUpDiscussionOnGitlab() throws IOException { .hasMessage("Could not add note to Merge Request discussion"); verify(gitlabClient, never()).resolveMergeRequestDiscussion(anyLong(), anyLong(), any()); - ArgumentCaptor discussionIdArgumentCaptor = ArgumentCaptor.forClass(String.class); - ArgumentCaptor noteContentArgumentCaptor = ArgumentCaptor.forClass(String.class); + ArgumentCaptor discussionIdArgumentCaptor = ArgumentCaptor.captor(); + ArgumentCaptor noteContentArgumentCaptor = ArgumentCaptor.captor(); verify(gitlabClient).addMergeRequestDiscussionNote(eq(PROJECT_ID), eq(MERGE_REQUEST_IID), discussionIdArgumentCaptor.capture(), noteContentArgumentCaptor.capture()); assertThat(discussionIdArgumentCaptor.getValue()).isEqualTo(discussion.getId()); @@ -409,22 +409,22 @@ void shouldThrowErrorIfUnableToCleanUpDiscussionOnGitlab() throws IOException { @Test void shouldNotCommentOrAttemptCloseOfDiscussionWithMultipleResolvableNotesFromSonarqubeUserAndACloseMessageWithIssueId() throws IOException { - Note note = mock(Note.class); + Note note = mock(); when(note.getAuthor()).thenReturn(sonarqubeUser); when(note.getBody()).thenReturn("And another post with an issue ID\n[View in SonarQube](url)"); when(note.isResolvable()).thenReturn(true); - Note note2 = mock(Note.class); + Note note2 = mock(); when(note2.getAuthor()).thenReturn(sonarqubeUser); when(note2.getBody()).thenReturn(OLD_SONARQUBE_ISSUE_COMMENT); when(note2.isResolvable()).thenReturn(true); - Note note3 = mock(Note.class); + Note note3 = mock(); when(note3.getAuthor()).thenReturn(sonarqubeUser); when(note3.getBody()).thenReturn("Some additional comment"); when(note3.isResolvable()).thenReturn(true); - Discussion discussion = mock(Discussion.class); + Discussion discussion = mock(); when(discussion.getId()).thenReturn("discussionId6"); when(discussion.getNotes()).thenReturn(Arrays.asList(note, note2, note3)); @@ -438,14 +438,14 @@ void shouldNotCommentOrAttemptCloseOfDiscussionWithMultipleResolvableNotesFromSo @Test void shouldThrowErrorIfSubmittingNewIssueToGitlabFails() throws IOException { - PostAnalysisIssueVisitor.LightIssue lightIssue = mock(PostAnalysisIssueVisitor.LightIssue.class); + PostAnalysisIssueVisitor.LightIssue lightIssue = mock(); when(lightIssue.key()).thenReturn("issueKey1"); when(lightIssue.issueStatus()).thenReturn(IssueStatus.OPEN); when(lightIssue.getLine()).thenReturn(999); - Component component = mock(Component.class); + Component component = mock(); - PostAnalysisIssueVisitor.ComponentIssue componentIssue = mock(PostAnalysisIssueVisitor.ComponentIssue.class); + PostAnalysisIssueVisitor.ComponentIssue componentIssue = mock(); when(componentIssue.getIssue()).thenReturn(lightIssue); when(componentIssue.getComponent()).thenReturn(component); when(componentIssue.getScmPath()).thenReturn(Optional.of("path-to-file")); @@ -453,10 +453,10 @@ void shouldThrowErrorIfSubmittingNewIssueToGitlabFails() throws IOException { when(analysisDetails.getScmReportableIssues()).thenReturn(Collections.singletonList(componentIssue)); when(gitlabClient.getMergeRequestDiscussions(anyLong(), anyLong())).thenReturn(new ArrayList<>()); - Changeset changeset = mock(Changeset.class); + Changeset changeset = mock(); when(changeset.getRevision()).thenReturn("DEF"); - ScmInfo scmInfo = mock(ScmInfo.class); + ScmInfo scmInfo = mock(); when(scmInfo.hasChangesetForLine(999)).thenReturn(true); when(scmInfo.getChangesetForLine(999)).thenReturn(changeset); when(scmInfoRepository.getScmInfo(component)).thenReturn(Optional.of(scmInfo)); @@ -470,7 +470,7 @@ void shouldThrowErrorIfSubmittingNewIssueToGitlabFails() throws IOException { verify(gitlabClient, never()).resolveMergeRequestDiscussion(anyLong(), anyLong(), any()); verify(gitlabClient, never()).addMergeRequestDiscussionNote(anyLong(), anyLong(), any(), any()); - ArgumentCaptor mergeRequestNoteArgumentCaptor = ArgumentCaptor.forClass(MergeRequestNote.class); + ArgumentCaptor mergeRequestNoteArgumentCaptor = ArgumentCaptor.captor(); verify(gitlabClient).addMergeRequestDiscussion(eq(PROJECT_ID), eq(MERGE_REQUEST_IID), mergeRequestNoteArgumentCaptor.capture()); assertThat(mergeRequestNoteArgumentCaptor.getValue()) @@ -480,14 +480,14 @@ void shouldThrowErrorIfSubmittingNewIssueToGitlabFails() throws IOException { @Test void shouldStartNewDiscussionForNewIssueFromCommitInMergeRequest() throws IOException { - PostAnalysisIssueVisitor.LightIssue lightIssue = mock(PostAnalysisIssueVisitor.LightIssue.class); + PostAnalysisIssueVisitor.LightIssue lightIssue = mock(); when(lightIssue.key()).thenReturn("issueKey1"); when(lightIssue.issueStatus()).thenReturn(IssueStatus.OPEN); when(lightIssue.getLine()).thenReturn(999); - Component component = mock(Component.class); + Component component = mock(); - PostAnalysisIssueVisitor.ComponentIssue componentIssue = mock(PostAnalysisIssueVisitor.ComponentIssue.class); + PostAnalysisIssueVisitor.ComponentIssue componentIssue = mock(); when(componentIssue.getIssue()).thenReturn(lightIssue); when(componentIssue.getComponent()).thenReturn(component); when(componentIssue.getScmPath()).thenReturn(Optional.of("path-to-file")); @@ -495,10 +495,10 @@ void shouldStartNewDiscussionForNewIssueFromCommitInMergeRequest() throws IOExce when(analysisDetails.getScmReportableIssues()).thenReturn(Collections.singletonList(componentIssue)); when(gitlabClient.getMergeRequestDiscussions(anyLong(), anyLong())).thenReturn(new ArrayList<>()); - Changeset changeset = mock(Changeset.class); + Changeset changeset = mock(); when(changeset.getRevision()).thenReturn("DEF"); - ScmInfo scmInfo = mock(ScmInfo.class); + ScmInfo scmInfo = mock(); when(scmInfo.hasChangesetForLine(999)).thenReturn(true); when(scmInfo.getChangesetForLine(999)).thenReturn(changeset); when(scmInfoRepository.getScmInfo(component)).thenReturn(Optional.of(scmInfo)); @@ -508,7 +508,7 @@ void shouldStartNewDiscussionForNewIssueFromCommitInMergeRequest() throws IOExce verify(gitlabClient, never()).resolveMergeRequestDiscussion(anyLong(), anyLong(), any()); verify(gitlabClient, never()).addMergeRequestDiscussionNote(anyLong(), anyLong(), any(), any()); - ArgumentCaptor mergeRequestNoteArgumentCaptor = ArgumentCaptor.forClass(MergeRequestNote.class); + ArgumentCaptor mergeRequestNoteArgumentCaptor = ArgumentCaptor.captor(); verify(gitlabClient, times(2)).addMergeRequestDiscussion(eq(PROJECT_ID), eq(MERGE_REQUEST_IID), mergeRequestNoteArgumentCaptor.capture()); assertThat(mergeRequestNoteArgumentCaptor.getAllValues().get(0)) @@ -519,34 +519,34 @@ void shouldStartNewDiscussionForNewIssueFromCommitInMergeRequest() throws IOExce @Test void shouldNotStartNewDiscussionForIssueWithExistingCommentFromCommitInMergeRequest() throws IOException { - PostAnalysisIssueVisitor.LightIssue lightIssue = mock(PostAnalysisIssueVisitor.LightIssue.class); + PostAnalysisIssueVisitor.LightIssue lightIssue = mock(); when(lightIssue.key()).thenReturn("issueKey1"); when(lightIssue.issueStatus()).thenReturn(IssueStatus.OPEN); when(lightIssue.getLine()).thenReturn(999); - Component component = mock(Component.class); + Component component = mock(); - PostAnalysisIssueVisitor.ComponentIssue componentIssue = mock(PostAnalysisIssueVisitor.ComponentIssue.class); + PostAnalysisIssueVisitor.ComponentIssue componentIssue = mock(); when(componentIssue.getIssue()).thenReturn(lightIssue); when(componentIssue.getComponent()).thenReturn(component); when(componentIssue.getScmPath()).thenReturn(Optional.of("path-to-file")); - Note note = mock(Note.class); + Note note = mock(); when(note.getBody()).thenReturn("Reported issue\n[View in SonarQube](http://domain.url/sonar/issue?issues=issueKey1&id=" + PROJECT_KEY + ")"); when(note.getAuthor()).thenReturn(sonarqubeUser); when(note.isResolvable()).thenReturn(true); - Discussion discussion = mock(Discussion.class); + Discussion discussion = mock(); when(discussion.getId()).thenReturn("discussion-id"); when(discussion.getNotes()).thenReturn(Collections.singletonList(note)); when(gitlabClient.getMergeRequestDiscussions(anyLong(), anyLong())).thenReturn(Collections.singletonList(discussion)); when(analysisDetails.getScmReportableIssues()).thenReturn(Collections.singletonList(componentIssue)); - Changeset changeset = mock(Changeset.class); + Changeset changeset = mock(); when(changeset.getRevision()).thenReturn("DEF"); - ScmInfo scmInfo = mock(ScmInfo.class); + ScmInfo scmInfo = mock(); when(scmInfo.hasChangesetForLine(999)).thenReturn(true); when(scmInfo.getChangesetForLine(999)).thenReturn(changeset); when(scmInfoRepository.getScmInfo(component)).thenReturn(Optional.of(scmInfo)); @@ -556,7 +556,7 @@ void shouldNotStartNewDiscussionForIssueWithExistingCommentFromCommitInMergeRequ verify(gitlabClient, never()).resolveMergeRequestDiscussion(anyLong(), anyLong(), any()); verify(gitlabClient, never()).addMergeRequestDiscussionNote(anyLong(), anyLong(), any(), any()); - ArgumentCaptor mergeRequestNoteArgumentCaptor = ArgumentCaptor.forClass(MergeRequestNote.class); + ArgumentCaptor mergeRequestNoteArgumentCaptor = ArgumentCaptor.captor(); verify(gitlabClient).addMergeRequestDiscussion(eq(PROJECT_ID), eq(MERGE_REQUEST_IID), mergeRequestNoteArgumentCaptor.capture()); assertThat(mergeRequestNoteArgumentCaptor.getValue()).isNotInstanceOf(CommitNote.class); @@ -564,14 +564,14 @@ void shouldNotStartNewDiscussionForIssueWithExistingCommentFromCommitInMergeRequ @Test void shouldNotCreateCommentsForIssuesWithNoLineNumbers() throws IOException { - PostAnalysisIssueVisitor.LightIssue lightIssue = mock(PostAnalysisIssueVisitor.LightIssue.class); + PostAnalysisIssueVisitor.LightIssue lightIssue = mock(); when(lightIssue.key()).thenReturn("issueKey1"); when(lightIssue.issueStatus()).thenReturn(IssueStatus.OPEN); when(lightIssue.getLine()).thenReturn(null); - Component component = mock(Component.class); + Component component = mock(); - PostAnalysisIssueVisitor.ComponentIssue componentIssue = mock(PostAnalysisIssueVisitor.ComponentIssue.class); + PostAnalysisIssueVisitor.ComponentIssue componentIssue = mock(); when(componentIssue.getIssue()).thenReturn(lightIssue); when(componentIssue.getComponent()).thenReturn(component); @@ -584,7 +584,7 @@ void shouldNotCreateCommentsForIssuesWithNoLineNumbers() throws IOException { verify(gitlabClient, never()).addMergeRequestDiscussionNote(anyLong(), anyLong(), any(), any()); verify(scmInfoRepository, never()).getScmInfo(any()); - ArgumentCaptor mergeRequestNoteArgumentCaptor = ArgumentCaptor.forClass(MergeRequestNote.class); + ArgumentCaptor mergeRequestNoteArgumentCaptor = ArgumentCaptor.captor(); verify(gitlabClient).addMergeRequestDiscussion(eq(PROJECT_ID), eq(MERGE_REQUEST_IID), mergeRequestNoteArgumentCaptor.capture()); assertThat(mergeRequestNoteArgumentCaptor.getValue()).isNotInstanceOf(CommitNote.class); @@ -598,16 +598,16 @@ void shouldSubmitSuccessfulPipelineStatusAndResolvedSummaryCommentOnSuccessAnaly when(analysisSummary.format(any())).thenReturn("Summary comment"); when(analysisSummary.getDashboardUrl()).thenReturn("https://sonarqube.dummy/dashboard?id=projectKey&pullRequest=123"); - Discussion discussion = mock(Discussion.class); + Discussion discussion = mock(); when(discussion.getId()).thenReturn("dicussion id"); when(gitlabClient.addMergeRequestDiscussion(anyLong(), anyLong(), any())).thenReturn(discussion); underTest.decorateQualityGateStatus(analysisDetails, almSettingDto, projectAlmSettingDto); - ArgumentCaptor mergeRequestNoteArgumentCaptor = ArgumentCaptor.forClass(MergeRequestNote.class); + ArgumentCaptor mergeRequestNoteArgumentCaptor = ArgumentCaptor.captor(); verify(gitlabClient).addMergeRequestDiscussion(eq(PROJECT_ID), eq(MERGE_REQUEST_IID), mergeRequestNoteArgumentCaptor.capture()); verify(gitlabClient).resolveMergeRequestDiscussion(PROJECT_ID, MERGE_REQUEST_IID, discussion.getId()); - ArgumentCaptor pipelineStatusArgumentCaptor = ArgumentCaptor.forClass(PipelineStatus.class); + ArgumentCaptor pipelineStatusArgumentCaptor = ArgumentCaptor.captor(); verify(gitlabClient).setMergeRequestPipelineStatus(eq(PROJECT_ID), eq("commitsha"), pipelineStatusArgumentCaptor.capture()); assertThat(mergeRequestNoteArgumentCaptor.getValue()) @@ -629,16 +629,16 @@ void shouldSubmitFailedPipelineStatusAndUnresolvedSummaryCommentOnFailedAnalysis when(analysisSummary.getDashboardUrl()).thenReturn("https://sonarqube2.dummy/dashboard?id=projectKey&pullRequest=123"); when(analysisSummary.getNewCoverage()).thenReturn(BigDecimal.TEN); - Discussion discussion = mock(Discussion.class); + Discussion discussion = mock(); when(discussion.getId()).thenReturn("dicussion id 2"); when(gitlabClient.addMergeRequestDiscussion(anyLong(), anyLong(), any())).thenReturn(discussion); underTest.decorateQualityGateStatus(analysisDetails, almSettingDto, projectAlmSettingDto); - ArgumentCaptor mergeRequestNoteArgumentCaptor = ArgumentCaptor.forClass(MergeRequestNote.class); + ArgumentCaptor mergeRequestNoteArgumentCaptor = ArgumentCaptor.captor(); verify(gitlabClient).addMergeRequestDiscussion(eq(PROJECT_ID), eq(MERGE_REQUEST_IID), mergeRequestNoteArgumentCaptor.capture()); verify(gitlabClient, never()).resolveMergeRequestDiscussion(PROJECT_ID, MERGE_REQUEST_IID, discussion.getId()); - ArgumentCaptor pipelineStatusArgumentCaptor = ArgumentCaptor.forClass(PipelineStatus.class); + ArgumentCaptor pipelineStatusArgumentCaptor = ArgumentCaptor.captor(); verify(gitlabClient).setMergeRequestPipelineStatus(eq(PROJECT_ID), eq("other sha"), pipelineStatusArgumentCaptor.capture()); assertThat(mergeRequestNoteArgumentCaptor.getValue()) @@ -660,7 +660,7 @@ void shouldThrowErrorWhenSubmitPipelineStatusToGitlabFails() throws IOException when(analysisSummary.getDashboardUrl()).thenReturn("https://sonarqube2.dummy/dashboard?id=projectKey&pullRequest=123"); when(analysisSummary.getNewCoverage()).thenReturn(BigDecimal.TEN); - Discussion discussion = mock(Discussion.class); + Discussion discussion = mock(); when(discussion.getId()).thenReturn("dicussion id 2"); when(gitlabClient.addMergeRequestDiscussion(anyLong(), anyLong(), any())).thenReturn(discussion); doThrow(new IOException("dummy")).when(gitlabClient).setMergeRequestPipelineStatus(anyLong(), any(), any()); @@ -669,10 +669,10 @@ void shouldThrowErrorWhenSubmitPipelineStatusToGitlabFails() throws IOException .isInstanceOf(IllegalStateException.class) .hasMessage("Could not update pipeline status in Gitlab"); - ArgumentCaptor mergeRequestNoteArgumentCaptor = ArgumentCaptor.forClass(MergeRequestNote.class); + ArgumentCaptor mergeRequestNoteArgumentCaptor = ArgumentCaptor.captor(); verify(gitlabClient).addMergeRequestDiscussion(eq(PROJECT_ID), eq(MERGE_REQUEST_IID), mergeRequestNoteArgumentCaptor.capture()); verify(gitlabClient, never()).resolveMergeRequestDiscussion(PROJECT_ID, MERGE_REQUEST_IID, discussion.getId()); - ArgumentCaptor pipelineStatusArgumentCaptor = ArgumentCaptor.forClass(PipelineStatus.class); + ArgumentCaptor pipelineStatusArgumentCaptor = ArgumentCaptor.captor(); verify(gitlabClient).setMergeRequestPipelineStatus(eq(PROJECT_ID), eq("other sha"), pipelineStatusArgumentCaptor.capture()); assertThat(mergeRequestNoteArgumentCaptor.getValue()) @@ -692,7 +692,7 @@ void shouldThrowErrorWhenSubmitAnalysisToGitlabFails() throws IOException { when(analysisSummary.format(any())).thenReturn("Different Summary comment"); - Discussion discussion = mock(Discussion.class); + Discussion discussion = mock(); when(discussion.getId()).thenReturn("dicussion id 2"); when(gitlabClient.addMergeRequestDiscussion(anyLong(), anyLong(), any())).thenReturn(discussion); doThrow(new IOException("dummy")).when(gitlabClient).addMergeRequestDiscussion(anyLong(), anyLong(), any()); @@ -701,7 +701,7 @@ void shouldThrowErrorWhenSubmitAnalysisToGitlabFails() throws IOException { .isInstanceOf(IllegalStateException.class) .hasMessage("Could not submit summary comment to Gitlab"); - ArgumentCaptor mergeRequestNoteArgumentCaptor = ArgumentCaptor.forClass(MergeRequestNote.class); + ArgumentCaptor mergeRequestNoteArgumentCaptor = ArgumentCaptor.captor(); verify(gitlabClient).addMergeRequestDiscussion(eq(PROJECT_ID), eq(MERGE_REQUEST_IID), mergeRequestNoteArgumentCaptor.capture()); verify(gitlabClient, never()).resolveMergeRequestDiscussion(PROJECT_ID, MERGE_REQUEST_IID, discussion.getId()); verify(gitlabClient, never()).setMergeRequestPipelineStatus(anyLong(), any(), any()); diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/markup/DocumentTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/markup/DocumentTest.java index 755b74dd2..a8485fe94 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/markup/DocumentTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/markup/DocumentTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2019 Michael Clarke + * Copyright (C) 2019-2024 Michael Clarke * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -18,20 +18,19 @@ */ package com.github.mc1arke.sonarqube.plugin.ce.pullrequest.markup; -import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.Test; -public class DocumentTest { +class DocumentTest { @Test - public void checkInvalidChild() { - assertFalse(new Document().isValidChild(new Document())); + void shouldNotAcceptDocumentAsValidChild() { + assertThat(new Document().isValidChild(new Document())).isFalse(); } @Test - public void checkValidChild() { - assertTrue(new Document().isValidChild(new Text(""))); + void shouldAcceptTextAsValidChild() { + assertThat(new Document().isValidChild(new Text(""))).isTrue(); } } \ No newline at end of file diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/markup/HeadingTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/markup/HeadingTest.java index 3295a32ca..bbc1c7705 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/markup/HeadingTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/markup/HeadingTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2019 Michael Clarke + * Copyright (C) 2019-2024 Michael Clarke * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -18,38 +18,36 @@ */ package com.github.mc1arke.sonarqube.plugin.ce.pullrequest.markup; -import org.junit.Test; - import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -public class HeadingTest { +import org.junit.jupiter.api.Test; + +class HeadingTest { @Test - public void correctParametersReturned() { + void shouldReturnCorrectParameters() { Heading heading = new Heading(2); assertThat(heading.getLevel()).isEqualTo(2); } @Test - public void checkInvalidAddChild() { - assertFalse(new Heading(2).isValidChild(new Heading(2))); + void shouldNotAcceptHeadingAsValidChild() { + assertThat(new Heading(2).isValidChild(new Heading(2))).isFalse(); } @Test - public void checkValidAddChildText() { - assertTrue(new Heading(2).isValidChild(new Text(""))); + void shouldAcceptTextAsValidChild() { + assertThat(new Heading(2).isValidChild(new Text(""))).isTrue(); } @Test - public void checkValidAddChildImage() { - assertTrue(new Heading(2).isValidChild(new Image("alt", "src"))); + void shouldAcceptImageAsValidChild() { + assertThat(new Heading(2).isValidChild(new Image("alt", "src"))).isTrue(); } @Test - public void checkValidAddChildLink() { - assertTrue(new Heading(2).isValidChild(new Link("url"))); + void shouldAcceptLinkAsValidChild() { + assertThat(new Heading(2).isValidChild(new Link("url"))).isTrue(); } } \ No newline at end of file diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/markup/ImageTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/markup/ImageTest.java index e05c06d7c..0d9c7784e 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/markup/ImageTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/markup/ImageTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2019 Michael Clarke + * Copyright (C) 2019-2024 Michael Clarke * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -18,23 +18,23 @@ */ package com.github.mc1arke.sonarqube.plugin.ce.pullrequest.markup; -import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertFalse; -public class ImageTest { +import org.junit.jupiter.api.Test; + +class ImageTest { @Test - public void correctParametersReturned() { + void shouldReturnCorrectParametersFromObject() { Image image = new Image("alt", "source"); assertThat(image).extracting(Image::getAltText).isEqualTo("alt"); assertThat(image).extracting(Image::getSource).isEqualTo("source"); } @Test - public void checkInvalidAddChild() { - assertFalse(new Image("", "").isValidChild(new Image("", ""))); + void shouldNotAcceptImageAsChild() { + assertThat(new Image("", "").isValidChild(new Image("", ""))).isFalse(); } } \ No newline at end of file diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/markup/ListItemTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/markup/ListItemTest.java index 5b4b98355..a0bd93af3 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/markup/ListItemTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/markup/ListItemTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2019 Michael Clarke + * Copyright (C) 2019-2024 Michael Clarke * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -18,31 +18,30 @@ */ package com.github.mc1arke.sonarqube.plugin.ce.pullrequest.markup; -import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.Test; -public class ListItemTest { +class ListItemTest { @Test - public void testIsValidChildInvalidChild() { - assertFalse(new ListItem().isValidChild(new Paragraph())); + void shouldNotAcceptParagraphAsValidChild() { + assertThat(new ListItem().isValidChild(new Paragraph())).isFalse(); } @Test - public void testIsValidChildText() { - assertTrue(new ListItem().isValidChild(new Text(""))); + void shouldAcceptTextAsValidChild() { + assertThat(new ListItem().isValidChild(new Text(""))).isTrue(); } @Test - public void testIsValidChildImage() { - assertTrue(new ListItem().isValidChild(new Image("", ""))); + void shouldAcceptImageAsValidChild() { + assertThat(new ListItem().isValidChild(new Image("", ""))).isTrue(); } @Test - public void testIsValidChildLink() { - assertTrue(new ListItem().isValidChild(new Link(""))); + void shouldAcceptLinkAsValidChild() { + assertThat(new ListItem().isValidChild(new Link(""))).isTrue(); } } \ No newline at end of file diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/markup/ListTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/markup/ListTest.java index 5c6ecdb79..d8837642f 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/markup/ListTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/markup/ListTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2019 Michael Clarke + * Copyright (C) 2019-2024 Michael Clarke * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -18,21 +18,20 @@ */ package com.github.mc1arke.sonarqube.plugin.ce.pullrequest.markup; -import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.Test; -public class ListTest { +class ListTest { @Test - public void testIsValidChildInvalidChild() { - assertFalse(new List(List.Style.BULLET).isValidChild(new Paragraph())); + void shouldNotAcceptParagraphAsChild() { + assertThat(new List(List.Style.BULLET).isValidChild(new Paragraph())).isFalse(); } @Test - public void testIsValidChildText() { - assertTrue(new List(List.Style.BULLET).isValidChild(new ListItem())); + void shouldAcceptListItemAsValidChild() { + assertThat(new List(List.Style.BULLET).isValidChild(new ListItem())).isTrue(); } } \ No newline at end of file diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/markup/NodeTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/markup/NodeTest.java index 98f12752a..8e6de718b 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/markup/NodeTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/markup/NodeTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2019 Michael Clarke + * Copyright (C) 2019-2024 Michael Clarke * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -18,27 +18,28 @@ */ package com.github.mc1arke.sonarqube.plugin.ce.pullrequest.markup; -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 NodeTest { +import org.junit.jupiter.api.Test; + +class NodeTest { @Test - public void testExceptionThrownOnInvalidChild() { - assertThatThrownBy(() -> new BasicInvalidChildNodeImpl(new BasicValidChildNodeImpl())) + void shouldThrowExceptionOnInvalidChild() { + BasicValidChildNodeImpl childNode = new BasicValidChildNodeImpl(); + assertThatThrownBy(() -> new BasicInvalidChildNodeImpl(childNode)) .isExactlyInstanceOf(IllegalArgumentException.class).hasMessage( BasicValidChildNodeImpl.class.getName() + " is not a valid child of " + BasicInvalidChildNodeImpl.class.getName()); } @Test - public void testCorrectChildrenReturned() { - Node node1 = mock(Node.class); - Node node2 = mock(Node.class); - Node node3 = mock(Node.class); + void shouldReturnCorrectChildren() { + Node node1 = mock(); + Node node2 = mock(); + Node node3 = mock(); assertThat(new BasicValidChildNodeImpl(node1, node2, node3).getChildren()).containsExactly(node1, node2, node3); } diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/markup/ParagraphTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/markup/ParagraphTest.java index bbc9fd2dd..bb80dcf6a 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/markup/ParagraphTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/markup/ParagraphTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2019 Michael Clarke + * Copyright (C) 2019-2024 Michael Clarke * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -18,30 +18,29 @@ */ package com.github.mc1arke.sonarqube.plugin.ce.pullrequest.markup; -import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.Test; -public class ParagraphTest { +class ParagraphTest { @Test - public void testIsValidChildInvalidChild() { - assertFalse(new Paragraph().isValidChild(new Paragraph())); + void shouldNorAcceptParagraphAsValidChild() { + assertThat(new Paragraph().isValidChild(new Paragraph())).isFalse(); } @Test - public void testIsValidChildValidChildText() { - assertTrue(new Paragraph().isValidChild(new Text(""))); + void shouldAcceptTextAsValidChild() { + assertThat(new Paragraph().isValidChild(new Text(""))).isTrue(); } @Test - public void testIsValidChildValidChildImage() { - assertTrue(new Paragraph().isValidChild(new Image("", ""))); + void shouldAcceptImageAsValidChild() { + assertThat(new Paragraph().isValidChild(new Image("", ""))).isTrue(); } @Test - public void testIsValidChildValidChildLink() { - assertTrue(new Paragraph().isValidChild(new Link(""))); + void shouldAcceptLinkAsValidChild() { + assertThat(new Paragraph().isValidChild(new Link(""))).isTrue(); } } \ No newline at end of file diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/markup/TextTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/markup/TextTest.java index 881d812ef..228a63824 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/markup/TextTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/ce/pullrequest/markup/TextTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2019 Michael Clarke + * Copyright (C) 2019-2024 Michael Clarke * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -18,21 +18,20 @@ */ package com.github.mc1arke.sonarqube.plugin.ce.pullrequest.markup; -import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import org.junit.jupiter.api.Test; -public class TextTest { +class TextTest { @Test - public void testGetContent() { - assertEquals("testContent", new Text("testContent").getContent()); + void shouldReturnCorrectContent() { + assertThat(new Text("testContent").getContent()).isEqualTo("testContent"); } @Test - public void testInvalidChild() { - assertFalse((new Text("").isValidChild(new Text("")))); + void shouldRejectTextAsChildElement() { + assertThat((new Text("").isValidChild(new Text("")))).isFalse(); } } \ No newline at end of file diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/classloader/ClassReferenceElevatedClassLoaderFactoryTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/classloader/ClassReferenceElevatedClassLoaderFactoryTest.java index e9d498c74..72e3b0a34 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/classloader/ClassReferenceElevatedClassLoaderFactoryTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/classloader/ClassReferenceElevatedClassLoaderFactoryTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2020 Michael Clarke + * Copyright (C) 2020-2024 Michael Clarke * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -18,68 +18,55 @@ */ package com.github.mc1arke.sonarqube.plugin.classloader; -import org.hamcrest.core.IsEqual; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.mockito.ArgumentCaptor; -import org.sonar.api.Plugin; -import org.sonar.api.batch.rule.ActiveRule; -import org.sonar.classloader.ClassloaderBuilder; -import org.sonar.classloader.Mask; +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; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import java.util.Map; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotSame; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.sonar.api.Plugin; +import org.sonar.api.batch.rule.ActiveRule; +import org.sonar.classloader.ClassloaderBuilder; +import org.sonar.classloader.Mask; -/** - * @author Michael Clarke - */ -public class ClassReferenceElevatedClassLoaderFactoryTest { +class ClassReferenceElevatedClassLoaderFactoryTest { private static final String TARGET_PLUGIN_CLASS = "org.sonar.plugins.java.JavaPlugin"; - private final ExpectedException expectedException = ExpectedException.none(); - - @Rule - public ExpectedException expectedException() { - return expectedException; - } @Test - public void testExceptionOnNoSuchClass() { + void shouldThrowExceptionIfNoSuchClassExists() { ClassReferenceElevatedClassLoaderFactory testCase = new ClassReferenceElevatedClassLoaderFactory("1"); + Class pluginClass = ((Plugin) context -> {}).getClass(); + assertThatThrownBy(() -> testCase.createClassLoader(pluginClass)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Could not load class '1' from Plugin Classloader") + .hasCause(new ClassNotFoundException("1")); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage(IsEqual.equalTo("Could not load class '1' from Plugin Classloader")); - - testCase.createClassLoader(((Plugin) context -> { - }).getClass()); } @Test - public void testClassloaderReturnedOnHappyPath() throws ReflectiveOperationException, MalformedURLException { + void shouldCreateClassloaderWhenProvidedValidArguments() throws ReflectiveOperationException, MalformedURLException { URLClassLoader mockClassLoader = new URLClassLoader(findSonarqubePluginJars()); ElevatedClassLoaderFactory testCase = spy(new ClassReferenceElevatedClassLoaderFactory(getClass().getName())); testCase.createClassLoader((Class) mockClassLoader.loadClass(TARGET_PLUGIN_CLASS)); - ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(ClassLoader.class); + ArgumentCaptor argumentCaptor = ArgumentCaptor.captor(); verify(testCase).createClassLoader(argumentCaptor.capture(), argumentCaptor.capture()); - assertEquals(Arrays.asList(mockClassLoader, getClass().getClassLoader()), argumentCaptor.getAllValues()); + assertThat(argumentCaptor.getAllValues()).containsExactly(mockClassLoader, getClass().getClassLoader()); } @Test - public void testLoadClass() throws ClassNotFoundException, MalformedURLException { + void shouldCreateClassLoaderThatCanLoadInterceptedClasses() throws ClassNotFoundException, MalformedURLException { ClassloaderBuilder builder = new ClassloaderBuilder(); builder.newClassloader("_api_", getClass().getClassLoader()); builder.setMask("_api_", Mask.builder().include("java/", "org/sonar/api/").build()); @@ -101,8 +88,8 @@ public void testLoadClass() throws ClassNotFoundException, MalformedURLException new ClassReferenceElevatedClassLoaderFactory(ActiveRule.class.getName()); ClassLoader elevatedLoader = testCase.createClassLoader(loadedClass); Class elevatedClass = elevatedLoader.loadClass(loadedClass.getName()); - // Getting closer than this is going to be difficult since the URLClassLoader that actually loads is an inner class of evelvatedClassLoader - assertNotSame(elevatedLoader, elevatedClass.getClassLoader()); + // Getting closer than this is going to be difficult since the URLClassLoader that actually loads is an inner class of elevatedClassLoader + assertThat(elevatedClass.getClassLoader()).isNotSameAs(elevatedLoader); } private static URL[] findSonarqubePluginJars() throws MalformedURLException { diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/classloader/DefaultElevatedClassLoaderFactoryProviderTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/classloader/DefaultElevatedClassLoaderFactoryProviderTest.java index 40444ba2f..14f2afdec 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/classloader/DefaultElevatedClassLoaderFactoryProviderTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/classloader/DefaultElevatedClassLoaderFactoryProviderTest.java @@ -1,27 +1,45 @@ +/* + * Copyright (C) 2019-2024 Michael Clarke + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ package com.github.mc1arke.sonarqube.plugin.classloader; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.sonar.api.Plugin; import org.sonar.api.config.Configuration; import java.util.Optional; -import static org.junit.Assert.assertTrue; +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; -public class DefaultElevatedClassLoaderFactoryProviderTest { +class DefaultElevatedClassLoaderFactoryProviderTest { @Test - public void validFactoryReturnedOnNoPropertiesSet() { - Plugin.Context context = mock(Plugin.Context.class); - Configuration configuration = mock(Configuration.class); + void shouldCreateValidFactoryWhenNoPropertiesSet() { + Plugin.Context context = mock(); + Configuration configuration = mock(); when(context.getBootConfiguration()).thenReturn(configuration); when(configuration.get(any())).thenReturn(Optional.empty()); - assertTrue(DefaultElevatedClassLoaderFactoryProvider.getInstance() - .createFactory(context) instanceof ClassReferenceElevatedClassLoaderFactory); + assertThat(DefaultElevatedClassLoaderFactoryProvider.getInstance() + .createFactory(context)).isInstanceOf(ClassReferenceElevatedClassLoaderFactory.class); } } diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/classloader/ElevatedClassLoaderFactoryTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/classloader/ElevatedClassLoaderFactoryTest.java index 7096a38b5..9ac31ed69 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/classloader/ElevatedClassLoaderFactoryTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/classloader/ElevatedClassLoaderFactoryTest.java @@ -1,46 +1,55 @@ +/* + * Copyright (C) 2019-2024 Michael Clarke + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ package com.github.mc1arke.sonarqube.plugin.classloader; -import org.hamcrest.core.IsEqual; -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 org.junit.jupiter.api.Test; import org.sonar.api.Plugin; import java.io.IOException; import java.net.URL; import java.net.URLClassLoader; -import static org.junit.Assert.assertEquals; - -public class ElevatedClassLoaderFactoryTest { - - private final ExpectedException expectedException = ExpectedException.none(); - @Rule - public ExpectedException expectedException() { - return expectedException; - } +class ElevatedClassLoaderFactoryTest { @Test - public void testExceptionOnInvalidLoader() { + void shouldThrowExceptionOnInvalidDelegateLoader() { ElevatedClassLoaderFactory testCase = new ElevatedClassLoaderFactoryImpl(); ClassLoader classLoaderImpl = new ClassLoader() { }; - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage(IsEqual.equalTo( - "Incorrect ClassLoader type. Expected 'java.net.URLClassLoader' but got '" + - classLoaderImpl.getClass().getName() + "'")); - - testCase.createClassLoader(classLoaderImpl, classLoaderImpl); + assertThatThrownBy(() -> testCase.createClassLoader(classLoaderImpl, classLoaderImpl)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Incorrect ClassLoader type. Expected 'java.net.URLClassLoader' but got '" + classLoaderImpl.getClass().getName() + "'") + .hasNoCause(); } @Test - public void testFallthroughClassLoading() throws IOException, ClassNotFoundException { + void shouldDelegateToParentIfTargetClassNotFound() throws IOException, ClassNotFoundException { ElevatedClassLoaderFactory testCase = new ElevatedClassLoaderFactoryImpl(); try (URLClassLoader classLoader1 = new URLClassLoader(new URL[]{}) { + @Override public Class loadClass(String name) throws ClassNotFoundException { if ("1".equals(name)) { throw new ClassNotFoundException("Not here"); @@ -48,6 +57,7 @@ public Class loadClass(String name) throws ClassNotFoundException { return this.getClass(); } }; URLClassLoader classLoader2 = new URLClassLoader(new URL[]{}) { + @Override public Class loadClass(String name) throws ClassNotFoundException { if ("2".equals(name)) { throw new ClassNotFoundException("Whoops"); @@ -56,12 +66,12 @@ public Class loadClass(String name) throws ClassNotFoundException { } }) { ClassLoader createdClassLoader = testCase.createClassLoader(classLoader2, classLoader1); - assertEquals(classLoader2.getClass(), createdClassLoader.loadClass("1")); - - expectedException.expect(ClassNotFoundException.class); - expectedException.expectMessage(IsEqual.equalTo("Whoops")); + assertThat(createdClassLoader.loadClass("1")).isEqualTo(classLoader2.getClass()); - createdClassLoader.loadClass("2"); + assertThatThrownBy(() -> createdClassLoader.loadClass("2")) + .isInstanceOf(ClassNotFoundException.class) + .hasMessage("Whoops") + .hasNoCause(); } } diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/classloader/ProviderTypeTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/classloader/ProviderTypeTest.java index e49245994..69b9a2b72 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/classloader/ProviderTypeTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/classloader/ProviderTypeTest.java @@ -1,50 +1,59 @@ +/* + * Copyright (C) 2020-2024 Michael Clarke + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ package com.github.mc1arke.sonarqube.plugin.classloader; -import org.hamcrest.core.IsEqual; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; import org.sonar.api.Plugin; import org.sonar.api.config.Configuration; -import static org.junit.Assert.assertTrue; +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 ProviderTypeTest { - - private final ExpectedException expectedException = ExpectedException.none(); - - @Rule - public ExpectedException expectedException() { - return expectedException; - } +class ProviderTypeTest { @Test - public void testReflectiveTypeMatched() { - Plugin.Context context = mock(Plugin.Context.class); - Configuration configuration = mock(Configuration.class); + void testReflectiveTypeMatched() { + Plugin.Context context = mock(); + Configuration configuration = mock(); when(context.getBootConfiguration()).thenReturn(configuration); - assertTrue(ProviderType.fromName("REFLECTIVE") - .createFactory(context) instanceof ReflectiveElevatedClassLoaderFactory); + assertThat(ProviderType.fromName("REFLECTIVE") + .createFactory(context)).isInstanceOf(ReflectiveElevatedClassLoaderFactory.class); } @Test - public void testClassReferenceTypeMatched() { - Plugin.Context context = mock(Plugin.Context.class); - Configuration configuration = mock(Configuration.class); + void testClassReferenceTypeMatched() { + Plugin.Context context = mock(); + Configuration configuration = mock(); when(context.getBootConfiguration()).thenReturn(configuration); - assertTrue(ProviderType.fromName("CLASS_REFERENCE") - .createFactory(context) instanceof ClassReferenceElevatedClassLoaderFactory); + assertThat(ProviderType.fromName("CLASS_REFERENCE") + .createFactory(context)).isInstanceOf(ClassReferenceElevatedClassLoaderFactory.class); } @Test - public void errorOnInvalidConfig() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage(IsEqual.equalTo("No provider with type 'xxx' could be found")); - - ProviderType.fromName("xxx"); + void errorOnInvalidConfig() { + assertThatThrownBy(() -> ProviderType.fromName("xxx")) + .isInstanceOf(IllegalStateException.class) + .hasMessage("No provider with type 'xxx' could be found") + .hasNoCause(); } } diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/classloader/ReflectiveElevatedClassLoaderFactoryTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/classloader/ReflectiveElevatedClassLoaderFactoryTest.java index 633f8f2d3..92048df15 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/classloader/ReflectiveElevatedClassLoaderFactoryTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/classloader/ReflectiveElevatedClassLoaderFactoryTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2020 Michael Clarke + * Copyright (C) 2020-2024 Michael Clarke * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -18,10 +18,10 @@ */ package com.github.mc1arke.sonarqube.plugin.classloader; -import org.hamcrest.core.IsEqual; -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 org.junit.jupiter.api.Test; import org.sonar.api.Plugin; import org.sonar.classloader.ClassloaderBuilder; import org.sonar.classloader.Mask; @@ -32,26 +32,14 @@ import java.net.URLClassLoader; import java.util.Map; -import static org.junit.Assert.assertNotSame; - -/** - * @author Michael Clarke - */ -public class ReflectiveElevatedClassLoaderFactoryTest { +class ReflectiveElevatedClassLoaderFactoryTest { private static final String TARGET_PLUGIN_CLASS = "org.sonar.plugins.java.JavaPlugin"; private static final String BUNDLED_PLUGINS_DIRECTORY = "lib/extensions"; private static final String SONARQUBE_LIB_DIRECTORY = "sonarqube-lib/"; - private final ExpectedException expectedException = ExpectedException.none(); - - @Rule - public ExpectedException expectedException() { - return expectedException; - } - @Test - public void testLoadClass() throws ClassNotFoundException, MalformedURLException { + void testLoadClass() throws ClassNotFoundException, MalformedURLException { ClassloaderBuilder builder = new ClassloaderBuilder(); builder.newClassloader("_api_", getClass().getClassLoader()); builder.setMask("_api_", Mask.builder().include("java/", "org/sonar/api/").build()); @@ -75,13 +63,13 @@ public void testLoadClass() throws ClassNotFoundException, MalformedURLException ReflectiveElevatedClassLoaderFactory testCase = new ReflectiveElevatedClassLoaderFactory(); ClassLoader elevatedLoader = testCase.createClassLoader(loadedClass); Class elevatedClass = elevatedLoader.loadClass(loadedClass.getName()); - // Getting closer than this is going to be difficult since the URLClassLoader that actually loads is an inner class of evelvatedClassLoader - assertNotSame(elevatedLoader, elevatedClass.getClassLoader()); + // Getting closer than this is going to be difficult since the URLClassLoader that actually loads is an inner class of elevatedClassLoader + assertThat(elevatedClass.getClassLoader()).isNotSameAs(elevatedLoader); } @Test - public void testLoadClassInvalidClassRealmKey() throws ClassNotFoundException, MalformedURLException { + void testLoadClassInvalidClassRealmKey() throws ClassNotFoundException, MalformedURLException { ClassloaderBuilder builder = new ClassloaderBuilder(); builder.newClassloader("_xxx_", getClass().getClassLoader()); builder.setMask("_xxx_", Mask.builder().include("java/", "org/sonar/api/").build()); @@ -102,17 +90,17 @@ public void testLoadClassInvalidClassRealmKey() throws ClassNotFoundException, M Class loadedClass = (Class) classLoader.loadClass(TARGET_PLUGIN_CLASS); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage(IsEqual.equalTo("Expected classloader with key '_api_' but found key '_xxx_'")); - ReflectiveElevatedClassLoaderFactory testCase = new ReflectiveElevatedClassLoaderFactory(); - testCase.createClassLoader(loadedClass); + assertThatThrownBy(() -> testCase.createClassLoader(loadedClass)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Expected classloader with key '_api_' but found key '_xxx_'") + .hasNoCause(); } @Test - public void testLoadClassNoParentRef() throws ClassNotFoundException, MalformedURLException { + void testLoadClassNoParentRef() throws ClassNotFoundException, MalformedURLException { ClassloaderBuilder builder = new ClassloaderBuilder(); builder.newClassloader("_xxx_", getClass().getClassLoader()); builder.setMask("_xxx_", Mask.ALL); @@ -129,16 +117,15 @@ public void testLoadClassNoParentRef() throws ClassNotFoundException, MalformedU Class loadedClass = (Class) classLoader.loadClass(TARGET_PLUGIN_CLASS); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage(IsEqual.equalTo("Could not access ClassLoader chain using reflection")); - ReflectiveElevatedClassLoaderFactory testCase = new ReflectiveElevatedClassLoaderFactory(); - testCase.createClassLoader(loadedClass); - + assertThatThrownBy(() -> testCase.createClassLoader(loadedClass)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Could not access ClassLoader chain using reflection") + .hasCause(new NoSuchFieldException("classloader")); } @Test - public void testLoadClassInvalidApiClassloader() throws ClassNotFoundException, MalformedURLException { + void testLoadClassInvalidApiClassloader() throws ClassNotFoundException, MalformedURLException { ClassloaderBuilder builder = new ClassloaderBuilder(); builder.newClassloader("_customPlugin"); builder.setParent("_customPlugin", new URLClassLoader(new URL[0]), Mask.ALL); @@ -156,17 +143,15 @@ public void testLoadClassInvalidApiClassloader() throws ClassNotFoundException, Class loadedClass = (Class) classLoader.loadClass(TARGET_PLUGIN_CLASS); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage(IsEqual.equalTo( - "Expected classloader of type 'org.sonar.classloader.ClassRealm' but got 'java.net.URLClassLoader'")); - ReflectiveElevatedClassLoaderFactory testCase = new ReflectiveElevatedClassLoaderFactory(); - testCase.createClassLoader(loadedClass); - + assertThatThrownBy(() -> testCase.createClassLoader(loadedClass)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Expected classloader of type 'org.sonar.classloader.ClassRealm' but got 'java.net.URLClassLoader'") + .hasNoCause(); } @Test - public void testLoadClassInvalidClassloader() throws ClassNotFoundException, MalformedURLException { + void testLoadClassInvalidClassloader() throws ClassNotFoundException, MalformedURLException { File[] sonarQubeDistributions = new File(SONARQUBE_LIB_DIRECTORY).listFiles(); File[] plugins = new File(sonarQubeDistributions[0], BUNDLED_PLUGINS_DIRECTORY).listFiles(); @@ -182,13 +167,11 @@ public void testLoadClassInvalidClassloader() throws ClassNotFoundException, Mal Class loadedClass = (Class) classLoader.loadClass(TARGET_PLUGIN_CLASS); - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage(IsEqual.equalTo( - "Expected classloader of type 'org.sonar.classloader.ClassRealm' but got 'java.net.URLClassLoader'")); - ReflectiveElevatedClassLoaderFactory testCase = new ReflectiveElevatedClassLoaderFactory(); - testCase.createClassLoader(loadedClass); - + assertThatThrownBy(() -> testCase.createClassLoader(loadedClass)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Expected classloader of type 'org.sonar.classloader.ClassRealm' but got 'java.net.URLClassLoader'") + .hasNoCause(); } } diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/scanner/BranchConfigurationFactoryTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/scanner/BranchConfigurationFactoryTest.java index 165e0a876..7b141124b 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/scanner/BranchConfigurationFactoryTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/scanner/BranchConfigurationFactoryTest.java @@ -35,7 +35,7 @@ class BranchConfigurationFactoryTest { @Test void shouldReturnBranchWithNoTargetIfNoProjectBranchesExist() { - ProjectBranches projectBranches = mock(ProjectBranches.class); + ProjectBranches projectBranches = mock(); when(projectBranches.isEmpty()).thenReturn(true); BranchConfigurationFactory underTest = new BranchConfigurationFactory(); @@ -46,7 +46,7 @@ void shouldReturnBranchWithNoTargetIfNoProjectBranchesExist() { @Test void shouldReturnBranchWithDefaultReferenceIfSpecifiedBranchDoesNotExist() { - ProjectBranches projectBranches = mock(ProjectBranches.class); + ProjectBranches projectBranches = mock(); when(projectBranches.isEmpty()).thenReturn(false); when(projectBranches.defaultBranchName()).thenReturn("default"); when(projectBranches.get(any())).thenReturn(null); @@ -59,10 +59,10 @@ void shouldReturnBranchWithDefaultReferenceIfSpecifiedBranchDoesNotExist() { @Test void shouldReturnBranchWithSelfReferenceIfSpecifiedBranchDoesExist() { - ProjectBranches projectBranches = mock(ProjectBranches.class); + ProjectBranches projectBranches = mock(); when(projectBranches.isEmpty()).thenReturn(false); when(projectBranches.defaultBranchName()).thenReturn("default"); - when(projectBranches.get(any())).thenReturn(mock(BranchInfo.class)); + when(projectBranches.get(any())).thenReturn(mock()); BranchConfigurationFactory underTest = new BranchConfigurationFactory(); BranchConfiguration actual = underTest.createBranchConfiguration("branch", projectBranches); @@ -72,7 +72,7 @@ void shouldReturnBranchWithSelfReferenceIfSpecifiedBranchDoesExist() { @Test void shouldThrowErrorIfAttemptingToCreatePullRequestWithNoTargetIfNoProjectBranchesExist() { - ProjectBranches projectBranches = mock(ProjectBranches.class); + ProjectBranches projectBranches = mock(); when(projectBranches.isEmpty()).thenReturn(true); when(projectBranches.defaultBranchName()).thenReturn("default-branch-name"); @@ -84,7 +84,7 @@ void shouldThrowErrorIfAttemptingToCreatePullRequestWithNoTargetIfNoProjectBranc @Test void shouldThrowErrorIfAttemptingToCreatePullRequestWithTargetIfNoProjectBranchesExist() { - ProjectBranches projectBranches = mock(ProjectBranches.class); + ProjectBranches projectBranches = mock(); when(projectBranches.isEmpty()).thenReturn(true); BranchConfigurationFactory underTest = new BranchConfigurationFactory(); @@ -95,7 +95,7 @@ void shouldThrowErrorIfAttemptingToCreatePullRequestWithTargetIfNoProjectBranche @Test void shouldThrowErrorIfAttemptingToCreatePullRequestWithTargetBranchThatDoesNotExist() { - ProjectBranches projectBranches = mock(ProjectBranches.class); + ProjectBranches projectBranches = mock(); when(projectBranches.isEmpty()).thenReturn(false); BranchConfigurationFactory underTest = new BranchConfigurationFactory(); @@ -106,7 +106,7 @@ void shouldThrowErrorIfAttemptingToCreatePullRequestWithTargetBranchThatDoesNotE @Test void shouldReturnPullRequestWithTargetOfDefaultBranchIfTargetNotSpecifiedAndDefaultExists() { - ProjectBranches projectBranches = mock(ProjectBranches.class); + ProjectBranches projectBranches = mock(); when(projectBranches.isEmpty()).thenReturn(false); when(projectBranches.defaultBranchName()).thenReturn("defaultBranch"); BranchInfo branchInfo = new BranchInfo("defaultBranch", BranchType.BRANCH, true, null); @@ -134,7 +134,7 @@ void shouldReturnPullRequestWithTargetOfDefaultBranchIfTargetDoesNotExistAndDefa @Test void shouldReturnPullRequestWithTargetOfTargetAsReferenceIfTargetBranchExists() { - ProjectBranches projectBranches = mock(ProjectBranches.class); + ProjectBranches projectBranches = mock(); when(projectBranches.isEmpty()).thenReturn(false); BranchInfo branchInfo = new BranchInfo("target", BranchType.PULL_REQUEST, false, "target2"); when(projectBranches.get("target")).thenReturn(branchInfo); @@ -149,7 +149,7 @@ void shouldReturnPullRequestWithTargetOfTargetAsReferenceIfTargetBranchExists() @Test void shouldThrowExceptionIfPullRequestTargetsOtherPullRequestWithoutATarget() { - ProjectBranches projectBranches = mock(ProjectBranches.class); + ProjectBranches projectBranches = mock(); when(projectBranches.isEmpty()).thenReturn(false); BranchInfo branchInfo = new BranchInfo("target", BranchType.PULL_REQUEST, false, null); when(projectBranches.get("target")).thenReturn(branchInfo); diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/scanner/CommunityBranchConfigurationLoaderTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/scanner/CommunityBranchConfigurationLoaderTest.java index f40ed851c..c98dca737 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/scanner/CommunityBranchConfigurationLoaderTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/scanner/CommunityBranchConfigurationLoaderTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2020-2023 Michael Clarke + * Copyright (C) 2020-2024 Michael Clarke * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -42,17 +42,17 @@ */ class CommunityBranchConfigurationLoaderTest { - private final System2 system2 = mock(System2.class); - private final BranchConfigurationFactory branchConfigurationFactory = mock(BranchConfigurationFactory.class); - private final BranchAutoConfigurer branchAutoConfigurer = mock(BranchAutoConfigurer.class); + private final System2 system2 = mock(); + private final BranchConfigurationFactory branchConfigurationFactory = mock(); + private final BranchAutoConfigurer branchAutoConfigurer = mock(); private final BranchConfigurationLoader testCase = new CommunityBranchConfigurationLoader(system2, branchConfigurationFactory, List.of(branchAutoConfigurer)); @Test void shouldReturnResultFromAutoConfigurerIfPresentAndNoParametersSpecified() { - BranchConfiguration branchConfiguration = mock(BranchConfiguration.class); + BranchConfiguration branchConfiguration = mock(); when(branchAutoConfigurer.detectConfiguration(any(), any())).thenReturn(Optional.of(branchConfiguration)); - ProjectBranches projectBranches = mock(ProjectBranches.class); + ProjectBranches projectBranches = mock(); BranchConfiguration actual = testCase.load(Map.of(), projectBranches); @@ -65,7 +65,7 @@ void shouldReturnResultFromAutoConfigurerIfPresentAndNoParametersSpecified() { void shouldReturnDefaultBranchIfAutoConfigurerNoResultAndNoParametersSpecified() { when(branchAutoConfigurer.detectConfiguration(any(), any())).thenReturn(Optional.empty()); - ProjectBranches projectBranches = mock(ProjectBranches.class); + ProjectBranches projectBranches = mock(); BranchConfiguration actual = testCase.load(Map.of(), projectBranches); @@ -76,8 +76,8 @@ void shouldReturnDefaultBranchIfAutoConfigurerNoResultAndNoParametersSpecified() @Test void shouldCreateBranchConfigurationIfAnyBranchPropertiesSet() { - ProjectBranches projectBranches = mock(ProjectBranches.class); - BranchConfiguration branchConfiguration = mock(BranchConfiguration.class); + ProjectBranches projectBranches = mock(); + BranchConfiguration branchConfiguration = mock(); when(branchConfigurationFactory.createBranchConfiguration(any(), any())).thenReturn(branchConfiguration); BranchConfiguration actual = testCase.load(Map.of("sonar.branch.name", "branch", "sonar.branch.target", "target"), projectBranches); @@ -89,8 +89,8 @@ void shouldCreateBranchConfigurationIfAnyBranchPropertiesSet() { @Test void shouldCreatePullConfigurationIfAnyPullRequestPropertiesSet() { - ProjectBranches projectBranches = mock(ProjectBranches.class); - BranchConfiguration branchConfiguration = mock(BranchConfiguration.class); + ProjectBranches projectBranches = mock(); + BranchConfiguration branchConfiguration = mock(); when(branchConfigurationFactory.createPullRequestConfiguration(any(), any(), any(), any())).thenReturn(branchConfiguration); BranchConfiguration actual = testCase.load(Map.of("sonar.pullrequest.key", "key", "sonar.pullrequest.branch", "source", "sonar.pullrequest.base", "target"), projectBranches); @@ -102,17 +102,17 @@ void shouldCreatePullConfigurationIfAnyPullRequestPropertiesSet() { @Test void shouldThrowErrorIfBothBranchAndPullRequestParametersPresent() { - assertThatThrownBy(() -> testCase.load(Map.of("sonar.pullrequest.key", "key", "sonar.pullrequest.branch", "source", "sonar.branch.name", "branch"), mock(ProjectBranches.class))).hasMessage("sonar.pullrequest and sonar.branch parameters should not be specified in the same scan"); + assertThatThrownBy(() -> testCase.load(Map.of("sonar.pullrequest.key", "key", "sonar.pullrequest.branch", "source", "sonar.branch.name", "branch"), mock())).hasMessage("sonar.pullrequest and sonar.branch parameters should not be specified in the same scan"); } @Test void shouldThrowErrorIfPullRequestAnalysisWithoutPullRequestKey() { - assertThatThrownBy(() -> testCase.load(Map.of("sonar.pullrequest.base", "target"), mock(ProjectBranches.class))).hasMessage("sonar.pullrequest.key is required for a pull request analysis"); + assertThatThrownBy(() -> testCase.load(Map.of("sonar.pullrequest.base", "target"), mock())).hasMessage("sonar.pullrequest.key is required for a pull request analysis"); } @Test void shouldThrowErrorIfPullRequestAnalysisWithoutPullRequestBranch() { - assertThatThrownBy(() -> testCase.load(Map.of("sonar.pullrequest.key", "key"), mock(ProjectBranches.class))).hasMessage("sonar.pullrequest.branch is required for a pull request analysis"); + assertThatThrownBy(() -> testCase.load(Map.of("sonar.pullrequest.key", "key"), mock())).hasMessage("sonar.pullrequest.branch is required for a pull request analysis"); } } diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/scanner/CommunityBranchParamsValidatorTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/scanner/CommunityBranchParamsValidatorTest.java index ec00da402..af2832223 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/scanner/CommunityBranchParamsValidatorTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/scanner/CommunityBranchParamsValidatorTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2020 Michael Clarke + * Copyright (C) 2020-2024 Michael Clarke * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -18,23 +18,20 @@ */ package com.github.mc1arke.sonarqube.plugin.scanner; -import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.List; -import static org.junit.Assert.assertEquals; +import org.junit.jupiter.api.Test; -/** - * @author Michael Clarke - */ -public class CommunityBranchParamsValidatorTest { +class CommunityBranchParamsValidatorTest { @Test - public void testNoMessagesOnValidate() { + void shouldReturnNoValidationMessageOnValidData() { List messages = new ArrayList<>(); new CommunityBranchParamsValidator().validate(messages); - assertEquals(0, messages.size()); + assertThat(messages).isEmpty(); } } diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/scanner/CommunityRepositoryBranchesLoaderTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/scanner/CommunityRepositoryBranchesLoaderTest.java index 57f62c2e2..4af9c261b 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/scanner/CommunityRepositoryBranchesLoaderTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/scanner/CommunityRepositoryBranchesLoaderTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2020 Michael Clarke + * Copyright (C) 2020-2024 Michael Clarke * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -18,9 +18,7 @@ */ package com.github.mc1arke.sonarqube.plugin.scanner; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; import org.sonar.api.utils.MessageException; import org.sonar.scanner.http.ScannerWsClient; import org.sonar.scanner.protocol.GsonHelper; @@ -37,30 +35,19 @@ import java.util.ArrayList; import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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; -/** - * @author Michael Clarke - */ -public class CommunityRepositoryBranchesLoaderTest { - - private final ScannerWsClient scannerWsClient = mock(ScannerWsClient.class); - private final ExpectedException expectedException = ExpectedException.none(); +class CommunityRepositoryBranchesLoaderTest { - @Rule - public ExpectedException expectedException() { - return expectedException; - } + private final ScannerWsClient scannerWsClient = mock(); @Test - public void testEmptyBranchesOnEmptyServerResponse() { - WsResponse mockResponse = mock(WsResponse.class); + void shouldReturnEmptyBranchesOnEmptyServerResponse() { + WsResponse mockResponse = mock(); when(scannerWsClient.call(any())).thenReturn(mockResponse); StringReader stringReader = new StringReader( @@ -69,12 +56,12 @@ public void testEmptyBranchesOnEmptyServerResponse() { CommunityProjectBranchesLoader testCase = new CommunityProjectBranchesLoader(scannerWsClient); ProjectBranches response = testCase.load("projectKey"); - assertTrue(response.isEmpty()); + assertThat(response.isEmpty()).isTrue(); } @Test - public void testAllBranchesFromNonEmptyServerResponse() { - WsResponse mockResponse = mock(WsResponse.class); + void shouldReturnAllBranchesFromNonEmptyServerResponse() { + WsResponse mockResponse = mock(); when(scannerWsClient.call(any())).thenReturn(mockResponse); List infos = new ArrayList<>(); @@ -88,66 +75,66 @@ public void testAllBranchesFromNonEmptyServerResponse() { CommunityProjectBranchesLoader testCase = new CommunityProjectBranchesLoader(scannerWsClient); ProjectBranches response = testCase.load("key"); - assertFalse(response.isEmpty()); + assertThat(response.isEmpty()).isFalse(); for (BranchInfo info : infos) { BranchInfo responseInfo = response.get(info.name()); - assertNotNull(responseInfo); - assertEquals(info.branchTargetName(), responseInfo.branchTargetName()); - assertEquals(info.isMain(), responseInfo.isMain()); - assertEquals(info.name(), responseInfo.name()); - assertEquals(info.type(), responseInfo.type()); + assertThat(responseInfo).isNotNull(); + assertThat(responseInfo.branchTargetName()).isEqualTo(info.branchTargetName()); + assertThat(responseInfo.isMain()).isEqualTo(info.isMain()); + assertThat(responseInfo.name()).isEqualTo(info.name()); + assertThat(responseInfo.type()).isEqualTo(info.type()); } } @Test - public void testMessageExceptionOnIOException() { - WsResponse mockResponse = mock(WsResponse.class); + void shouldThrowMessageExceptionOnIOException() { + WsResponse mockResponse = mock(); when(scannerWsClient.call(any())).thenReturn(mockResponse); Reader mockReader = new BufferedReader(new StringReader( GsonHelper.create().toJson(new CommunityProjectBranchesLoader.BranchesResponse(new ArrayList<>())))) { + @Override public void close() throws IOException { throw new IOException("Dummy IO Exception"); } }; when(mockResponse.contentReader()).thenReturn(mockReader); - expectedException.expectMessage("Could not load branches from server"); - expectedException.expect(MessageException.class); - CommunityProjectBranchesLoader testCase = new CommunityProjectBranchesLoader(scannerWsClient); - testCase.load("project"); - - + assertThatThrownBy(() -> testCase.load("project")) + .isInstanceOf(MessageException.class) + .hasMessage("Could not load branches from server") + .hasCause(new IOException("Dummy IO Exception")); } @Test - public void testErrorOnNon404HttpResponse() { - WsResponse mockResponse = mock(WsResponse.class); + void shouldThrowExceptionOnNon404HttpResponse() { + WsResponse mockResponse = mock(); when(scannerWsClient.call(any())).thenReturn(mockResponse); Reader mockReader = new BufferedReader(new StringReader( GsonHelper.create().toJson(new CommunityProjectBranchesLoader.BranchesResponse(new ArrayList<>())))) { + @Override public void close() { throw new HttpException("url", 12, "content"); } }; when(mockResponse.contentReader()).thenReturn(mockReader); - expectedException.expectMessage("Could not load branches from server"); - expectedException.expect(MessageException.class); - CommunityProjectBranchesLoader testCase = new CommunityProjectBranchesLoader(scannerWsClient); - testCase.load("project"); + assertThatThrownBy(() ->testCase.load("project")) + .isInstanceOf(MessageException.class) + .hasMessage("Could not load branches from server") + .hasCause(new HttpException("url", 12, "content")); } @Test - public void testEmptyListOn404HttpResponse() { + void shouldReturnEmptyListOn404HttpResponse() { when(scannerWsClient.call(any())).thenThrow(new HttpException("url", 404, "content")); CommunityProjectBranchesLoader testCase = new CommunityProjectBranchesLoader(scannerWsClient); - assertTrue(testCase.load("project").isEmpty()); + assertThat(testCase.load("project").isEmpty()).isTrue(); } } diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/scanner/ScannerPullRequestPropertySensorTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/scanner/ScannerPullRequestPropertySensorTest.java index 3da1a8ea1..147cff1ae 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/scanner/ScannerPullRequestPropertySensorTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/scanner/ScannerPullRequestPropertySensorTest.java @@ -1,8 +1,24 @@ +/* + * Copyright (C) 2020-2024 Michael Clarke + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ package com.github.mc1arke.sonarqube.plugin.scanner; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; import org.sonar.api.batch.fs.internal.DefaultInputFile; import org.sonar.api.batch.fs.internal.TestInputFileBuilder; import org.sonar.api.batch.sensor.internal.SensorContextTester; @@ -13,23 +29,17 @@ import java.nio.file.Path; import java.util.Map; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -public class ScannerPullRequestPropertySensorTest { +class ScannerPullRequestPropertySensorTest { - private final System2 system2 = mock(System2.class); - private final ExpectedException expectedException = ExpectedException.none(); + private final System2 system2 = mock(); private final ScannerPullRequestPropertySensor sensor = new ScannerPullRequestPropertySensor(system2); - @Rule - public ExpectedException expectedException() { - return expectedException; - } - @Test - public void testPropertySensorWithGitlabCIEnvValues() throws IOException { + void testPropertySensorWithGitlabCIEnvValues() throws IOException { Path temp = Files.createTempDirectory("sensor"); @@ -47,11 +57,11 @@ public void testPropertySensorWithGitlabCIEnvValues() throws IOException { Map properties = context.getContextProperties(); - assertEquals(2, properties.size()); + assertThat(properties).hasSize(2); } @Test - public void testPropertySensorWithGitlabEnvValues() throws IOException { + void testPropertySensorWithGitlabEnvValues() throws IOException { Path temp = Files.createTempDirectory("sensor"); @@ -67,6 +77,6 @@ public void testPropertySensorWithGitlabEnvValues() throws IOException { Map properties = context.getContextProperties(); - assertEquals(2, properties.size()); + assertThat(properties).hasSize(2); } } diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/scanner/autoconfiguration/AzureDevopsAutoConfigurerTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/scanner/autoconfiguration/AzureDevopsAutoConfigurerTest.java index 9a7577aeb..3d9b1c61c 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/scanner/autoconfiguration/AzureDevopsAutoConfigurerTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/scanner/autoconfiguration/AzureDevopsAutoConfigurerTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2022 Michael Clarke + * Copyright (C) 2022-2024 Michael Clarke * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -34,9 +34,9 @@ class AzureDevopsAutoConfigurerTest { @Test void shouldReturnOptionalEmptyIfNotTfBuild() { - System2 system2 = mock(System2.class); - BranchConfigurationFactory branchConfigurationFactory = mock(BranchConfigurationFactory.class); - ProjectBranches projectBranches = mock(ProjectBranches.class); + System2 system2 = mock(); + BranchConfigurationFactory branchConfigurationFactory = mock(); + ProjectBranches projectBranches = mock(); AzureDevopsAutoConfigurer underTest = new AzureDevopsAutoConfigurer(branchConfigurationFactory); assertThat(underTest.detectConfiguration(system2, projectBranches)).isEmpty(); @@ -44,10 +44,10 @@ void shouldReturnOptionalEmptyIfNotTfBuild() { @Test void shouldReturnOptionalEmptyIfTfBuildWithNoPullRequestId() { - System2 system2 = mock(System2.class); + System2 system2 = mock(); when(system2.envVariable("TF_BUILD")).thenReturn("true"); - BranchConfigurationFactory branchConfigurationFactory = mock(BranchConfigurationFactory.class); - ProjectBranches projectBranches = mock(ProjectBranches.class); + BranchConfigurationFactory branchConfigurationFactory = mock(); + ProjectBranches projectBranches = mock(); AzureDevopsAutoConfigurer underTest = new AzureDevopsAutoConfigurer(branchConfigurationFactory); assertThat(underTest.detectConfiguration(system2, projectBranches)).isEmpty(); @@ -55,15 +55,15 @@ void shouldReturnOptionalEmptyIfTfBuildWithNoPullRequestId() { @Test void shouldReturnConfigurationBasedOnAllEnvironmentParameters() { - System2 system2 = mock(System2.class); + System2 system2 = mock(); when(system2.envVariable("TF_BUILD")).thenReturn("true"); when(system2.envVariable("SYSTEM_PULLREQUEST_PULLREQUESTID")).thenReturn("id"); when(system2.envVariable("SYSTEM_PULLREQUEST_SOURCEBRANCH")).thenReturn("source"); when(system2.envVariable("SYSTEM_PULLREQUEST_TARGETBRANCH")).thenReturn("target"); - BranchConfigurationFactory branchConfigurationFactory = mock(BranchConfigurationFactory.class); - BranchConfiguration branchConfiguration = mock(BranchConfiguration.class); + BranchConfigurationFactory branchConfigurationFactory = mock(); + BranchConfiguration branchConfiguration = mock(); when(branchConfigurationFactory.createPullRequestConfiguration(any(), any(), any(), any())).thenReturn(branchConfiguration); - ProjectBranches projectBranches = mock(ProjectBranches.class); + ProjectBranches projectBranches = mock(); AzureDevopsAutoConfigurer underTest = new AzureDevopsAutoConfigurer(branchConfigurationFactory); assertThat(underTest.detectConfiguration(system2, projectBranches)).contains(branchConfiguration); diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/scanner/autoconfiguration/BitbucketPipelinesAutoConfigurerTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/scanner/autoconfiguration/BitbucketPipelinesAutoConfigurerTest.java index ee0710762..64e3309c4 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/scanner/autoconfiguration/BitbucketPipelinesAutoConfigurerTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/scanner/autoconfiguration/BitbucketPipelinesAutoConfigurerTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2022 Michael Clarke + * Copyright (C) 2022-2024 Michael Clarke * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -34,9 +34,9 @@ class BitbucketPipelinesAutoConfigurerTest { @Test void shouldReturnOptionalEmptyIfNotCi() { - System2 system2 = mock(System2.class); - BranchConfigurationFactory branchConfigurationFactory = mock(BranchConfigurationFactory.class); - ProjectBranches projectBranches = mock(ProjectBranches.class); + System2 system2 = mock(); + BranchConfigurationFactory branchConfigurationFactory = mock(); + ProjectBranches projectBranches = mock(); BitbucketPipelinesAutoConfigurer underTest = new BitbucketPipelinesAutoConfigurer(branchConfigurationFactory); assertThat(underTest.detectConfiguration(system2, projectBranches)).isEmpty(); @@ -44,10 +44,10 @@ void shouldReturnOptionalEmptyIfNotCi() { @Test void shouldReturnOptionalEmptyIfCiWithNoBranchProperty() { - System2 system2 = mock(System2.class); + System2 system2 = mock(); when(system2.envVariable("CI")).thenReturn("true"); - BranchConfigurationFactory branchConfigurationFactory = mock(BranchConfigurationFactory.class); - ProjectBranches projectBranches = mock(ProjectBranches.class); + BranchConfigurationFactory branchConfigurationFactory = mock(); + ProjectBranches projectBranches = mock(); BitbucketPipelinesAutoConfigurer underTest = new BitbucketPipelinesAutoConfigurer(branchConfigurationFactory); assertThat(underTest.detectConfiguration(system2, projectBranches)).isEmpty(); @@ -55,13 +55,13 @@ void shouldReturnOptionalEmptyIfCiWithNoBranchProperty() { @Test void shouldReturnBranchConfigurationBasedOnNoPrIdInEnvironmentParameters() { - System2 system2 = mock(System2.class); + System2 system2 = mock(); when(system2.envVariable("CI")).thenReturn("true"); when(system2.envVariable("BITBUCKET_BRANCH")).thenReturn("branch"); - BranchConfigurationFactory branchConfigurationFactory = mock(BranchConfigurationFactory.class); - BranchConfiguration branchConfiguration = mock(BranchConfiguration.class); + BranchConfigurationFactory branchConfigurationFactory = mock(); + BranchConfiguration branchConfiguration = mock(); when(branchConfigurationFactory.createBranchConfiguration(any(), any())).thenReturn(branchConfiguration); - ProjectBranches projectBranches = mock(ProjectBranches.class); + ProjectBranches projectBranches = mock(); BitbucketPipelinesAutoConfigurer underTest = new BitbucketPipelinesAutoConfigurer(branchConfigurationFactory); assertThat(underTest.detectConfiguration(system2, projectBranches)).contains(branchConfiguration); @@ -70,15 +70,15 @@ void shouldReturnBranchConfigurationBasedOnNoPrIdInEnvironmentParameters() { @Test void shouldReturnPullRequestConfigurationBasedOnPrIdInEnvironmentParameters() { - System2 system2 = mock(System2.class); + System2 system2 = mock(); when(system2.envVariable("CI")).thenReturn("true"); when(system2.envVariable("BITBUCKET_BRANCH")).thenReturn("source"); when(system2.envVariable("BITBUCKET_PR_ID")).thenReturn("id"); when(system2.envVariable("BITBUCKET_PR_DESTINATION_BRANCH")).thenReturn("target"); - BranchConfigurationFactory branchConfigurationFactory = mock(BranchConfigurationFactory.class); - BranchConfiguration branchConfiguration = mock(BranchConfiguration.class); + BranchConfigurationFactory branchConfigurationFactory = mock(); + BranchConfiguration branchConfiguration = mock(); when(branchConfigurationFactory.createPullRequestConfiguration(any(), any(), any(), any())).thenReturn(branchConfiguration); - ProjectBranches projectBranches = mock(ProjectBranches.class); + ProjectBranches projectBranches = mock(); BitbucketPipelinesAutoConfigurer underTest = new BitbucketPipelinesAutoConfigurer(branchConfigurationFactory); assertThat(underTest.detectConfiguration(system2, projectBranches)).contains(branchConfiguration); diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/scanner/autoconfiguration/CirrusCiAutoConfigurerTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/scanner/autoconfiguration/CirrusCiAutoConfigurerTest.java index 38f326ce4..488fad812 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/scanner/autoconfiguration/CirrusCiAutoConfigurerTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/scanner/autoconfiguration/CirrusCiAutoConfigurerTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2022 Michael Clarke + * Copyright (C) 2022-2024 Michael Clarke * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -34,9 +34,9 @@ class CirrusCiAutoConfigurerTest { @Test void shouldReturnOptionalEmptyIfNotCirrusCi() { - System2 system2 = mock(System2.class); - BranchConfigurationFactory branchConfigurationFactory = mock(BranchConfigurationFactory.class); - ProjectBranches projectBranches = mock(ProjectBranches.class); + System2 system2 = mock(); + BranchConfigurationFactory branchConfigurationFactory = mock(); + ProjectBranches projectBranches = mock(); CirrusCiAutoConfigurer underTest = new CirrusCiAutoConfigurer(branchConfigurationFactory); assertThat(underTest.detectConfiguration(system2, projectBranches)).isEmpty(); @@ -44,10 +44,10 @@ void shouldReturnOptionalEmptyIfNotCirrusCi() { @Test void shouldReturnOptionalEmptyIfCirrusCiWithNoBranchProperty() { - System2 system2 = mock(System2.class); + System2 system2 = mock(); when(system2.envVariable("CIRRUS_CI")).thenReturn("true"); - BranchConfigurationFactory branchConfigurationFactory = mock(BranchConfigurationFactory.class); - ProjectBranches projectBranches = mock(ProjectBranches.class); + BranchConfigurationFactory branchConfigurationFactory = mock(); + ProjectBranches projectBranches = mock(); CirrusCiAutoConfigurer underTest = new CirrusCiAutoConfigurer(branchConfigurationFactory); assertThat(underTest.detectConfiguration(system2, projectBranches)).isEmpty(); @@ -55,13 +55,13 @@ void shouldReturnOptionalEmptyIfCirrusCiWithNoBranchProperty() { @Test void shouldReturnBranchConfigurationBasedOnNoPrIdInEnvironmentParameters() { - System2 system2 = mock(System2.class); + System2 system2 = mock(); when(system2.envVariable("CIRRUS_CI")).thenReturn("true"); when(system2.envVariable("CIRRUS_BRANCH")).thenReturn("branch"); - BranchConfigurationFactory branchConfigurationFactory = mock(BranchConfigurationFactory.class); - BranchConfiguration branchConfiguration = mock(BranchConfiguration.class); + BranchConfigurationFactory branchConfigurationFactory = mock(); + BranchConfiguration branchConfiguration = mock(); when(branchConfigurationFactory.createBranchConfiguration(any(), any())).thenReturn(branchConfiguration); - ProjectBranches projectBranches = mock(ProjectBranches.class); + ProjectBranches projectBranches = mock(); CirrusCiAutoConfigurer underTest = new CirrusCiAutoConfigurer(branchConfigurationFactory); assertThat(underTest.detectConfiguration(system2, projectBranches)).contains(branchConfiguration); @@ -70,15 +70,15 @@ void shouldReturnBranchConfigurationBasedOnNoPrIdInEnvironmentParameters() { @Test void shouldReturnPullRequestConfigurationBasedOnPrIdInEnvironmentParameters() { - System2 system2 = mock(System2.class); + System2 system2 = mock(); when(system2.envVariable("CIRRUS_CI")).thenReturn("true"); when(system2.envVariable("CIRRUS_BRANCH")).thenReturn("source"); when(system2.envVariable("CIRRUS_PR")).thenReturn("id"); when(system2.envVariable("CIRRUS_BASE_BRANCH")).thenReturn("target"); - BranchConfigurationFactory branchConfigurationFactory = mock(BranchConfigurationFactory.class); - BranchConfiguration branchConfiguration = mock(BranchConfiguration.class); + BranchConfigurationFactory branchConfigurationFactory = mock(); + BranchConfiguration branchConfiguration = mock(); when(branchConfigurationFactory.createPullRequestConfiguration(any(), any(), any(), any())).thenReturn(branchConfiguration); - ProjectBranches projectBranches = mock(ProjectBranches.class); + ProjectBranches projectBranches = mock(); CirrusCiAutoConfigurer underTest = new CirrusCiAutoConfigurer(branchConfigurationFactory); assertThat(underTest.detectConfiguration(system2, projectBranches)).contains(branchConfiguration); diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/scanner/autoconfiguration/CodeMagicAutoConfigurerTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/scanner/autoconfiguration/CodeMagicAutoConfigurerTest.java index 8a99fcc23..5bc4e8333 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/scanner/autoconfiguration/CodeMagicAutoConfigurerTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/scanner/autoconfiguration/CodeMagicAutoConfigurerTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2022 Michael Clarke + * Copyright (C) 2022-2024 Michael Clarke * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -34,9 +34,9 @@ class CodeMagicAutoConfigurerTest { @Test void shouldReturnOptionalEmptyIfNotCi() { - System2 system2 = mock(System2.class); - BranchConfigurationFactory branchConfigurationFactory = mock(BranchConfigurationFactory.class); - ProjectBranches projectBranches = mock(ProjectBranches.class); + System2 system2 = mock(); + BranchConfigurationFactory branchConfigurationFactory = mock(); + ProjectBranches projectBranches = mock(); CodeMagicAutoConfigurer underTest = new CodeMagicAutoConfigurer(branchConfigurationFactory); assertThat(underTest.detectConfiguration(system2, projectBranches)).isEmpty(); @@ -44,10 +44,10 @@ void shouldReturnOptionalEmptyIfNotCi() { @Test void shouldReturnOptionalEmptyIfCiWithNoFciBranchProperty() { - System2 system2 = mock(System2.class); + System2 system2 = mock(); when(system2.envVariable("CI")).thenReturn("true"); - BranchConfigurationFactory branchConfigurationFactory = mock(BranchConfigurationFactory.class); - ProjectBranches projectBranches = mock(ProjectBranches.class); + BranchConfigurationFactory branchConfigurationFactory = mock(); + ProjectBranches projectBranches = mock(); CodeMagicAutoConfigurer underTest = new CodeMagicAutoConfigurer(branchConfigurationFactory); assertThat(underTest.detectConfiguration(system2, projectBranches)).isEmpty(); @@ -55,13 +55,13 @@ void shouldReturnOptionalEmptyIfCiWithNoFciBranchProperty() { @Test void shouldReturnBranchConfigurationBasedOnNoPrIdInEnvironmentParameters() { - System2 system2 = mock(System2.class); + System2 system2 = mock(); when(system2.envVariable("CI")).thenReturn("true"); when(system2.envVariable("FCI_BRANCH")).thenReturn("branch"); - BranchConfigurationFactory branchConfigurationFactory = mock(BranchConfigurationFactory.class); - BranchConfiguration branchConfiguration = mock(BranchConfiguration.class); + BranchConfigurationFactory branchConfigurationFactory = mock(); + BranchConfiguration branchConfiguration = mock(); when(branchConfigurationFactory.createBranchConfiguration(any(), any())).thenReturn(branchConfiguration); - ProjectBranches projectBranches = mock(ProjectBranches.class); + ProjectBranches projectBranches = mock(); CodeMagicAutoConfigurer underTest = new CodeMagicAutoConfigurer(branchConfigurationFactory); assertThat(underTest.detectConfiguration(system2, projectBranches)).contains(branchConfiguration); @@ -70,16 +70,16 @@ void shouldReturnBranchConfigurationBasedOnNoPrIdInEnvironmentParameters() { @Test void shouldReturnPullRequestConfigurationBasedOnPrIdInEnvironmentParameters() { - System2 system2 = mock(System2.class); + System2 system2 = mock(); when(system2.envVariable("CI")).thenReturn("true"); when(system2.envVariable("FCI_BRANCH")).thenReturn("source"); when(system2.envVariable("FCI_PULL_REQUEST")).thenReturn("true"); when(system2.envVariable("FCI_PULL_REQUEST_NUMBER")).thenReturn("id"); when(system2.envVariable("FCI_PULL_REQUEST_DEST")).thenReturn("target"); - BranchConfigurationFactory branchConfigurationFactory = mock(BranchConfigurationFactory.class); - BranchConfiguration branchConfiguration = mock(BranchConfiguration.class); + BranchConfigurationFactory branchConfigurationFactory = mock(); + BranchConfiguration branchConfiguration = mock(); when(branchConfigurationFactory.createPullRequestConfiguration(any(), any(), any(), any())).thenReturn(branchConfiguration); - ProjectBranches projectBranches = mock(ProjectBranches.class); + ProjectBranches projectBranches = mock(); CodeMagicAutoConfigurer underTest = new CodeMagicAutoConfigurer(branchConfigurationFactory); assertThat(underTest.detectConfiguration(system2, projectBranches)).contains(branchConfiguration); diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/scanner/autoconfiguration/GithubActionsAutoConfigurerTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/scanner/autoconfiguration/GithubActionsAutoConfigurerTest.java index 54b04d6e1..006ae8c4a 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/scanner/autoconfiguration/GithubActionsAutoConfigurerTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/scanner/autoconfiguration/GithubActionsAutoConfigurerTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2022 Michael Clarke + * Copyright (C) 2022-2024 Michael Clarke * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -34,9 +34,9 @@ class GithubActionsAutoConfigurerTest { @Test void shouldReturnOptionalEmptyIfNotGithubActions() { - System2 system2 = mock(System2.class); - BranchConfigurationFactory branchConfigurationFactory = mock(BranchConfigurationFactory.class); - ProjectBranches projectBranches = mock(ProjectBranches.class); + System2 system2 = mock(); + BranchConfigurationFactory branchConfigurationFactory = mock(); + ProjectBranches projectBranches = mock(); GithubActionsAutoConfigurer underTest = new GithubActionsAutoConfigurer(branchConfigurationFactory); assertThat(underTest.detectConfiguration(system2, projectBranches)).isEmpty(); @@ -44,10 +44,10 @@ void shouldReturnOptionalEmptyIfNotGithubActions() { @Test void shouldReturnOptionalEmptyIfGithubActionsWithNoGithubRefProperty() { - System2 system2 = mock(System2.class); + System2 system2 = mock(); when(system2.envVariable("GITHUB_ACTIONS")).thenReturn("true"); - BranchConfigurationFactory branchConfigurationFactory = mock(BranchConfigurationFactory.class); - ProjectBranches projectBranches = mock(ProjectBranches.class); + BranchConfigurationFactory branchConfigurationFactory = mock(); + ProjectBranches projectBranches = mock(); GithubActionsAutoConfigurer underTest = new GithubActionsAutoConfigurer(branchConfigurationFactory); assertThat(underTest.detectConfiguration(system2, projectBranches)).isEmpty(); @@ -55,14 +55,14 @@ void shouldReturnOptionalEmptyIfGithubActionsWithNoGithubRefProperty() { @Test void shouldReturnBranchConfigurationBasedOnNoPrIdInEnvironmentParameters() { - System2 system2 = mock(System2.class); + System2 system2 = mock(); when(system2.envVariable("GITHUB_ACTIONS")).thenReturn("true"); when(system2.envVariable("GITHUB_REF")).thenReturn("refs/heads/branch"); when(system2.envVariable("GITHUB_REF_NAME")).thenReturn("branch"); - BranchConfigurationFactory branchConfigurationFactory = mock(BranchConfigurationFactory.class); - BranchConfiguration branchConfiguration = mock(BranchConfiguration.class); + BranchConfigurationFactory branchConfigurationFactory = mock(); + BranchConfiguration branchConfiguration = mock(); when(branchConfigurationFactory.createBranchConfiguration(any(), any())).thenReturn(branchConfiguration); - ProjectBranches projectBranches = mock(ProjectBranches.class); + ProjectBranches projectBranches = mock(); GithubActionsAutoConfigurer underTest = new GithubActionsAutoConfigurer(branchConfigurationFactory); assertThat(underTest.detectConfiguration(system2, projectBranches)).contains(branchConfiguration); @@ -71,15 +71,15 @@ void shouldReturnBranchConfigurationBasedOnNoPrIdInEnvironmentParameters() { @Test void shouldReturnPullRequestConfigurationBasedOnPrIdInEnvironmentParameters() { - System2 system2 = mock(System2.class); + System2 system2 = mock(); when(system2.envVariable("GITHUB_ACTIONS")).thenReturn("true"); when(system2.envVariable("GITHUB_HEAD_REF")).thenReturn("source"); when(system2.envVariable("GITHUB_REF")).thenReturn("refs/pull/id/merge"); when(system2.envVariable("GITHUB_BASE_REF")).thenReturn("target"); - BranchConfigurationFactory branchConfigurationFactory = mock(BranchConfigurationFactory.class); - BranchConfiguration branchConfiguration = mock(BranchConfiguration.class); + BranchConfigurationFactory branchConfigurationFactory = mock(); + BranchConfiguration branchConfiguration = mock(); when(branchConfigurationFactory.createPullRequestConfiguration(any(), any(), any(), any())).thenReturn(branchConfiguration); - ProjectBranches projectBranches = mock(ProjectBranches.class); + ProjectBranches projectBranches = mock(); GithubActionsAutoConfigurer underTest = new GithubActionsAutoConfigurer(branchConfigurationFactory); assertThat(underTest.detectConfiguration(system2, projectBranches)).contains(branchConfiguration); diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/scanner/autoconfiguration/GitlabCiAutoConfigurerTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/scanner/autoconfiguration/GitlabCiAutoConfigurerTest.java index 4fa565255..e04c2b6e6 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/scanner/autoconfiguration/GitlabCiAutoConfigurerTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/scanner/autoconfiguration/GitlabCiAutoConfigurerTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2022 Michael Clarke + * Copyright (C) 2022-2024 Michael Clarke * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -34,9 +34,9 @@ class GitlabCiAutoConfigurerTest { @Test void shouldReturnOptionalEmptyIfNotGitlabCi() { - System2 system2 = mock(System2.class); - BranchConfigurationFactory branchConfigurationFactory = mock(BranchConfigurationFactory.class); - ProjectBranches projectBranches = mock(ProjectBranches.class); + System2 system2 = mock(); + BranchConfigurationFactory branchConfigurationFactory = mock(); + ProjectBranches projectBranches = mock(); GitlabCiAutoConfigurer underTest = new GitlabCiAutoConfigurer(branchConfigurationFactory); assertThat(underTest.detectConfiguration(system2, projectBranches)).isEmpty(); @@ -44,13 +44,13 @@ void shouldReturnOptionalEmptyIfNotGitlabCi() { @Test void shouldReturnBranchConfigurationBasedOnNoPrIdInEnvironmentParameters() { - System2 system2 = mock(System2.class); + System2 system2 = mock(); when(system2.envVariable("GITLAB_CI")).thenReturn("true"); when(system2.envVariable("CI_COMMIT_REF_NAME")).thenReturn("branch"); - BranchConfigurationFactory branchConfigurationFactory = mock(BranchConfigurationFactory.class); - BranchConfiguration branchConfiguration = mock(BranchConfiguration.class); + BranchConfigurationFactory branchConfigurationFactory = mock(); + BranchConfiguration branchConfiguration = mock(); when(branchConfigurationFactory.createBranchConfiguration(any(), any())).thenReturn(branchConfiguration); - ProjectBranches projectBranches = mock(ProjectBranches.class); + ProjectBranches projectBranches = mock(); GitlabCiAutoConfigurer underTest = new GitlabCiAutoConfigurer(branchConfigurationFactory); assertThat(underTest.detectConfiguration(system2, projectBranches)).contains(branchConfiguration); @@ -59,15 +59,15 @@ void shouldReturnBranchConfigurationBasedOnNoPrIdInEnvironmentParameters() { @Test void shouldReturnPullRequestConfigurationBasedOnPrIdInEnvironmentParameters() { - System2 system2 = mock(System2.class); + System2 system2 = mock(); when(system2.envVariable("GITLAB_CI")).thenReturn("true"); when(system2.envVariable("CI_MERGE_REQUEST_SOURCE_BRANCH_NAME")).thenReturn("source"); when(system2.envVariable("CI_MERGE_REQUEST_IID")).thenReturn("id"); when(system2.envVariable("CI_MERGE_REQUEST_TARGET_BRANCH_NAME")).thenReturn("target"); - BranchConfigurationFactory branchConfigurationFactory = mock(BranchConfigurationFactory.class); - BranchConfiguration branchConfiguration = mock(BranchConfiguration.class); + BranchConfigurationFactory branchConfigurationFactory = mock(); + BranchConfiguration branchConfiguration = mock(); when(branchConfigurationFactory.createPullRequestConfiguration(any(), any(), any(), any())).thenReturn(branchConfiguration); - ProjectBranches projectBranches = mock(ProjectBranches.class); + ProjectBranches projectBranches = mock(); GitlabCiAutoConfigurer underTest = new GitlabCiAutoConfigurer(branchConfigurationFactory); assertThat(underTest.detectConfiguration(system2, projectBranches)).contains(branchConfiguration); diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/scanner/autoconfiguration/JenkinsAutoConfigurerTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/scanner/autoconfiguration/JenkinsAutoConfigurerTest.java index b30a70244..20ba0d263 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/scanner/autoconfiguration/JenkinsAutoConfigurerTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/scanner/autoconfiguration/JenkinsAutoConfigurerTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2022 Michael Clarke + * Copyright (C) 2022-2024 Michael Clarke * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -34,9 +34,9 @@ class JenkinsAutoConfigurerTest { @Test void shouldReturnOptionalEmptyIfNotJenkins() { - System2 system2 = mock(System2.class); - BranchConfigurationFactory branchConfigurationFactory = mock(BranchConfigurationFactory.class); - ProjectBranches projectBranches = mock(ProjectBranches.class); + System2 system2 = mock(); + BranchConfigurationFactory branchConfigurationFactory = mock(); + ProjectBranches projectBranches = mock(); JenkinsAutoConfigurer underTest = new JenkinsAutoConfigurer(branchConfigurationFactory); assertThat(underTest.detectConfiguration(system2, projectBranches)).isEmpty(); @@ -44,13 +44,13 @@ void shouldReturnOptionalEmptyIfNotJenkins() { @Test void shouldReturnBranchConfigurationBasedOnNoPrIdInEnvironmentParameters() { - System2 system2 = mock(System2.class); + System2 system2 = mock(); when(system2.envVariable("JENKINS_HOME")).thenReturn("/path/to/home"); when(system2.envVariable("BRANCH_NAME")).thenReturn("branch"); - BranchConfigurationFactory branchConfigurationFactory = mock(BranchConfigurationFactory.class); - BranchConfiguration branchConfiguration = mock(BranchConfiguration.class); + BranchConfigurationFactory branchConfigurationFactory = mock(); + BranchConfiguration branchConfiguration = mock(); when(branchConfigurationFactory.createBranchConfiguration(any(), any())).thenReturn(branchConfiguration); - ProjectBranches projectBranches = mock(ProjectBranches.class); + ProjectBranches projectBranches = mock(); JenkinsAutoConfigurer underTest = new JenkinsAutoConfigurer(branchConfigurationFactory); assertThat(underTest.detectConfiguration(system2, projectBranches)).contains(branchConfiguration); @@ -59,15 +59,15 @@ void shouldReturnBranchConfigurationBasedOnNoPrIdInEnvironmentParameters() { @Test void shouldReturnPullRequestConfigurationBasedOnPrIdInEnvironmentParameters() { - System2 system2 = mock(System2.class); + System2 system2 = mock(); when(system2.envVariable("JENKINS_HOME")).thenReturn("/path/to/home"); when(system2.envVariable("CHANGE_BRANCH")).thenReturn("source"); when(system2.envVariable("CHANGE_ID")).thenReturn("id"); when(system2.envVariable("CHANGE_TARGET")).thenReturn("target"); - BranchConfigurationFactory branchConfigurationFactory = mock(BranchConfigurationFactory.class); - BranchConfiguration branchConfiguration = mock(BranchConfiguration.class); + BranchConfigurationFactory branchConfigurationFactory = mock(); + BranchConfiguration branchConfiguration = mock(); when(branchConfigurationFactory.createPullRequestConfiguration(any(), any(), any(), any())).thenReturn(branchConfiguration); - ProjectBranches projectBranches = mock(ProjectBranches.class); + ProjectBranches projectBranches = mock(); JenkinsAutoConfigurer underTest = new JenkinsAutoConfigurer(branchConfigurationFactory); assertThat(underTest.detectConfiguration(system2, projectBranches)).contains(branchConfiguration); diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/server/CommunityBranchSupportDelegateTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/server/CommunityBranchSupportDelegateTest.java index e5a09a320..12769a5cc 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/server/CommunityBranchSupportDelegateTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/server/CommunityBranchSupportDelegateTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2020-2023 Michael Clarke + * Copyright (C) 2020-2024 Michael Clarke * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -56,10 +56,10 @@ */ class CommunityBranchSupportDelegateTest { - private final Clock clock = mock(Clock.class); - private final SequenceUuidFactory sequenceUuidFactory = mock(SequenceUuidFactory.class); - private final DbClient dbClient = mock(DbClient.class); - private final ProjectConfigurationLoader projectConfigurationLoader = mock(ProjectConfigurationLoader.class); + private final Clock clock = mock(); + private final SequenceUuidFactory sequenceUuidFactory = mock(); + private final DbClient dbClient = mock(); + private final ProjectConfigurationLoader projectConfigurationLoader = mock(); private final CommunityBranchSupportDelegate underTest = new CommunityBranchSupportDelegate(sequenceUuidFactory, dbClient, clock, projectConfigurationLoader); @Test @@ -103,27 +103,27 @@ void shouldThrowExceptoinOnCreateComponentKeyInvalidBranchTypeParameter() { @Test void shouldThrowExceptionIfBranchAndComponentKeysMismatch() { - DbSession dbSession = mock(DbSession.class); + DbSession dbSession = mock(); - ComponentDto componentDto = mock(ComponentDto.class); + ComponentDto componentDto = mock(); when(componentDto.getKey()).thenReturn("otherComponentKey"); when(componentDto.uuid()).thenReturn("componentUuid"); ComponentDto copyComponentDto = spy(ComponentDto.class); when(componentDto.copy()).thenReturn(copyComponentDto); - BranchDto branchDto = mock(BranchDto.class); + BranchDto branchDto = mock(); when(branchDto.getUuid()).thenReturn("componentUuid"); when(branchDto.getBranchType()).thenReturn(BranchType.BRANCH); when(clock.millis()).thenReturn(12345678901234L); - BranchSupport.ComponentKey componentKey = mock(BranchSupport.ComponentKey.class); + BranchSupport.ComponentKey componentKey = mock(); when(componentKey.getKey()).thenReturn("componentKey"); when(componentKey.getBranchName()).thenReturn(Optional.of("dummy")); when(componentKey.getPullRequestKey()).thenReturn(Optional.empty()); - ComponentDao componentDao = mock(ComponentDao.class); + ComponentDao componentDao = mock(); when(dbClient.componentDao()).thenReturn(componentDao); @@ -144,13 +144,13 @@ static Stream shouldCreateComponentAndBranchDtoIfValidationPassesData @ParameterizedTest void shouldCreateComponentAndBranchDtoIfValidationPasses(String branchName, String pullRequestKey, BranchType branchType, String[] retainBranchesConfiguration, boolean excludedFromPurge) { - DbSession dbSession = mock(DbSession.class); + DbSession dbSession = mock(); - ComponentDto componentDto = mock(ComponentDto.class); + ComponentDto componentDto = mock(); when(componentDto.getKey()).thenReturn("componentKey"); when(componentDto.uuid()).thenReturn("componentUuid"); - ComponentDto copyComponentDto = mock(ComponentDto.class); + ComponentDto copyComponentDto = mock(); when(componentDto.copy()).thenReturn(copyComponentDto); when(copyComponentDto.setBranchUuid(any())).thenReturn(copyComponentDto); when(copyComponentDto.setKey(any())).thenReturn(copyComponentDto); @@ -158,25 +158,25 @@ void shouldCreateComponentAndBranchDtoIfValidationPasses(String branchName, Stri when(copyComponentDto.setUuid(any())).thenReturn(copyComponentDto); when(copyComponentDto.setCreatedAt(any())).thenReturn(copyComponentDto); - BranchDto branchDto = mock(BranchDto.class); + BranchDto branchDto = mock(); when(branchDto.getProjectUuid()).thenReturn("projectUuid"); when(branchDto.getKey()).thenReturn("nonDummy"); when(clock.millis()).thenReturn(12345678901234L); - BranchSupport.ComponentKey componentKey = mock(BranchSupport.ComponentKey.class); + BranchSupport.ComponentKey componentKey = mock(); when(componentKey.getKey()).thenReturn("componentKey"); when(componentKey.getBranchName()).thenReturn(Optional.ofNullable(branchName)); when(componentKey.getPullRequestKey()).thenReturn(Optional.ofNullable(pullRequestKey)); - BranchDao branchDao = mock(BranchDao.class); - ComponentDao componentDao = mock(ComponentDao.class); + BranchDao branchDao = mock(); + ComponentDao componentDao = mock(); when(dbClient.componentDao()).thenReturn(componentDao); when(dbClient.branchDao()).thenReturn(branchDao); when(sequenceUuidFactory.create()).thenReturn("uuid0"); - Configuration configuration = mock(Configuration.class); + Configuration configuration = mock(); when(configuration.getStringArray(any())).thenReturn(retainBranchesConfiguration); when(projectConfigurationLoader.loadProjectConfiguration(any(), any())).thenReturn(configuration); @@ -189,7 +189,7 @@ void shouldCreateComponentAndBranchDtoIfValidationPasses(String branchName, Stri assertThat(result).isSameAs(copyComponentDto); - ArgumentCaptor branchDtoArgumentCaptor = ArgumentCaptor.forClass(BranchDto.class); + ArgumentCaptor branchDtoArgumentCaptor = ArgumentCaptor.captor(); verify(branchDao).insert(eq(dbSession), branchDtoArgumentCaptor.capture()); assertThat(branchDtoArgumentCaptor.getValue()).usingRecursiveComparison().isEqualTo(new BranchDto() diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/validator/AzureDevopsValidatorTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/validator/AzureDevopsValidatorTest.java index df533d262..c9ab87fc5 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/validator/AzureDevopsValidatorTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/validator/AzureDevopsValidatorTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Michael Clarke + * Copyright (C) 2021-2024 Michael Clarke * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -21,7 +21,6 @@ import com.github.mc1arke.sonarqube.plugin.InvalidConfigurationException; import com.github.mc1arke.sonarqube.plugin.almclient.azuredevops.AzureDevopsClient; import com.github.mc1arke.sonarqube.plugin.almclient.azuredevops.AzureDevopsClientFactory; -import com.github.mc1arke.sonarqube.plugin.almclient.azuredevops.model.Repository; import org.assertj.core.api.Condition; import org.junit.jupiter.api.Test; import org.sonar.db.alm.setting.ALM; @@ -39,9 +38,9 @@ class AzureDevopsValidatorTest { - private final AzureDevopsClientFactory azureDevopsClientFactory = mock(AzureDevopsClientFactory.class); - private final ProjectAlmSettingDto projectAlmSettingDto = mock(ProjectAlmSettingDto.class); - private final AlmSettingDto almSettingDto = mock(AlmSettingDto.class); + private final AzureDevopsClientFactory azureDevopsClientFactory = mock(); + private final ProjectAlmSettingDto projectAlmSettingDto = mock(); + private final AlmSettingDto almSettingDto = mock(); @Test void testCorrectAlmReturnedForValidator() { @@ -64,7 +63,7 @@ void testInvalidConfigurationExceptionThrownIfRetrieveProjectFails() throws IOEx AzureDevopsValidator underTest = new AzureDevopsValidator(azureDevopsClientFactory); when(projectAlmSettingDto.getAlmSlug()).thenReturn("slug"); when(projectAlmSettingDto.getAlmRepo()).thenReturn("repo"); - AzureDevopsClient azureDevopsClient = mock(AzureDevopsClient.class); + AzureDevopsClient azureDevopsClient = mock(); when(azureDevopsClient.getRepository(any(), any())).thenThrow(new IllegalStateException("dummy")); when(azureDevopsClientFactory.createClient(any(), any())).thenReturn(azureDevopsClient); assertThatThrownBy(() -> underTest.validate(projectAlmSettingDto, almSettingDto)) @@ -86,8 +85,8 @@ void testInvalidConfigurationExceptionRethrownIfCreateClientThrowsInvalidConfigu @Test void testExceptionOnMissingSlug() throws IOException { AzureDevopsValidator underTest = new AzureDevopsValidator(azureDevopsClientFactory); - AzureDevopsClient azureDevopsClient = mock(AzureDevopsClient.class); - when(azureDevopsClient.getRepository(any(), any())).thenReturn(mock(Repository.class)); + AzureDevopsClient azureDevopsClient = mock(); + when(azureDevopsClient.getRepository(any(), any())).thenReturn(mock()); when(azureDevopsClientFactory.createClient(any(), any())).thenReturn(azureDevopsClient); assertThatThrownBy(() -> underTest.validate(projectAlmSettingDto, almSettingDto)) @@ -99,8 +98,8 @@ void testExceptionOnMissingSlug() throws IOException { @Test void testExceptionOnMissingRepo() throws IOException { AzureDevopsValidator underTest = new AzureDevopsValidator(azureDevopsClientFactory); - AzureDevopsClient azureDevopsClient = mock(AzureDevopsClient.class); - when(azureDevopsClient.getRepository(any(), any())).thenReturn(mock(Repository.class)); + AzureDevopsClient azureDevopsClient = mock(); + when(azureDevopsClient.getRepository(any(), any())).thenReturn(mock()); when(azureDevopsClientFactory.createClient(any(), any())).thenReturn(azureDevopsClient); when(projectAlmSettingDto.getAlmSlug()).thenReturn("slug"); @@ -114,8 +113,8 @@ void testExceptionOnMissingRepo() throws IOException { @Test void testHappyPath() throws IOException { AzureDevopsValidator underTest = new AzureDevopsValidator(azureDevopsClientFactory); - AzureDevopsClient azureDevopsClient = mock(AzureDevopsClient.class); - when(azureDevopsClient.getRepository(any(), any())).thenReturn(mock(Repository.class)); + AzureDevopsClient azureDevopsClient = mock(); + when(azureDevopsClient.getRepository(any(), any())).thenReturn(mock()); when(azureDevopsClientFactory.createClient(any(), any())).thenReturn(azureDevopsClient); when(projectAlmSettingDto.getAlmSlug()).thenReturn("slug"); when(projectAlmSettingDto.getAlmRepo()).thenReturn("repo"); diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/validator/BitbucketValidatorTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/validator/BitbucketValidatorTest.java index 9acba694c..69c8b8af3 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/validator/BitbucketValidatorTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/validator/BitbucketValidatorTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021-2022 Michael Clarke + * Copyright (C) 2021-2024 Michael Clarke * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -38,9 +38,9 @@ class BitbucketValidatorTest { - private final BitbucketClientFactory bitbucketClientFactory = mock(BitbucketClientFactory.class); - private final ProjectAlmSettingDto projectAlmSettingDto = mock(ProjectAlmSettingDto.class); - private final AlmSettingDto almSettingDto = mock(AlmSettingDto.class); + private final BitbucketClientFactory bitbucketClientFactory = mock(); + private final ProjectAlmSettingDto projectAlmSettingDto = mock(); + private final AlmSettingDto almSettingDto = mock(); @Test void testCorrectAlmReturnedForValidator() { @@ -71,7 +71,7 @@ void testInvalidConfigurationExceptionRethrownIfCreateClientThrows() { @Test void testInvalidConfigurationExceptionThrownIfRetrieveRepositoryFails() throws IOException { BitbucketValidator underTest = new BitbucketValidator(bitbucketClientFactory); - BitbucketClient bitbucketClient = mock(BitbucketClient.class); + BitbucketClient bitbucketClient = mock(); when(bitbucketClient.retrieveRepository()).thenThrow(new IOException("dummy")); when(bitbucketClientFactory.createClient(any(), any())).thenReturn(bitbucketClient); assertThatThrownBy(() -> underTest.validate(projectAlmSettingDto, almSettingDto)) @@ -83,7 +83,7 @@ void testInvalidConfigurationExceptionThrownIfRetrieveRepositoryFails() throws I @Test void testInvalidConfigurationExceptionThrownIfCodeInsightsCheckFails() { BitbucketValidator underTest = new BitbucketValidator(bitbucketClientFactory); - BitbucketClient bitbucketClient = mock(BitbucketClient.class); + BitbucketClient bitbucketClient = mock(); when(bitbucketClient.supportsCodeInsights()).thenThrow(new IllegalStateException("dummy")); when(bitbucketClientFactory.createClient(any(), any())).thenReturn(bitbucketClient); assertThatThrownBy(() -> underTest.validate(projectAlmSettingDto, almSettingDto)) @@ -95,7 +95,7 @@ void testInvalidConfigurationExceptionThrownIfCodeInsightsCheckFails() { @Test void testInvalidConfigurationExceptionThrownIfCodeInsightsIsFalse() { BitbucketValidator underTest = new BitbucketValidator(bitbucketClientFactory); - BitbucketClient bitbucketClient = mock(BitbucketClient.class); + BitbucketClient bitbucketClient = mock(); when(bitbucketClient.supportsCodeInsights()).thenReturn(false); when(bitbucketClientFactory.createClient(any(), any())).thenReturn(bitbucketClient); assertThatThrownBy(() -> underTest.validate(projectAlmSettingDto, almSettingDto)) @@ -107,7 +107,7 @@ void testInvalidConfigurationExceptionThrownIfCodeInsightsIsFalse() { @Test void testHappyPath() { BitbucketValidator underTest = new BitbucketValidator(bitbucketClientFactory); - BitbucketClient bitbucketClient = mock(BitbucketClient.class); + BitbucketClient bitbucketClient = mock(); when(bitbucketClient.supportsCodeInsights()).thenReturn(true); when(bitbucketClientFactory.createClient(any(), any())).thenReturn(bitbucketClient); diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/validator/GitlabValidatorTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/validator/GitlabValidatorTest.java index 87f203e0d..34f3251a8 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/validator/GitlabValidatorTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/validator/GitlabValidatorTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Michael Clarke + * Copyright (C) 2021-2024 Michael Clarke * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -21,7 +21,6 @@ import com.github.mc1arke.sonarqube.plugin.InvalidConfigurationException; import com.github.mc1arke.sonarqube.plugin.almclient.gitlab.GitlabClient; import com.github.mc1arke.sonarqube.plugin.almclient.gitlab.GitlabClientFactory; -import com.github.mc1arke.sonarqube.plugin.almclient.gitlab.model.Project; import org.assertj.core.api.Condition; import org.junit.jupiter.api.Test; import org.sonar.db.alm.setting.ALM; @@ -39,9 +38,9 @@ class GitlabValidatorTest { - private final GitlabClientFactory gitlabClientFactory = mock(GitlabClientFactory.class); - private final ProjectAlmSettingDto projectAlmSettingDto = mock(ProjectAlmSettingDto.class); - private final AlmSettingDto almSettingDto = mock(AlmSettingDto.class); + private final GitlabClientFactory gitlabClientFactory = mock(); + private final ProjectAlmSettingDto projectAlmSettingDto = mock(); + private final AlmSettingDto almSettingDto = mock(); @Test void testCorrectAlmReturnedForValidator() { @@ -62,7 +61,7 @@ void testInvalidConfigurationExceptionThrownIfCreateClientFails() { @Test void testInvalidConfigurationExceptionThrownIfRetrieveProjectFails() throws IOException { GitlabValidator underTest = new GitlabValidator(gitlabClientFactory); - GitlabClient gitlabClient = mock(GitlabClient.class); + GitlabClient gitlabClient = mock(); when(gitlabClient.getProject(any())).thenThrow(new IllegalStateException("dummy")); when(gitlabClientFactory.createClient(any(), any())).thenReturn(gitlabClient); assertThatThrownBy(() -> underTest.validate(projectAlmSettingDto, almSettingDto)) @@ -84,8 +83,8 @@ void testInvalidConfigurationExceptionRethrownIfCreateClientThrowsInvalidConfigu @Test void testHappyPath() throws IOException { GitlabValidator underTest = new GitlabValidator(gitlabClientFactory); - GitlabClient gitlabClient = mock(GitlabClient.class); - when(gitlabClient.getProject(any())).thenReturn(mock(Project.class)); + GitlabClient gitlabClient = mock(); + when(gitlabClient.getProject(any())).thenReturn(mock()); when(gitlabClientFactory.createClient(any(), any())).thenReturn(gitlabClient); underTest.validate(projectAlmSettingDto, almSettingDto); diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/ws/AlmTypeMapperTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/ws/AlmTypeMapperTest.java deleted file mode 100644 index fb1d325c4..000000000 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/ws/AlmTypeMapperTest.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.github.mc1arke.sonarqube.plugin.server.pullrequest.ws; - - -import static org.assertj.core.api.Assertions.assertThat; - -import org.junit.Test; -import org.sonar.db.alm.setting.ALM; -import org.sonarqube.ws.AlmSettings; - -public class AlmTypeMapperTest { - - @Test - public void testToAlmWs() { - assertThat(AlmTypeMapper.toAlmWs(ALM.AZURE_DEVOPS)).isEqualTo(AlmSettings.Alm.azure); - assertThat(AlmTypeMapper.toAlmWs(ALM.GITLAB)).isEqualTo(AlmSettings.Alm.gitlab); - assertThat(AlmTypeMapper.toAlmWs(ALM.GITHUB)).isEqualTo(AlmSettings.Alm.github); - assertThat(AlmTypeMapper.toAlmWs(ALM.BITBUCKET)).isEqualTo(AlmSettings.Alm.bitbucket); - } -} \ No newline at end of file diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/ws/binding/action/DeleteBindingActionTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/ws/binding/action/DeleteBindingActionTest.java index 566af4f07..ee2e708b9 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/ws/binding/action/DeleteBindingActionTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/ws/binding/action/DeleteBindingActionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2020-2023 Michael Clarke + * Copyright (C) 2020-2024 Michael Clarke * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -38,17 +38,17 @@ class DeleteBindingActionTest { @Test void shouldDefineEndpointWithParameters() { - DbClient dbClient = mock(DbClient.class); - UserSession userSession = mock(UserSession.class); - ComponentFinder componentFinder = mock(ComponentFinder.class); + DbClient dbClient = mock(); + UserSession userSession = mock(); + ComponentFinder componentFinder = mock(); DeleteBindingAction testCase = new DeleteBindingAction(dbClient, userSession, componentFinder); - WebService.NewParam keyParam = mock(WebService.NewParam.class); + WebService.NewParam keyParam = mock(); when(keyParam.setMaximumLength(200)).thenReturn(keyParam); - WebService.NewParam newKeyParam = mock(WebService.NewParam.class); + WebService.NewParam newKeyParam = mock(); when(newKeyParam.setMaximumLength(200)).thenReturn(newKeyParam); - WebService.NewController newController = mock(WebService.NewController.class); - WebService.NewAction newAction = mock(WebService.NewAction.class); + WebService.NewController newController = mock(); + WebService.NewAction newAction = mock(); when(newController.createAction("delete_binding")).thenReturn(newAction); when(newAction.setPost(true)).thenReturn(newAction); when(newAction.setHandler(testCase)).thenReturn(newAction); @@ -63,19 +63,19 @@ void shouldDefineEndpointWithParameters() { @Test void shouldHandleEndpointWithValidRequest() { - DbClient dbClient = mock(DbClient.class); - DbSession dbSession = mock(DbSession.class); + DbClient dbClient = mock(); + DbSession dbSession = mock(); when(dbClient.openSession(false)).thenReturn(dbSession); - AlmSettingDao almSettingDao = mock(AlmSettingDao.class); + AlmSettingDao almSettingDao = mock(); when(dbClient.almSettingDao()).thenReturn(almSettingDao); - ProjectAlmSettingDao projectAlmSettingDao = mock(ProjectAlmSettingDao.class); + ProjectAlmSettingDao projectAlmSettingDao = mock(); when(dbClient.projectAlmSettingDao()).thenReturn(projectAlmSettingDao); - UserSession userSession = mock(UserSession.class); + UserSession userSession = mock(); - ProjectDto componentDto = mock(ProjectDto.class); - ComponentFinder componentFinder = mock(ComponentFinder.class); + ProjectDto componentDto = mock(); + ComponentFinder componentFinder = mock(); when(componentFinder.getProjectByKey(dbSession, "projectKey")).thenReturn(componentDto); DeleteBindingAction testCase = new DeleteBindingAction(dbClient, userSession, componentFinder); diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/ws/binding/action/SetAzureBindingActionTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/ws/binding/action/SetAzureBindingActionTest.java index 77cc1a584..4e86c93ad 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/ws/binding/action/SetAzureBindingActionTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/ws/binding/action/SetAzureBindingActionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2020-2022 Michael Clarke + * Copyright (C) 2020-2024 Michael Clarke * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -37,29 +37,29 @@ class SetAzureBindingActionTest { @Test void shouldDefineActionWithRequiredParameters() { - DbClient dbClient = mock(DbClient.class); - UserSession userSession = mock(UserSession.class); - ComponentFinder componentFinder = mock(ComponentFinder.class); + DbClient dbClient = mock(); + UserSession userSession = mock(); + ComponentFinder componentFinder = mock(); - WebService.NewAction newAction = mock(WebService.NewAction.class); + WebService.NewAction newAction = mock(); when(newAction.setPost(anyBoolean())).thenReturn(newAction); - WebService.NewParam repositoryNameParameter = mock(WebService.NewParam.class); + WebService.NewParam repositoryNameParameter = mock(); when(repositoryNameParameter.setMaximumLength(any(Integer.class))).thenReturn(repositoryNameParameter); when(repositoryNameParameter.setRequired(anyBoolean())).thenReturn(repositoryNameParameter); when(newAction.createParam("repositoryName")).thenReturn(repositoryNameParameter); - WebService.NewParam projectNameParameter = mock(WebService.NewParam.class); + WebService.NewParam projectNameParameter = mock(); when(projectNameParameter.setMaximumLength(any(Integer.class))).thenReturn(projectNameParameter); when(projectNameParameter.setRequired(anyBoolean())).thenReturn(projectNameParameter); when(newAction.createParam("projectName")).thenReturn(projectNameParameter); - WebService.NewParam almSettingParameter = mock(WebService.NewParam.class); + WebService.NewParam almSettingParameter = mock(); when(almSettingParameter.setMaximumLength(any(Integer.class))).thenReturn(almSettingParameter); when(almSettingParameter.setRequired(anyBoolean())).thenReturn(almSettingParameter); when(newAction.createParam("almSetting")).thenReturn(almSettingParameter); - WebService.NewParam monoRepoParameter = mock(WebService.NewParam.class); + WebService.NewParam monoRepoParameter = mock(); when(monoRepoParameter.setRequired(anyBoolean())).thenReturn(monoRepoParameter); when(newAction.createParam("monorepo")).thenReturn(monoRepoParameter); @@ -76,11 +76,11 @@ void shouldDefineActionWithRequiredParameters() { @Test void shouldHandleRequestWithValidParameters() { - DbClient dbClient = mock(DbClient.class); - UserSession userSession = mock(UserSession.class); - ComponentFinder componentFinder = mock(ComponentFinder.class); + DbClient dbClient = mock(); + UserSession userSession = mock(); + ComponentFinder componentFinder = mock(); - Request request = mock(Request.class); + Request request = mock(); when(request.mandatoryParam("repositoryName")).thenReturn("repository"); when(request.mandatoryParam("projectName")).thenReturn("project"); diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/ws/binding/action/SetBindingActionTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/ws/binding/action/SetBindingActionTest.java index 7fd27366b..c5c5cdf4d 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/ws/binding/action/SetBindingActionTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/ws/binding/action/SetBindingActionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2020-2022 Michael Clarke + * Copyright (C) 2020-2024 Michael Clarke * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -47,10 +47,10 @@ class SetBindingActionTest { @Test void shouldDefineActionWithRequiredParameters() { - DbClient dbClient = mock(DbClient.class); - ComponentFinder componentFinder = mock(ComponentFinder.class); - UserSession userSession = mock(UserSession.class); - ProjectAlmSettingDto projectAlmSettingDto = mock(ProjectAlmSettingDto.class); + DbClient dbClient = mock(); + ComponentFinder componentFinder = mock(); + UserSession userSession = mock(); + ProjectAlmSettingDto projectAlmSettingDto = mock(); SetBindingAction testCase = new SetBindingAction(dbClient, componentFinder, userSession, "dummy") { @Override @@ -61,13 +61,13 @@ protected ProjectAlmSettingDto createProjectAlmSettingDto(String projectUuid, St Map paramMap = new HashMap<>(); - WebService.NewController newController = mock(WebService.NewController.class); - WebService.NewAction newAction = mock(WebService.NewAction.class); + WebService.NewController newController = mock(); + WebService.NewAction newAction = mock(); when(newController.createAction(any())).thenReturn(newAction); when(newAction.setPost(true)).thenReturn(newAction); when(newAction.setHandler(testCase)).thenReturn(newAction); when(newAction.createParam(any())).then(i -> { - WebService.NewParam newParam = mock(WebService.NewParam.class); + WebService.NewParam newParam = mock(); paramMap.put(i.getArgument(0), newParam); when(newParam.setRequired(anyBoolean())).thenReturn(newParam); return newParam; @@ -84,23 +84,23 @@ protected ProjectAlmSettingDto createProjectAlmSettingDto(String projectUuid, St @Test void shouldHandleRequestWithRequiredParameters() { - DbClient dbClient = mock(DbClient.class); - DbSession dbSession = mock(DbSession.class); + DbClient dbClient = mock(); + DbSession dbSession = mock(); when(dbClient.openSession(false)).thenReturn(dbSession); - AlmSettingDao almSettingDao = mock(AlmSettingDao.class); - AlmSettingDto almSettingDto = mock(AlmSettingDto.class); + AlmSettingDao almSettingDao = mock(); + AlmSettingDto almSettingDto = mock(); when(almSettingDto.getUuid()).thenReturn("almSettingsUuid"); when(almSettingDao.selectByKey(dbSession, "almSetting")).thenReturn(Optional.of(almSettingDto)); when(dbClient.almSettingDao()).thenReturn(almSettingDao); - ProjectAlmSettingDao projectAlmSettingDao = mock(ProjectAlmSettingDao.class); + ProjectAlmSettingDao projectAlmSettingDao = mock(); when(dbClient.projectAlmSettingDao()).thenReturn(projectAlmSettingDao); - ComponentFinder componentFinder = mock(ComponentFinder.class); - ProjectDto componentDto = mock(ProjectDto.class); + ComponentFinder componentFinder = mock(); + ProjectDto componentDto = mock(); when(componentDto.getUuid()).thenReturn("projectUuid"); when(componentFinder.getProjectByKey(dbSession, "project")).thenReturn(componentDto); - UserSession userSession = mock(UserSession.class); + UserSession userSession = mock(); ThreadLocal capturedAction = new ThreadLocal<>(); - ProjectAlmSettingDto projectAlmSettingDto = mock(ProjectAlmSettingDto.class); + ProjectAlmSettingDto projectAlmSettingDto = mock(); SetBindingAction testCase = new SetBindingAction(dbClient, componentFinder, userSession, "dummy") { @Override @@ -116,8 +116,8 @@ protected ProjectAlmSettingDto createProjectAlmSettingDto(String projectUuid, St } }; - Request request = mock(Request.class); - Response response = mock(Response.class); + Request request = mock(); + Response response = mock(); when(request.mandatoryParam("almSetting")).thenReturn("almSetting"); when(request.mandatoryParam("project")).thenReturn("project"); diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/ws/binding/action/SetBitBucketBindingActionTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/ws/binding/action/SetBitBucketBindingActionTest.java index 53a5f71b6..feff3e3ec 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/ws/binding/action/SetBitBucketBindingActionTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/ws/binding/action/SetBitBucketBindingActionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2020-2022 Michael Clarke + * Copyright (C) 2020-2024 Michael Clarke * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -37,29 +37,29 @@ class SetBitBucketBindingActionTest { @Test void shouldDefineActionWithRequiredParameters() { - DbClient dbClient = mock(DbClient.class); - UserSession userSession = mock(UserSession.class); - ComponentFinder componentFinder = mock(ComponentFinder.class); + DbClient dbClient = mock(); + UserSession userSession = mock(); + ComponentFinder componentFinder = mock(); - WebService.NewAction newAction = mock(WebService.NewAction.class); + WebService.NewAction newAction = mock(); when(newAction.setPost(anyBoolean())).thenReturn(newAction); - WebService.NewParam slugParameter = mock(WebService.NewParam.class); + WebService.NewParam slugParameter = mock(); when(slugParameter.setMaximumLength(any(Integer.class))).thenReturn(slugParameter); when(slugParameter.setRequired(anyBoolean())).thenReturn(slugParameter); when(newAction.createParam("slug")).thenReturn(slugParameter); - WebService.NewParam repositoryParameter = mock(WebService.NewParam.class); + WebService.NewParam repositoryParameter = mock(); when(repositoryParameter.setMaximumLength(any(Integer.class))).thenReturn(repositoryParameter); when(repositoryParameter.setRequired(anyBoolean())).thenReturn(repositoryParameter); when(newAction.createParam("repository")).thenReturn(repositoryParameter); - WebService.NewParam almSettingParameter = mock(WebService.NewParam.class); + WebService.NewParam almSettingParameter = mock(); when(almSettingParameter.setMaximumLength(any(Integer.class))).thenReturn(almSettingParameter); when(almSettingParameter.setRequired(anyBoolean())).thenReturn(almSettingParameter); when(newAction.createParam("almSetting")).thenReturn(almSettingParameter); - WebService.NewParam monoRepoParameter = mock(WebService.NewParam.class); + WebService.NewParam monoRepoParameter = mock(); when(monoRepoParameter.setRequired(anyBoolean())).thenReturn(monoRepoParameter); when(newAction.createParam("monorepo")).thenReturn(monoRepoParameter); @@ -79,11 +79,11 @@ void shouldDefineActionWithRequiredParameters() { @Test void shouldHandleRequestWithRequiredParameters() { - DbClient dbClient = mock(DbClient.class); - UserSession userSession = mock(UserSession.class); - ComponentFinder componentFinder = mock(ComponentFinder.class); + DbClient dbClient = mock(); + UserSession userSession = mock(); + ComponentFinder componentFinder = mock(); - Request request = mock(Request.class); + Request request = mock(); when(request.mandatoryParam("slug")).thenReturn("slug"); when(request.mandatoryParam("repository")).thenReturn("repository"); diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/ws/binding/action/SetBitBucketCloudBindingActionTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/ws/binding/action/SetBitBucketCloudBindingActionTest.java index 281ed27af..a2be1145c 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/ws/binding/action/SetBitBucketCloudBindingActionTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/ws/binding/action/SetBitBucketCloudBindingActionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021-2022 Michael Clarke + * Copyright (C) 2021-2024 Michael Clarke * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -37,24 +37,24 @@ class SetBitBucketCloudBindingActionTest { @Test void shouldDefineActionWithValidParameters() { - DbClient dbClient = mock(DbClient.class); - UserSession userSession = mock(UserSession.class); - ComponentFinder componentFinder = mock(ComponentFinder.class); + DbClient dbClient = mock(); + UserSession userSession = mock(); + ComponentFinder componentFinder = mock(); - WebService.NewAction newAction = mock(WebService.NewAction.class); + WebService.NewAction newAction = mock(); when(newAction.setPost(anyBoolean())).thenReturn(newAction); - WebService.NewParam repositoryParameter = mock(WebService.NewParam.class); + WebService.NewParam repositoryParameter = mock(); when(repositoryParameter.setMaximumLength(any(Integer.class))).thenReturn(repositoryParameter); when(repositoryParameter.setRequired(anyBoolean())).thenReturn(repositoryParameter); when(newAction.createParam("repository")).thenReturn(repositoryParameter); - WebService.NewParam almSettingParameter = mock(WebService.NewParam.class); + WebService.NewParam almSettingParameter = mock(); when(almSettingParameter.setMaximumLength(any(Integer.class))).thenReturn(almSettingParameter); when(almSettingParameter.setRequired(anyBoolean())).thenReturn(almSettingParameter); when(newAction.createParam("almSetting")).thenReturn(almSettingParameter); - WebService.NewParam monoRepoParameter = mock(WebService.NewParam.class); + WebService.NewParam monoRepoParameter = mock(); when(monoRepoParameter.setRequired(anyBoolean())).thenReturn(monoRepoParameter); when(newAction.createParam("monorepo")).thenReturn(monoRepoParameter); @@ -72,11 +72,11 @@ void shouldDefineActionWithValidParameters() { @Test void shouldHandleRequestWithValidParameters() { - DbClient dbClient = mock(DbClient.class); - UserSession userSession = mock(UserSession.class); - ComponentFinder componentFinder = mock(ComponentFinder.class); + DbClient dbClient = mock(); + UserSession userSession = mock(); + ComponentFinder componentFinder = mock(); - Request request = mock(Request.class); + Request request = mock(); when(request.mandatoryParam("repository")).thenReturn("repository"); SetBitbucketCloudBindingAction testCase = new SetBitbucketCloudBindingAction(dbClient, componentFinder, userSession); diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/ws/binding/action/SetGithubBindingActionTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/ws/binding/action/SetGithubBindingActionTest.java index 406b3055e..6fe80fefd 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/ws/binding/action/SetGithubBindingActionTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/ws/binding/action/SetGithubBindingActionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2020-2022 Michael Clarke + * Copyright (C) 2020-2024 Michael Clarke * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -37,29 +37,29 @@ class SetGithubBindingActionTest { @Test void shouldDefineActionWithRequiredParameters() { - DbClient dbClient = mock(DbClient.class); - UserSession userSession = mock(UserSession.class); - ComponentFinder componentFinder = mock(ComponentFinder.class); + DbClient dbClient = mock(); + UserSession userSession = mock(); + ComponentFinder componentFinder = mock(); - WebService.NewAction newAction = mock(WebService.NewAction.class); + WebService.NewAction newAction = mock(); when(newAction.setPost(anyBoolean())).thenReturn(newAction); - WebService.NewParam repositoryParameter = mock(WebService.NewParam.class); + WebService.NewParam repositoryParameter = mock(); when(repositoryParameter.setMaximumLength(any(Integer.class))).thenReturn(repositoryParameter); when(repositoryParameter.setRequired(anyBoolean())).thenReturn(repositoryParameter); when(newAction.createParam("repository")).thenReturn(repositoryParameter); - WebService.NewParam commentEnabledParameter = mock(WebService.NewParam.class); + WebService.NewParam commentEnabledParameter = mock(); when(commentEnabledParameter.setBooleanPossibleValues()).thenReturn(commentEnabledParameter); when(commentEnabledParameter.setRequired(anyBoolean())).thenReturn(commentEnabledParameter); when(newAction.createParam("summaryCommentEnabled")).thenReturn(commentEnabledParameter); - WebService.NewParam almSettingParameter = mock(WebService.NewParam.class); + WebService.NewParam almSettingParameter = mock(); when(almSettingParameter.setMaximumLength(any(Integer.class))).thenReturn(almSettingParameter); when(almSettingParameter.setRequired(anyBoolean())).thenReturn(almSettingParameter); when(newAction.createParam("almSetting")).thenReturn(almSettingParameter); - WebService.NewParam monoRepoParameter = mock(WebService.NewParam.class); + WebService.NewParam monoRepoParameter = mock(); when(monoRepoParameter.setRequired(anyBoolean())).thenReturn(monoRepoParameter); when(newAction.createParam("monorepo")).thenReturn(monoRepoParameter); @@ -75,11 +75,11 @@ void shouldDefineActionWithRequiredParameters() { @Test void shouldHandleRequestWithRequiredParmaeters() { - DbClient dbClient = mock(DbClient.class); - UserSession userSession = mock(UserSession.class); - ComponentFinder componentFinder = mock(ComponentFinder.class); + DbClient dbClient = mock(); + UserSession userSession = mock(); + ComponentFinder componentFinder = mock(); - Request request = mock(Request.class); + Request request = mock(); when(request.mandatoryParam("repository")).thenReturn("repository"); when(request.paramAsBoolean("summaryCommentEnabled")).thenReturn(true); diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/ws/binding/action/SetGitlabBindingActionTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/ws/binding/action/SetGitlabBindingActionTest.java index f6598d6ef..a3fe106a1 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/ws/binding/action/SetGitlabBindingActionTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/ws/binding/action/SetGitlabBindingActionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2020-2022 Michael Clarke + * Copyright (C) 2020-2024 Michael Clarke * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -37,21 +37,21 @@ class SetGitlabBindingActionTest { @Test void shouldDefineActionWithRequiredParameters() { - DbClient dbClient = mock(DbClient.class); - UserSession userSession = mock(UserSession.class); - ComponentFinder componentFinder = mock(ComponentFinder.class); + DbClient dbClient = mock(); + UserSession userSession = mock(); + ComponentFinder componentFinder = mock(); - WebService.NewAction newAction = mock(WebService.NewAction.class); + WebService.NewAction newAction = mock(); when(newAction.setPost(anyBoolean())).thenReturn(newAction); - WebService.NewParam repositoryParameter = mock(WebService.NewParam.class); + WebService.NewParam repositoryParameter = mock(); when(newAction.createParam("repository")).thenReturn(repositoryParameter); - WebService.NewParam almSettingParameter = mock(WebService.NewParam.class); + WebService.NewParam almSettingParameter = mock(); when(almSettingParameter.setRequired(anyBoolean())).thenReturn(almSettingParameter); when(newAction.createParam("almSetting")).thenReturn(almSettingParameter); - WebService.NewParam monoRepoParameter = mock(WebService.NewParam.class); + WebService.NewParam monoRepoParameter = mock(); when(monoRepoParameter.setRequired(anyBoolean())).thenReturn(monoRepoParameter); when(newAction.createParam("monorepo")).thenReturn(monoRepoParameter); @@ -68,11 +68,11 @@ void shouldDefineActionWithRequiredParameters() { @Test void shouldHandleRequestWithValidParameters() { - DbClient dbClient = mock(DbClient.class); - UserSession userSession = mock(UserSession.class); - ComponentFinder componentFinder = mock(ComponentFinder.class); + DbClient dbClient = mock(); + UserSession userSession = mock(); + ComponentFinder componentFinder = mock(); - Request request = mock(Request.class); + Request request = mock(); when(request.param("repository")).thenReturn("repositoryId"); SetGitlabBindingAction testCase = new SetGitlabBindingAction(dbClient, componentFinder, userSession); diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/ws/binding/action/ValidateBindingActionTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/ws/binding/action/ValidateBindingActionTest.java index ca19f8f37..eaa1fb190 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/ws/binding/action/ValidateBindingActionTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/ws/binding/action/ValidateBindingActionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021-2023 Michael Clarke + * Copyright (C) 2021-2024 Michael Clarke * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -53,14 +53,14 @@ class ValidateBindingActionTest { - private final DbClient dbClient = mock(DbClient.class); - private final ComponentFinder componentFinder = mock(ComponentFinder.class); - private final UserSession userSession = mock(UserSession.class); + private final DbClient dbClient = mock(); + private final ComponentFinder componentFinder = mock(); + private final UserSession userSession = mock(); @Test void testConfigureActionNoOperation() { ValidateBindingAction underTest = new ValidateBindingAction(dbClient, componentFinder, userSession, Collections.emptyList()); - WebService.NewAction newAction = mock(WebService.NewAction.class); + WebService.NewAction newAction = mock(); underTest.configureAction(newAction); verifyNoInteractions(newAction); } @@ -69,12 +69,12 @@ void testConfigureActionNoOperation() { void testHandleProjectRequestSuccessWithNoFurtherOperationsWhenNoAlmConfigurationExistsForProject() { ValidateBindingAction underTest = new ValidateBindingAction(dbClient, componentFinder, userSession, Collections.emptyList()); - ProjectDto projectDto = mock(ProjectDto.class); - Request request = mock(Request.class); - Response response = mock(Response.class); - DbSession dbSession = mock(DbSession.class); + ProjectDto projectDto = mock(); + Request request = mock(); + Response response = mock(); + DbSession dbSession = mock(); - ProjectAlmSettingDao projectAlmSettingDao = mock(ProjectAlmSettingDao.class); + ProjectAlmSettingDao projectAlmSettingDao = mock(); when(projectAlmSettingDao.selectByProject(dbSession, projectDto)).thenReturn(Optional.empty()); when(dbClient.projectAlmSettingDao()).thenReturn(projectAlmSettingDao); @@ -89,19 +89,19 @@ void testHandleProjectRequestSuccessWithNoFurtherOperationsWhenNoAlmConfiguratio void testHandleProjectRequestThrowsExceptionWhenAlmForProjectDoesNotExist() { ValidateBindingAction underTest = new ValidateBindingAction(dbClient, componentFinder, userSession, Collections.emptyList()); - ProjectDto projectDto = mock(ProjectDto.class); - Request request = mock(Request.class); - Response response = mock(Response.class); - DbSession dbSession = mock(DbSession.class); + ProjectDto projectDto = mock(); + Request request = mock(); + Response response = mock(); + DbSession dbSession = mock(); String almUuid = "almUuid"; - ProjectAlmSettingDto projectAlmSettingDto = mock(ProjectAlmSettingDto.class); + ProjectAlmSettingDto projectAlmSettingDto = mock(); when(projectAlmSettingDto.getAlmSettingUuid()).thenReturn(almUuid); - ProjectAlmSettingDao projectAlmSettingDao = mock(ProjectAlmSettingDao.class); + ProjectAlmSettingDao projectAlmSettingDao = mock(); when(projectAlmSettingDao.selectByProject(dbSession, projectDto)).thenReturn(Optional.of(projectAlmSettingDto)); when(dbClient.projectAlmSettingDao()).thenReturn(projectAlmSettingDao); - AlmSettingDao almSettingDao = mock(AlmSettingDao.class); + AlmSettingDao almSettingDao = mock(); when(almSettingDao.selectByUuid(dbSession, almUuid)).thenReturn(Optional.empty()); when(dbClient.almSettingDao()).thenReturn(almSettingDao); @@ -115,21 +115,21 @@ void testHandleProjectRequestThrowsExceptionWhenAlmForProjectDoesNotExist() { void testHandleProjectRequestThrowsExceptionWhenNoValidatorExistsForAlm() { ValidateBindingAction underTest = new ValidateBindingAction(dbClient, componentFinder, userSession, Collections.emptyList()); - ProjectDto projectDto = mock(ProjectDto.class); - Request request = mock(Request.class); - Response response = mock(Response.class); - DbSession dbSession = mock(DbSession.class); + ProjectDto projectDto = mock(); + Request request = mock(); + Response response = mock(); + DbSession dbSession = mock(); String almUuid = "almUuid"; - ProjectAlmSettingDto projectAlmSettingDto = mock(ProjectAlmSettingDto.class); + ProjectAlmSettingDto projectAlmSettingDto = mock(); when(projectAlmSettingDto.getAlmSettingUuid()).thenReturn(almUuid); - ProjectAlmSettingDao projectAlmSettingDao = mock(ProjectAlmSettingDao.class); + ProjectAlmSettingDao projectAlmSettingDao = mock(); when(projectAlmSettingDao.selectByProject(dbSession, projectDto)).thenReturn(Optional.of(projectAlmSettingDto)); when(dbClient.projectAlmSettingDao()).thenReturn(projectAlmSettingDao); - AlmSettingDto almSettingDto = mock(AlmSettingDto.class); + AlmSettingDto almSettingDto = mock(); when(almSettingDto.getAlm()).thenReturn(ALM.AZURE_DEVOPS); - AlmSettingDao almSettingDao = mock(AlmSettingDao.class); + AlmSettingDao almSettingDao = mock(); when(almSettingDao.selectByUuid(dbSession, almUuid)).thenReturn(Optional.of(almSettingDto)); when(dbClient.almSettingDao()).thenReturn(almSettingDao); @@ -141,26 +141,26 @@ void testHandleProjectRequestThrowsExceptionWhenNoValidatorExistsForAlm() { @Test void testHandleProjectRequestThrowsInvalidConfigurationExceptionWhenRuntimeExceptionThrownByValidator() { - Validator validator = mock(Validator.class); + Validator validator = mock(); when(validator.alm()).thenReturn(Collections.singletonList(ALM.AZURE_DEVOPS)); doThrow(new InvalidConfigurationException(InvalidConfigurationException.Scope.PROJECT, "dummy")).when(validator).validate(any(), any()); ValidateBindingAction underTest = new ValidateBindingAction(dbClient, componentFinder, userSession, Collections.singletonList(validator)); - ProjectDto projectDto = mock(ProjectDto.class); - Request request = mock(Request.class); - Response response = mock(Response.class); - DbSession dbSession = mock(DbSession.class); + ProjectDto projectDto = mock(); + Request request = mock(); + Response response = mock(); + DbSession dbSession = mock(); String almUuid = "almUuid"; - ProjectAlmSettingDto projectAlmSettingDto = mock(ProjectAlmSettingDto.class); + ProjectAlmSettingDto projectAlmSettingDto = mock(); when(projectAlmSettingDto.getAlmSettingUuid()).thenReturn(almUuid); - ProjectAlmSettingDao projectAlmSettingDao = mock(ProjectAlmSettingDao.class); + ProjectAlmSettingDao projectAlmSettingDao = mock(); when(projectAlmSettingDao.selectByProject(dbSession, projectDto)).thenReturn(Optional.of(projectAlmSettingDto)); when(dbClient.projectAlmSettingDao()).thenReturn(projectAlmSettingDao); - AlmSettingDto almSettingDto = mock(AlmSettingDto.class); + AlmSettingDto almSettingDto = mock(); when(almSettingDto.getAlm()).thenReturn(ALM.AZURE_DEVOPS); - AlmSettingDao almSettingDao = mock(AlmSettingDao.class); + AlmSettingDao almSettingDao = mock(); when(almSettingDao.selectByUuid(dbSession, almUuid)).thenReturn(Optional.of(almSettingDto)); when(dbClient.almSettingDao()).thenReturn(almSettingDao); @@ -172,29 +172,29 @@ void testHandleProjectRequestThrowsInvalidConfigurationExceptionWhenRuntimeExcep @Test void testHandleProjectRequestHappyPath() { - Validator validator = mock(Validator.class); + Validator validator = mock(); when(validator.alm()).thenReturn(Collections.singletonList(ALM.AZURE_DEVOPS)); ValidateBindingAction underTest = new ValidateBindingAction(dbClient, componentFinder, userSession, Collections.singletonList(validator)); - ProjectDto projectDto = mock(ProjectDto.class); - Request request = mock(Request.class); - Response response = mock(Response.class); - DbSession dbSession = mock(DbSession.class); + ProjectDto projectDto = mock(); + Request request = mock(); + Response response = mock(); + DbSession dbSession = mock(); when(dbClient.openSession(anyBoolean())).thenReturn(dbSession); when(componentFinder.getProjectByKey(dbSession, "project")).thenReturn(projectDto); String almUuid = "almUuid"; - ProjectAlmSettingDto projectAlmSettingDto = mock(ProjectAlmSettingDto.class); + ProjectAlmSettingDto projectAlmSettingDto = mock(); when(projectAlmSettingDto.getAlmSettingUuid()).thenReturn(almUuid); - ProjectAlmSettingDao projectAlmSettingDao = mock(ProjectAlmSettingDao.class); + ProjectAlmSettingDao projectAlmSettingDao = mock(); when(projectAlmSettingDao.selectByProject(dbSession, projectDto)).thenReturn(Optional.of(projectAlmSettingDto)); when(dbClient.projectAlmSettingDao()).thenReturn(projectAlmSettingDao); - AlmSettingDto almSettingDto = mock(AlmSettingDto.class); + AlmSettingDto almSettingDto = mock(); when(almSettingDto.getAlm()).thenReturn(ALM.AZURE_DEVOPS); - AlmSettingDao almSettingDao = mock(AlmSettingDao.class); + AlmSettingDao almSettingDao = mock(); when(almSettingDao.selectByUuid(dbSession, almUuid)).thenReturn(Optional.of(almSettingDto)); when(dbClient.almSettingDao()).thenReturn(almSettingDao); diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/ws/pullrequest/PullRequestWsTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/ws/pullrequest/PullRequestWsTest.java index 6c88d7854..06a8cb4c6 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/ws/pullrequest/PullRequestWsTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/ws/pullrequest/PullRequestWsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2022 Michael Clarke + * Copyright (C) 2022-2024 Michael Clarke * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -32,10 +32,10 @@ class PullRequestWsTest { @Test void shouldCallDefineOnEachAction() { - PullRequestWsAction[] pullRequestWsActions = new PullRequestWsAction[]{mock(PullRequestWsAction.class), mock(PullRequestWsAction.class), mock(PullRequestWsAction.class)}; + PullRequestWsAction[] pullRequestWsActions = new PullRequestWsAction[]{mock(), mock(), mock()}; - WebService.Context context = mock(WebService.Context.class); - WebService.NewController controller = mock(WebService.NewController.class); + WebService.Context context = mock(); + WebService.NewController controller = mock(); when(context.createController(any())).thenReturn(controller); new PullRequestWs(pullRequestWsActions).define(context); diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/ws/pullrequest/action/DeleteActionTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/ws/pullrequest/action/DeleteActionTest.java index 421ca32db..a372880af 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/ws/pullrequest/action/DeleteActionTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/ws/pullrequest/action/DeleteActionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2022-2023 Michael Clarke + * Copyright (C) 2022-2024 Michael Clarke * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -46,20 +46,20 @@ class DeleteActionTest { - private final DbClient dbClient = mock(DbClient.class); - private final UserSession userSession = mock(UserSession.class); - private final ComponentFinder componentFinder = mock(ComponentFinder.class); - private final ComponentCleanerService componentCleanerService = mock(ComponentCleanerService.class); + private final DbClient dbClient = mock(); + private final UserSession userSession = mock(); + private final ComponentFinder componentFinder = mock(); + private final ComponentCleanerService componentCleanerService = mock(); private final DeleteAction underTest = new DeleteAction(dbClient, componentFinder, userSession, componentCleanerService); @Test void shouldDefineEndpointWithAllParameters() { - WebService.NewController newController = mock(WebService.NewController.class); - WebService.NewAction newAction = mock(WebService.NewAction.class); + WebService.NewController newController = mock(); + WebService.NewAction newAction = mock(); when(newAction.setHandler(any())).thenReturn(newAction); when(newController.createAction(any())).thenReturn(newAction); - WebService.NewParam projectParam = mock(WebService.NewParam.class); - WebService.NewParam pullRequestParam = mock(WebService.NewParam.class); + WebService.NewParam projectParam = mock(); + WebService.NewParam pullRequestParam = mock(); when(newAction.createParam(any())).thenReturn(projectParam, pullRequestParam); when(newAction.setPost(anyBoolean())).thenReturn(newAction); @@ -82,7 +82,7 @@ void shouldDefineEndpointWithAllParameters() { @Test void shouldExecuteRequestWithValidParameters() { - Request request = mock(Request.class); + Request request = mock(); when(request.mandatoryParam("project")).thenReturn("project"); when(request.mandatoryParam("pullRequest")).thenReturn("pullRequestId"); @@ -91,11 +91,11 @@ void shouldExecuteRequestWithValidParameters() { when(userSession.checkLoggedIn()).thenReturn(userSession); BranchDto pullRequest = new BranchDto().setBranchType(BranchType.PULL_REQUEST); - BranchDao branchDao = mock(BranchDao.class); + BranchDao branchDao = mock(); when(dbClient.branchDao()).thenReturn(branchDao); when(branchDao.selectByPullRequestKey(any(), any(), any())).thenReturn(Optional.of(pullRequest)); - Response response = mock(Response.class); + Response response = mock(); underTest.handle(request, response); @@ -105,7 +105,7 @@ void shouldExecuteRequestWithValidParameters() { @Test void shouldNotPerformDeleteIfUserNotLoggedIn() { - Request request = mock(Request.class); + Request request = mock(); when(request.mandatoryParam("project")).thenReturn("project"); when(request.mandatoryParam("pullRequest")).thenReturn("pullRequestId"); @@ -113,7 +113,7 @@ void shouldNotPerformDeleteIfUserNotLoggedIn() { when(userSession.checkLoggedIn()).thenThrow(new UnauthorizedException("Dummy")); - Response response = mock(Response.class); + Response response = mock(); assertThatThrownBy(() -> underTest.handle(request, response)).isInstanceOf(UnauthorizedException.class).hasMessage("Dummy"); @@ -123,7 +123,7 @@ void shouldNotPerformDeleteIfUserNotLoggedIn() { @Test void shouldNotPerformDeleteIfUserNotProjectAdmin() { - Request request = mock(Request.class); + Request request = mock(); when(request.mandatoryParam("project")).thenReturn("project"); when(request.mandatoryParam("pullRequest")).thenReturn("pullRequestId"); @@ -132,7 +132,7 @@ void shouldNotPerformDeleteIfUserNotProjectAdmin() { when(userSession.checkLoggedIn()).thenReturn(userSession); when(userSession.hasEntityPermission(any(), any(EntityDto.class))).thenThrow(new UnauthorizedException("Dummy")); - Response response = mock(Response.class); + Response response = mock(); assertThatThrownBy(() -> underTest.handle(request, response)).isInstanceOf(UnauthorizedException.class).hasMessage("Dummy"); diff --git a/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/ws/pullrequest/action/ListActionTest.java b/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/ws/pullrequest/action/ListActionTest.java index e90a065b4..3ea7f759b 100644 --- a/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/ws/pullrequest/action/ListActionTest.java +++ b/src/test/java/com/github/mc1arke/sonarqube/plugin/server/pullrequest/ws/pullrequest/action/ListActionTest.java @@ -51,19 +51,19 @@ class ListActionTest { - private final DbClient dbClient = mock(DbClient.class); - private final UserSession userSession = mock(UserSession.class); - private final ComponentFinder componentFinder = mock(ComponentFinder.class); - private final ProtoBufWriter protoBufWriter = mock(ProtoBufWriter.class); + private final DbClient dbClient = mock(); + private final UserSession userSession = mock(); + private final ComponentFinder componentFinder = mock(); + private final ProtoBufWriter protoBufWriter = mock(); private final ListAction underTest = new ListAction(dbClient, componentFinder, userSession, protoBufWriter); @Test void shouldDefineEndpointWithProjectParameter() { - WebService.NewController newController = mock(WebService.NewController.class); - WebService.NewAction newAction = mock(WebService.NewAction.class); + WebService.NewController newController = mock(); + WebService.NewAction newAction = mock(); when(newAction.setHandler(any())).thenReturn(newAction); when(newController.createAction(any())).thenReturn(newAction); - WebService.NewParam projectParam = mock(WebService.NewParam.class); + WebService.NewParam projectParam = mock(); when(newAction.createParam(any())).thenReturn(projectParam); underTest.define(newController); @@ -80,14 +80,14 @@ void shouldDefineEndpointWithProjectParameter() { @Test void shouldExecuteRequestWithValidParameter() { - Request request = mock(Request.class); + Request request = mock(); when(request.mandatoryParam("project")).thenReturn("project"); when(componentFinder.getProjectByKey(any(), any())).thenReturn(new ProjectDto().setKey("projectKey").setUuid("uuid0")); when(userSession.hasPermission(any())).thenReturn(true); - BranchDao branchDao = mock(BranchDao.class); + BranchDao branchDao = mock(); when(dbClient.branchDao()).thenReturn(branchDao); when(branchDao.selectByProject(any(), any())).thenReturn(List.of(new BranchDto() .setBranchType(BranchType.PULL_REQUEST) @@ -130,17 +130,17 @@ void shouldExecuteRequestWithValidParameter() { .setUuid("uuid2") .setKey("branch2Key"))); - LiveMeasureDao liveMeasureDao = mock(LiveMeasureDao.class); + LiveMeasureDao liveMeasureDao = mock(); when(dbClient.liveMeasureDao()).thenReturn(liveMeasureDao); when(liveMeasureDao.selectByComponentUuidsAndMetricKeys(any(), any(), any())).thenReturn(List.of(new LiveMeasureDto() .setComponentUuid("uuid1") .setData("live measure"))); - SnapshotDao snapshotDao = mock(SnapshotDao.class); + SnapshotDao snapshotDao = mock(); when(dbClient.snapshotDao()).thenReturn(snapshotDao); when(snapshotDao.selectLastAnalysesByRootComponentUuids(any(), any())).thenReturn(List.of(new SnapshotDto().setRootComponentUuid("uuid3").setCreatedAt(1234567891234L))); - Response response = mock(Response.class); + Response response = mock(); ProjectPullRequests.ListWsResponse expected = ProjectPullRequests.ListWsResponse.newBuilder() .addPullRequests(ProjectPullRequests.PullRequest.newBuilder() @@ -184,7 +184,7 @@ void shouldExecuteRequestWithValidParameter() { underTest.handle(request, response); - ArgumentCaptor messageArgumentCaptor = ArgumentCaptor.forClass(ProjectPullRequests.ListWsResponse.class); + ArgumentCaptor messageArgumentCaptor = ArgumentCaptor.captor(); verify(protoBufWriter).write(messageArgumentCaptor.capture(), eq(request), eq(response)); assertThat(messageArgumentCaptor.getValue()).usingRecursiveComparison().isEqualTo(expected); @@ -192,10 +192,10 @@ void shouldExecuteRequestWithValidParameter() { @Test void shouldNotExecuteRequestIfUserDoesNotHaveAnyPermissions() { - Request request = mock(Request.class); + Request request = mock(); when(request.mandatoryParam("project")).thenReturn("project"); - Response response = mock(Response.class); + Response response = mock(); assertThatThrownBy(() -> underTest.handle(request, response)).isInstanceOf(ForbiddenException.class);