From d6a142e8be676ee057e83f9cfea1c278101a2061 Mon Sep 17 00:00:00 2001 From: strangelookingnerd Date: Thu, 16 Jan 2025 10:13:06 +0100 Subject: [PATCH 1/3] Migrate tests to JUnit5 * Use JUnit5 annotations and imports * Cleanup assertions * Remove public visibility from test classes and methods --- pom.xml | 5 + .../ApacheAsyncHttpClientTest.java | 51 +++++----- ...turePromiseHttpPromiseAsyncClientTest.java | 16 ++-- .../plugins/jira/ChangingWorkflowTest.java | 30 +++--- .../hudson/plugins/jira/CliParameterTest.java | 21 ++-- .../hudson/plugins/jira/ConfigAsCodeTest.java | 23 ++--- .../plugins/jira/CredentialsHelperTest.java | 21 ++-- .../plugins/jira/DescriptorImplTest.java | 24 +++-- .../jira/EmptyFriendlyURLConverterTest.java | 20 ++-- .../plugins/jira/EnvironmentExpanderTest.java | 18 ++-- .../jira/JiraChangeLogAnnotatorTest.java | 42 ++++---- .../jira/JiraCreateIssueNotifierTest.java | 56 +++++------ .../jira/JiraCreateReleaseNotesTest.java | 38 ++++---- ...JiraEnvironmentContributingActionTest.java | 8 +- .../JiraEnvironmentVariableBuilderTest.java | 23 ++--- .../plugins/jira/JiraFolderPropertyTest.java | 13 ++- .../jira/JiraGlobalConfigurationSaveTest.java | 51 +++++----- .../jira/JiraGlobalConfigurationTest.java | 16 ++-- .../plugins/jira/JiraIssueMigratorTest.java | 18 ++-- .../jira/JiraIssueParameterDefResultTest.java | 20 ++-- .../jira/JiraIssueUpdateBuilderTest.java | 18 ++-- .../plugins/jira/JiraIssueUpdaterTest.java | 12 +-- .../plugins/jira/JiraJobActionTest.java | 28 +++--- .../plugins/jira/JiraProjectPropertyTest.java | 37 ++++---- .../JiraReplaceFixVersionByRegExTest.java | 18 ++-- .../jira/JiraRestServiceProxyTest.java | 32 +++---- .../plugins/jira/JiraRestServiceTest.java | 21 ++-- .../jira/JiraSiteSecurity1029Test.java | 24 ++--- .../hudson/plugins/jira/JiraSiteTest.java | 95 +++++++++---------- .../jira/MailResolverDisabledTest.java | 17 ++-- .../jira/MailResolverWithExtensionTest.java | 25 +++-- .../hudson/plugins/jira/UnmaskMailTest.java | 11 ++- .../java/hudson/plugins/jira/UpdaterTest.java | 63 ++++++------ .../plugins/jira/VersionCreatorTest.java | 22 ++--- .../plugins/jira/VersionReleaserTest.java | 24 ++--- .../BearerHttpAuthenticationHandlerTest.java | 6 +- .../auth/JiraRestServiceBearerAuthTest.java | 21 ++-- .../jira/pipeline/CommentStepTest.java | 23 ++--- .../pipeline/IssueFieldUpdateStepTest.java | 56 +++++------ .../jira/pipeline/IssueSelectorStepTest.java | 30 +++--- .../jira/pipeline/SearchIssuesStepTest.java | 23 ++--- .../selector/DefaultIssueSelectorTest.java | 51 +++++----- .../selector/ExplicitIssueSelectorTest.java | 6 +- .../jira/selector/JqlIssueSelectorTest.java | 20 ++-- .../perforce/JobIssueSelectorTest.java | 19 ++-- .../perforce/P4JobIssueSelectorTest.java | 12 +-- .../JiraVersionParameterDefinitionTest.java | 8 +- .../VersionComparatorTest.java | 12 +-- 48 files changed, 609 insertions(+), 639 deletions(-) diff --git a/pom.xml b/pom.xml index 414003bfd..cb0be1870 100644 --- a/pom.xml +++ b/pom.xml @@ -328,6 +328,11 @@ mockito-core test + + org.mockito + mockito-junit-jupiter + test + diff --git a/src/test/java/com/atlassian/httpclient/apache/httpcomponents/ApacheAsyncHttpClientTest.java b/src/test/java/com/atlassian/httpclient/apache/httpcomponents/ApacheAsyncHttpClientTest.java index 405bda4f4..d514155f5 100644 --- a/src/test/java/com/atlassian/httpclient/apache/httpcomponents/ApacheAsyncHttpClientTest.java +++ b/src/test/java/com/atlassian/httpclient/apache/httpcomponents/ApacheAsyncHttpClientTest.java @@ -1,5 +1,7 @@ package com.atlassian.httpclient.apache.httpcomponents; +import static org.junit.jupiter.api.Assertions.assertEquals; + import com.atlassian.httpclient.api.Response; import com.atlassian.httpclient.api.factory.HttpClientOptions; import com.atlassian.sal.api.ApplicationProperties; @@ -28,17 +30,14 @@ import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.util.Callback; -import org.junit.After; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; +@WithJenkins public class ApacheAsyncHttpClientTest { - @Rule - public JenkinsRule j = new JenkinsRule(); - private final ConnectionFactory connectionFactory = new HttpConnectionFactory(); private Server server; @@ -55,15 +54,15 @@ public void prepare(Handler handler) throws Exception { server.start(); } - @After - public void dispose() throws Exception { + @AfterEach + void dispose() throws Exception { if (server != null) { server.stop(); } } @Test - public void simple_get() throws Exception { + void simple_get(JenkinsRule r) throws Exception { TestHandler testHandler = new TestHandler(); prepare(testHandler); @@ -74,12 +73,12 @@ public void simple_get() throws Exception { .newRequest("http://localhost:" + connector.getLocalPort() + "/foo") .get() .get(10, TimeUnit.SECONDS); - Assert.assertEquals(200, response.getStatusCode()); - Assert.assertEquals(CONTENT_RESPONSE, IOUtils.toString(response.getEntityStream())); + assertEquals(200, response.getStatusCode()); + assertEquals(CONTENT_RESPONSE, IOUtils.toString(response.getEntityStream())); } @Test - public void simple_post() throws Exception { + void simple_post(JenkinsRule r) throws Exception { TestHandler testHandler = new TestHandler(); prepare(testHandler); @@ -92,13 +91,13 @@ public void simple_post() throws Exception { .setContentType("text") .post() .get(10, TimeUnit.SECONDS); - Assert.assertEquals(200, response.getStatusCode()); - Assert.assertEquals(CONTENT_RESPONSE, IOUtils.toString(response.getEntityStream())); - Assert.assertEquals("FOO", testHandler.postReceived); + assertEquals(200, response.getStatusCode()); + assertEquals(CONTENT_RESPONSE, IOUtils.toString(response.getEntityStream())); + assertEquals("FOO", testHandler.postReceived); } @Test - public void simple_get_with_non_proxy_host() throws Exception { + void simple_get_with_non_proxy_host(JenkinsRule r) throws Exception { ProxyTestHandler testHandler = new ProxyTestHandler(); prepare(testHandler); @@ -109,12 +108,12 @@ public void simple_get_with_non_proxy_host() throws Exception { null, buildApplicationProperties(), new NoOpThreadLocalContextManager(), new HttpClientOptions()); Response response = httpClient.newRequest("http://www.apache.org").get().get(30, TimeUnit.SECONDS); - Assert.assertEquals(200, response.getStatusCode()); - // Assert.assertEquals( CONTENT_RESPONSE, IOUtils.toString( response.getEntityStream() ) ); + assertEquals(200, response.getStatusCode()); + // assertEquals(CONTENT_RESPONSE, IOUtils.toString(response.getEntityStream())); } @Test - public void simple_get_with_proxy() throws Exception { + void simple_get_with_proxy(JenkinsRule r) throws Exception { ProxyTestHandler testHandler = new ProxyTestHandler(); prepare(testHandler); @@ -124,12 +123,12 @@ public void simple_get_with_proxy() throws Exception { null, buildApplicationProperties(), new NoOpThreadLocalContextManager(), new HttpClientOptions()); Response response = httpClient.newRequest("http://jenkins.io").get().get(30, TimeUnit.SECONDS); - Assert.assertEquals(200, response.getStatusCode()); - Assert.assertEquals(CONTENT_RESPONSE, IOUtils.toString(response.getEntityStream())); + assertEquals(200, response.getStatusCode()); + assertEquals(CONTENT_RESPONSE, IOUtils.toString(response.getEntityStream())); } @Test - public void simple_post_with_proxy() throws Exception { + void simple_post_with_proxy(JenkinsRule r) throws Exception { ProxyTestHandler testHandler = new ProxyTestHandler(); prepare(testHandler); @@ -145,9 +144,9 @@ public void simple_post_with_proxy() throws Exception { .post() .get(30, TimeUnit.SECONDS); // we are sure to hit the proxy first :-) - Assert.assertEquals(200, response.getStatusCode()); - Assert.assertEquals(CONTENT_RESPONSE, IOUtils.toString(response.getEntityStream())); - Assert.assertEquals("FOO", testHandler.postReceived); + assertEquals(200, response.getStatusCode()); + assertEquals(CONTENT_RESPONSE, IOUtils.toString(response.getEntityStream())); + assertEquals("FOO", testHandler.postReceived); } public static class ProxyTestHandler extends Handler.Abstract { diff --git a/src/test/java/com/atlassian/httpclient/apache/httpcomponents/CompletableFuturePromiseHttpPromiseAsyncClientTest.java b/src/test/java/com/atlassian/httpclient/apache/httpcomponents/CompletableFuturePromiseHttpPromiseAsyncClientTest.java index f8abb5e5b..edd3b28a6 100644 --- a/src/test/java/com/atlassian/httpclient/apache/httpcomponents/CompletableFuturePromiseHttpPromiseAsyncClientTest.java +++ b/src/test/java/com/atlassian/httpclient/apache/httpcomponents/CompletableFuturePromiseHttpPromiseAsyncClientTest.java @@ -15,15 +15,15 @@ import org.apache.http.concurrent.FutureCallback; import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; import org.apache.http.protocol.HttpContext; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.stubbing.Answer; -@RunWith(MockitoJUnitRunner.class) -public class CompletableFuturePromiseHttpPromiseAsyncClientTest { +@ExtendWith(MockitoExtension.class) +class CompletableFuturePromiseHttpPromiseAsyncClientTest { @Mock private CloseableHttpAsyncClient client; @@ -47,7 +47,7 @@ public class CompletableFuturePromiseHttpPromiseAsyncClientTest { private CompletableFuturePromiseHttpPromiseAsyncClient asyncClient; @Test - public void ensureCloseHttpclientOnCompletion() throws IOException { + void ensureCloseHttpclientOnCompletion() throws IOException { when(client.execute(eq(request), eq(context), any())).then((Answer>) invocation -> { invocation.getArgument(2, FutureCallback.class).completed(response); return mock(Future.class); @@ -59,7 +59,7 @@ public void ensureCloseHttpclientOnCompletion() throws IOException { } @Test - public void ensureCloseHttpclientOnFailure() throws IOException { + void ensureCloseHttpclientOnFailure() throws IOException { when(client.execute(eq(request), eq(context), any())).then((Answer>) invocation -> { invocation.getArgument(2, FutureCallback.class).failed(null); return mock(Future.class); @@ -71,7 +71,7 @@ public void ensureCloseHttpclientOnFailure() throws IOException { } @Test - public void ensureCloseHttpclientOnCancellation() throws IOException { + void ensureCloseHttpclientOnCancellation() throws IOException { when(client.execute(eq(request), eq(context), any())).then((Answer>) invocation -> { invocation.getArgument(2, FutureCallback.class).cancelled(); return mock(Future.class); diff --git a/src/test/java/hudson/plugins/jira/ChangingWorkflowTest.java b/src/test/java/hudson/plugins/jira/ChangingWorkflowTest.java index 834ea2d5f..f2c7354e0 100644 --- a/src/test/java/hudson/plugins/jira/ChangingWorkflowTest.java +++ b/src/test/java/hudson/plugins/jira/ChangingWorkflowTest.java @@ -25,18 +25,18 @@ import java.util.Arrays; import java.util.Collections; import java.util.concurrent.TimeoutException; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; /** * User: lanwen * Date: 10.09.13 * Time: 0:57 */ -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public class ChangingWorkflowTest { public static final String NON_EMPTY_COMMENT = "Non empty comment"; @@ -57,25 +57,25 @@ public class ChangingWorkflowTest { private JiraSession spySession; - @Before - public void setupSpy() { + @BeforeEach + void setupSpy() { spySession = spy(new JiraSession(site, restService)); } @Test - public void onGetActionItInvokesServiceMethod() { + void onGetActionItInvokesServiceMethod() { spySession.getActionIdForIssue(ISSUE_JQL, NON_EMPTY_WORKFLOW_LOWERCASE); verify(restService, times(1)).getAvailableActions(eq(ISSUE_JQL)); } @Test - public void getActionIdReturnsNullWhenServiceReturnsNull() { + void getActionIdReturnsNullWhenServiceReturnsNull() { doReturn(null).when(restService).getAvailableActions(ISSUE_JQL); assertThat(spySession.getActionIdForIssue(ISSUE_JQL, NON_EMPTY_WORKFLOW_LOWERCASE), nullValue()); } @Test - public void getActionIdIteratesOverAllActionsEvenOneOfNamesIsNull() { + void getActionIdIteratesOverAllActionsEvenOneOfNamesIsNull() { Transition action1 = mock(Transition.class); Transition action2 = mock(Transition.class); @@ -90,7 +90,7 @@ public void getActionIdIteratesOverAllActionsEvenOneOfNamesIsNull() { } @Test - public void getActionIdReturnsNullWhenNullWorkflowUsed() { + void getActionIdReturnsNullWhenNullWorkflowUsed() { String workflowAction = null; Transition action1 = mock(Transition.class); when(action1.getName()).thenReturn("name"); @@ -100,7 +100,7 @@ public void getActionIdReturnsNullWhenNullWorkflowUsed() { } @Test - public void getActionIdReturnsIdWhenFoundIgnorecaseWorkflow() { + void getActionIdReturnsIdWhenFoundIgnorecaseWorkflow() { String id = randomNumeric(5); Transition action1 = mock(Transition.class); when(action1.getName()).thenReturn(NON_EMPTY_WORKFLOW_LOWERCASE.toUpperCase()); @@ -112,7 +112,7 @@ public void getActionIdReturnsIdWhenFoundIgnorecaseWorkflow() { } @Test - public void addCommentsOnNonEmptyWorkflowAndNonEmptyComment() throws Exception { + void addCommentsOnNonEmptyWorkflowAndNonEmptyComment() throws Exception { when(site.getSession(any(), anyBoolean())).thenCallRealMethod(); when(site.getSession(any())).thenCallRealMethod(); when(site.createSession(any(), anyBoolean())).thenReturn(mockSession); @@ -130,7 +130,7 @@ public void addCommentsOnNonEmptyWorkflowAndNonEmptyComment() throws Exception { } @Test - public void addCommentsOnNullWorkflowAndNonEmptyComment() throws Exception { + void addCommentsOnNullWorkflowAndNonEmptyComment() throws Exception { when(site.getSession(any())).thenCallRealMethod(); when(site.getSession(any(), anyBoolean())).thenCallRealMethod(); when(site.createSession(any(), anyBoolean())).thenReturn(mockSession); @@ -146,7 +146,7 @@ public void addCommentsOnNullWorkflowAndNonEmptyComment() throws Exception { } @Test - public void dontAddCommentsOnNullWorkflowAndNullComment() throws TimeoutException { + void dontAddCommentsOnNullWorkflowAndNullComment() throws TimeoutException { site.progressMatchingIssues(ISSUE_JQL, null, null, mock(PrintStream.class)); verify(mockSession, never()).addComment(anyString(), anyString(), isNull(), isNull()); } diff --git a/src/test/java/hudson/plugins/jira/CliParameterTest.java b/src/test/java/hudson/plugins/jira/CliParameterTest.java index 82f84e813..8c463b2e2 100644 --- a/src/test/java/hudson/plugins/jira/CliParameterTest.java +++ b/src/test/java/hudson/plugins/jira/CliParameterTest.java @@ -10,25 +10,26 @@ import hudson.plugins.jira.listissuesparameter.JiraIssueParameterDefinition; import hudson.plugins.jira.versionparameter.JiraVersionParameterDefinition; import java.io.IOException; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; -public class CliParameterTest { +@WithJenkins +class CliParameterTest { - @Rule - public JenkinsRule jenkins = new JenkinsRule(); + private JenkinsRule jenkins; FreeStyleProject project; - @Before - public void setup() throws IOException { + @BeforeEach + void setup(JenkinsRule jenkins) throws IOException { + this.jenkins = jenkins; project = jenkins.createFreeStyleProject(); } @Test - public void jiraIssueParameterViaCli() throws Exception { + void jiraIssueParameterViaCli() throws Exception { project.addProperty(new ParametersDefinitionProperty( new JiraIssueParameterDefinition("jiraissue", "description", "filter"))); @@ -38,7 +39,7 @@ public void jiraIssueParameterViaCli() throws Exception { } @Test - public void jiraVersionParameterViaCli() throws Exception { + void jiraVersionParameterViaCli() throws Exception { project.addProperty(new ParametersDefinitionProperty( new JiraVersionParameterDefinition("jiraversion", "description", "PROJ", "RELEASE", "true", "false"))); diff --git a/src/test/java/hudson/plugins/jira/ConfigAsCodeTest.java b/src/test/java/hudson/plugins/jira/ConfigAsCodeTest.java index fc9ff9a5e..b76494945 100644 --- a/src/test/java/hudson/plugins/jira/ConfigAsCodeTest.java +++ b/src/test/java/hudson/plugins/jira/ConfigAsCodeTest.java @@ -3,43 +3,40 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import io.jenkins.plugins.casc.ConfigurationContext; import io.jenkins.plugins.casc.Configurator; import io.jenkins.plugins.casc.ConfiguratorRegistry; import io.jenkins.plugins.casc.misc.ConfiguredWithCode; import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithCodeRule; +import io.jenkins.plugins.casc.misc.junit.jupiter.WithJenkinsConfiguredWithCode; import io.jenkins.plugins.casc.model.CNode; import io.jenkins.plugins.casc.model.Mapping; import java.util.List; import java.util.Objects; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.jvnet.hudson.test.JenkinsRule; +import org.junit.jupiter.api.Test; -public class ConfigAsCodeTest { - - @Rule - public JenkinsRule r = new JenkinsConfiguredWithCodeRule(); +@WithJenkinsConfiguredWithCode +class ConfigAsCodeTest { @Test @ConfiguredWithCode("multiple-sites.yml") - public void shouldSupportConfigurationAsCode() throws Exception { + void shouldSupportConfigurationAsCode(JenkinsConfiguredWithCodeRule r) throws Exception { List sites = JiraGlobalConfiguration.get().getSites(); assertThat(sites, hasSize(2)); - Assert.assertEquals( + assertEquals( "https://issues.jenkins-ci.org/", Objects.requireNonNull(sites.get(0).getUrl()).toExternalForm()); - Assert.assertEquals( + assertEquals( "https://jira.com/", Objects.requireNonNull(sites.get(1).getUrl()).toExternalForm()); } @Test @ConfiguredWithCode("single-site.yml") - public void shouldExportConfigurationAsCode() throws Exception { + void shouldExportConfigurationAsCode(JenkinsConfiguredWithCodeRule r) throws Exception { ConfiguratorRegistry registry = ConfiguratorRegistry.get(); ConfigurationContext context = new ConfigurationContext(registry); final Configurator c = context.lookupOrFail(JiraGlobalConfiguration.class); diff --git a/src/test/java/hudson/plugins/jira/CredentialsHelperTest.java b/src/test/java/hudson/plugins/jira/CredentialsHelperTest.java index 2044f951a..442df83bb 100644 --- a/src/test/java/hudson/plugins/jira/CredentialsHelperTest.java +++ b/src/test/java/hudson/plugins/jira/CredentialsHelperTest.java @@ -3,8 +3,8 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.hasSize; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.CredentialsScope; @@ -18,19 +18,18 @@ import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; /** * @author Zhenlei Huang */ -public class CredentialsHelperTest { - @Rule - public JenkinsRule r = new JenkinsRule(); +@WithJenkins +class CredentialsHelperTest { @Test - public void lookupSystemCredentials() throws IOException, FormException { + void lookupSystemCredentials(JenkinsRule r) throws IOException, FormException { assertNull(CredentialsHelper.lookupSystemCredentials("nonexistent-credentials-id", null)); StandardUsernamePasswordCredentials c = @@ -42,7 +41,7 @@ public void lookupSystemCredentials() throws IOException, FormException { } @Test - public void lookupSystemCredentialsWithDomainRestriction() throws IOException, FormException { + void lookupSystemCredentialsWithDomainRestriction(JenkinsRule r) throws IOException, FormException { Domain domain = new Domain( "example", "test domain", @@ -57,7 +56,7 @@ public void lookupSystemCredentialsWithDomainRestriction() throws IOException, F } @Test - public void migrateCredentials() throws MalformedURLException, FormException { + void migrateCredentials(JenkinsRule r) throws MalformedURLException, FormException { assertThat( CredentialsProvider.lookupStores(r.jenkins).iterator().next().getCredentials(Domain.global()), empty()); @@ -71,7 +70,7 @@ public void migrateCredentials() throws MalformedURLException, FormException { } @Test - public void migrateCredentialsWithExsitingCredentials() throws IOException, FormException { + void migrateCredentialsWithExsitingCredentials(JenkinsRule r) throws IOException, FormException { Domain domain = new Domain( "example", "test domain", diff --git a/src/test/java/hudson/plugins/jira/DescriptorImplTest.java b/src/test/java/hudson/plugins/jira/DescriptorImplTest.java index 6c8267c96..ab800415e 100644 --- a/src/test/java/hudson/plugins/jira/DescriptorImplTest.java +++ b/src/test/java/hudson/plugins/jira/DescriptorImplTest.java @@ -2,8 +2,8 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasSize; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; @@ -35,20 +35,18 @@ import java.net.URL; import java.util.Arrays; import jenkins.model.Jenkins; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.MockAuthorizationStrategy; import org.jvnet.hudson.test.MockFolder; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.mockito.Mockito; /** * Created by warden on 14.09.15. */ -public class DescriptorImplTest { - - @Rule - public JenkinsRule r = new JenkinsRule(); +@WithJenkins +class DescriptorImplTest { AbstractBuild build = Mockito.mock(FreeStyleBuild.class); Run run = mock(Run.class); @@ -61,7 +59,7 @@ public class DescriptorImplTest { JiraSite.Builder builder = spy(new JiraSite.Builder()); @Test - public void doFillCredentialsIdItems() throws IOException, FormException { + void doFillCredentialsIdItems(JenkinsRule r) throws IOException, FormException { MockFolder dummy = r.createFolder("dummy"); r.jenkins.setSecurityRealm(r.createDummySecurityRealm()); @@ -90,7 +88,7 @@ public void doFillCredentialsIdItems() throws IOException, FormException { try (ACLContext ignored = ACL.as(User.getById("admin", true))) { ListBoxModel options = descriptor.doFillCredentialsIdItems(null, null, "http://example.org"); assertThat(options.toString(), options, hasSize(3)); - assertTrue(options.toString(), listBoxModelContainsName(options, CredentialsNameProvider.name(c1))); + assertTrue(listBoxModelContainsName(options, CredentialsNameProvider.name(c1)), options.toString()); options = descriptor.doFillCredentialsIdItems(null, null, "http://nonexistent.url"); assertThat(options.toString(), options, hasSize(1)); @@ -98,7 +96,7 @@ public void doFillCredentialsIdItems() throws IOException, FormException { options = descriptor.doFillCredentialsIdItems(dummy, null, "http://example.org"); assertThat(options.toString(), options, hasSize(2)); - assertTrue(options.toString(), listBoxModelContainsName(options, CredentialsNameProvider.name(c2))); + assertTrue(listBoxModelContainsName(options, CredentialsNameProvider.name(c2)), options.toString()); } try (ACLContext ignored = ACL.as(User.getById("alice", true))) { @@ -119,7 +117,7 @@ private boolean listBoxModelContainsName(ListBoxModel options, String name) { } @Test - public void validateFormConnectionErrors() throws Exception { + void validateFormConnectionErrors(JenkinsRule r) throws Exception { builder.withMainURL(new URL("http://test.com")); @@ -196,7 +194,7 @@ public void validateFormConnectionErrors() throws Exception { } @Test - public void validateFormConnectionOK() throws Exception { + void validateFormConnectionOK(JenkinsRule r) throws Exception { builder.withMainURL(new URL("http://test.com")); when(descriptor.getBuilder()).thenReturn(builder); diff --git a/src/test/java/hudson/plugins/jira/EmptyFriendlyURLConverterTest.java b/src/test/java/hudson/plugins/jira/EmptyFriendlyURLConverterTest.java index dc32f9469..1eebcfb4d 100644 --- a/src/test/java/hudson/plugins/jira/EmptyFriendlyURLConverterTest.java +++ b/src/test/java/hudson/plugins/jira/EmptyFriendlyURLConverterTest.java @@ -6,31 +6,29 @@ import java.net.URL; import org.apache.commons.lang.StringUtils; import org.hamcrest.Matchers; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.WithoutJenkins; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; /** * @author lanwen (Merkushev Kirill) */ +@WithJenkins public class EmptyFriendlyURLConverterTest { public static final String SOME_VALID_URL = "http://localhost/"; - @Rule - public JenkinsRule jRule = new JenkinsRule(); - @Test @WithoutJenkins - public void shouldHandleURLClass() throws Exception { + void shouldHandleURLClass() throws Exception { URL someUrl = new URL(SOME_VALID_URL); assertThat(new EmptyFriendlyURLConverter().convert(URL.class, someUrl), Matchers.is(someUrl)); } @Test @WithoutJenkins - public void shouldHandleStringClass() throws Exception { + void shouldHandleStringClass() throws Exception { assertThat( new EmptyFriendlyURLConverter().convert(URL.class, SOME_VALID_URL), Matchers.is(new URL(SOME_VALID_URL))); @@ -38,19 +36,19 @@ public void shouldHandleStringClass() throws Exception { @Test @WithoutJenkins - public void shouldHandleNull() throws Exception { + void shouldHandleNull() throws Exception { assertThat(new EmptyFriendlyURLConverter().convert(URL.class, null), nullValue()); } @Test @WithoutJenkins - public void shouldHandleEmptyString() throws Exception { + void shouldHandleEmptyString() throws Exception { assertThat(new EmptyFriendlyURLConverter().convert(URL.class, StringUtils.EMPTY), nullValue()); } @Test @WithoutJenkins - public void shouldHandleNullAsString() throws Exception { + void shouldHandleNullAsString() throws Exception { assertThat(new EmptyFriendlyURLConverter().convert(URL.class, "null"), nullValue()); } @@ -58,7 +56,7 @@ public void shouldHandleNullAsString() throws Exception { * Requires jenkins rule because of LOGGER usage starts descriptor creating */ @Test - public void shouldHandleMalformedUrlAsString() throws Exception { + void shouldHandleMalformedUrlAsString(JenkinsRule j) throws Exception { assertThat(new EmptyFriendlyURLConverter().convert(URL.class, "bla"), nullValue()); } } diff --git a/src/test/java/hudson/plugins/jira/EnvironmentExpanderTest.java b/src/test/java/hudson/plugins/jira/EnvironmentExpanderTest.java index ce15e3bcd..096efc6dd 100644 --- a/src/test/java/hudson/plugins/jira/EnvironmentExpanderTest.java +++ b/src/test/java/hudson/plugins/jira/EnvironmentExpanderTest.java @@ -10,11 +10,11 @@ import hudson.model.BuildListener; import hudson.model.FreeStyleBuild; import java.io.IOException; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; -public class EnvironmentExpanderTest { +class EnvironmentExpanderTest { private static final String VARIABLE = "${ISSUE_ID}"; private static final String ENVIRONMENT_KEY = "ISSUE_ID"; @@ -25,8 +25,8 @@ public class EnvironmentExpanderTest { BuildListener buildListener = mock(BuildListener.class); AbstractBuild currentBuild = mock(FreeStyleBuild.class); - @Before - public void createCharacteristicEnvironment() throws IOException, InterruptedException { + @BeforeEach + void createCharacteristicEnvironment() throws IOException, InterruptedException { env = new EnvVars(); env.put("BUILD_NUMBER", "1"); env.put("BUILD_URL", "/some/url/to/job"); @@ -36,13 +36,13 @@ public void createCharacteristicEnvironment() throws IOException, InterruptedExc } @Test - public void returnVariableWhenValueNotFound() { + void returnVariableWhenValueNotFound() { String value = EnvironmentExpander.expandVariable(VARIABLE, env); assertThat(value, equalTo(VARIABLE)); } @Test - public void returnValueWhenFound() { + void returnValueWhenFound() { env.put(ENVIRONMENT_KEY, ENVIRONMENT_VALUE); String value = EnvironmentExpander.expandVariable(VARIABLE, env); @@ -52,13 +52,13 @@ public void returnValueWhenFound() { } @Test - public void returnVariableFromNullRunEnvironment() { + void returnVariableFromNullRunEnvironment() { String value = EnvironmentExpander.expandVariable(VARIABLE, null, null); assertThat(value, equalTo(VARIABLE)); } @Test - public void returnValueFromRunEnvironment() { + void returnValueFromRunEnvironment() { env.put(ENVIRONMENT_KEY, ENVIRONMENT_VALUE); String value = EnvironmentExpander.expandVariable(VARIABLE, currentBuild, buildListener); diff --git a/src/test/java/hudson/plugins/jira/JiraChangeLogAnnotatorTest.java b/src/test/java/hudson/plugins/jira/JiraChangeLogAnnotatorTest.java index 19ddad4b5..9750f5d00 100644 --- a/src/test/java/hudson/plugins/jira/JiraChangeLogAnnotatorTest.java +++ b/src/test/java/hudson/plugins/jira/JiraChangeLogAnnotatorTest.java @@ -20,33 +20,33 @@ import java.util.HashSet; import java.util.concurrent.locks.ReentrantLock; import java.util.regex.Pattern; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.jvnet.hudson.test.Issue; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.stubbing.Answer; /** * @author Kohsuke Kawaguchi */ -@RunWith(MockitoJUnitRunner.class) -public class JiraChangeLogAnnotatorTest { +@ExtendWith(MockitoExtension.class) +class JiraChangeLogAnnotatorTest { private static final String TITLE = "title with $sign to confuse TextMarkup.replace"; - @Mock + @Mock(strictness = Mock.Strictness.LENIENT) private JiraSite site; @Mock private Run run; - @Mock + @Mock(strictness = Mock.Strictness.LENIENT) private JiraSession session; - @Before - public void before() throws Exception { + @BeforeEach + void before() throws Exception { when(session.getProjectKeys()).thenReturn(new HashSet(Arrays.asList("DUMMY", "JENKINS"))); when(site.getSession(any())).thenReturn(session); when(site.getProjectUpdateLock()).thenReturn(new ReentrantLock()); @@ -60,7 +60,7 @@ public void before() throws Exception { } @Test - public void annotate() { + void annotate() { when(run.getAction(JiraBuildAction.class)) .thenReturn(new JiraBuildAction(Collections.singleton(new JiraIssue("DUMMY-1", TITLE)))); @@ -76,7 +76,7 @@ public void annotate() { } @Test - public void annotateDisabledOnSiteLevel() { + void annotateDisabledOnSiteLevel() { JiraChangeLogAnnotator annotator = spy(new JiraChangeLogAnnotator()); doReturn(site).when(annotator).getSiteForProject(Mockito.any()); @@ -89,7 +89,7 @@ public void annotateDisabledOnSiteLevel() { } @Test - public void annotateWf() { + void annotateWf() { when(run.getAction(JiraBuildAction.class)) .thenReturn(new JiraBuildAction(Collections.singleton(new JiraIssue("DUMMY-1", TITLE)))); @@ -110,7 +110,7 @@ public void annotateWf() { * Regression test for this. */ @Test - public void wordBoundaryProblem() { + void wordBoundaryProblem() { JiraChangeLogAnnotator annotator = spy(new JiraChangeLogAnnotator()); doReturn(site).when(annotator).getSiteForProject(Mockito.any()); @@ -138,7 +138,7 @@ public void wordBoundaryProblem() { } @Test - public void matchMultipleIssueIds() { + void matchMultipleIssueIds() { JiraChangeLogAnnotator annotator = spy(new JiraChangeLogAnnotator()); doReturn(site).when(annotator).getSiteForProject(Mockito.any()); @@ -153,7 +153,7 @@ public void matchMultipleIssueIds() { } @Test - public void hasProjectForIssueIsCaseInsensitive() { + void hasProjectForIssueIsCaseInsensitive() { JiraChangeLogAnnotator annotator = spy(new JiraChangeLogAnnotator()); doReturn(site).when(annotator).getSiteForProject(Mockito.any()); @@ -168,7 +168,7 @@ public void hasProjectForIssueIsCaseInsensitive() { @Test @Issue("4132") - public void caseInsensitiveAnnotate() { + void caseInsensitiveAnnotate() { JiraChangeLogAnnotator annotator = spy(new JiraChangeLogAnnotator()); doReturn(site).when(annotator).getSiteForProject(Mockito.any()); @@ -184,7 +184,7 @@ public void caseInsensitiveAnnotate() { */ @Test @Issue("5252") - public void getIssueDetailsForMissingIssues() throws IOException { + void getIssueDetailsForMissingIssues() throws IOException { Run run = mock(Run.class); JiraChangeLogAnnotator annotator = spy(new JiraChangeLogAnnotator()); @@ -203,7 +203,7 @@ public void getIssueDetailsForMissingIssues() throws IOException { * no groups) */ @Test - public void invalidUserPattern() { + void invalidUserPattern() { JiraChangeLogAnnotator annotator = spy(new JiraChangeLogAnnotator()); when(site.getIssuePattern()).thenReturn(Pattern.compile("[a-zA-Z][a-zA-Z0-9_]+-[1-9][0-9]*")); @@ -221,7 +221,7 @@ public void invalidUserPattern() { * Previous implementation did so. */ @Test - public void matchOnlyMatchGroup1() throws IOException { + void matchOnlyMatchGroup1() throws IOException { JiraChangeLogAnnotator annotator = spy(new JiraChangeLogAnnotator()); doReturn(site).when(annotator).getSiteForProject(Mockito.any()); when(site.getIssuePattern()).thenReturn(Pattern.compile("([a-zA-Z][a-zA-Z0-9_]+-[1-9][0-9]*)abc")); @@ -249,7 +249,7 @@ public void matchOnlyMatchGroup1() throws IOException { * @throws Exception */ @Test - public void alternativeURLAnnotate() throws Exception { + void alternativeURLAnnotate() throws Exception { when(site.getAlternativeUrl(Mockito.anyString())).thenAnswer((Answer) invocation -> { String id = invocation.getArguments()[0].toString(); return new URL("http://altdummy/" + id); diff --git a/src/test/java/hudson/plugins/jira/JiraCreateIssueNotifierTest.java b/src/test/java/hudson/plugins/jira/JiraCreateIssueNotifierTest.java index 7d05cdae0..07b4c1e55 100644 --- a/src/test/java/hudson/plugins/jira/JiraCreateIssueNotifierTest.java +++ b/src/test/java/hudson/plugins/jira/JiraCreateIssueNotifierTest.java @@ -1,10 +1,7 @@ package hudson.plugins.jira; import static org.hamcrest.MatcherAssert.assertThat; -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.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; @@ -36,14 +33,15 @@ import java.util.Collections; import java.util.List; import org.hamcrest.Matchers; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.WithoutJenkins; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.mockito.Mockito; +@WithJenkins public class JiraCreateIssueNotifierTest { private static final String JIRA_PROJECT = "PROJECT"; @@ -66,18 +64,11 @@ public class JiraCreateIssueNotifierTest { AbstractBuild currentBuild = mock(FreeStyleBuild.class); File temporaryDirectory; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File temporaryFolder; - @Rule - public JenkinsRule j = new JenkinsRule(); - - { - j.timeout = 0; - } - - @Before - public void createCommonMocks() throws IOException, InterruptedException { + @BeforeEach + void createCommonMocks() throws IOException, InterruptedException { env = new EnvVars(); env.put("BUILD_NUMBER", "10"); env.put("BUILD_URL", "/some/url/to/job"); @@ -92,7 +83,7 @@ public void createCommonMocks() throws IOException, InterruptedException { doReturn(env).when(currentBuild).getEnvironment(Mockito.any()); - temporaryDirectory = temporaryFolder.newFolder(); + temporaryDirectory = newFolder(temporaryFolder, "junit"); when(project.getBuildDir()).thenReturn(temporaryDirectory); when(currentBuild.getProject()).thenReturn(project); @@ -105,7 +96,7 @@ public void createCommonMocks() throws IOException, InterruptedException { @Test @WithoutJenkins - public void performSuccessFailure() throws Exception { + void performSuccessFailure() throws Exception { when(previousBuild.getResult()).thenReturn(Result.SUCCESS); when(currentBuild.getResult()).thenReturn(Result.FAILURE); @@ -129,7 +120,7 @@ public void performSuccessFailure() throws Exception { @Test @WithoutJenkins - public void performSuccessFailureWithEnv() throws Exception { + void performSuccessFailureWithEnv() throws Exception { when(previousBuild.getResult()).thenReturn(Result.SUCCESS); when(currentBuild.getResult()).thenReturn(Result.FAILURE); @@ -153,7 +144,7 @@ public void performSuccessFailureWithEnv() throws Exception { @Test @WithoutJenkins - public void performFailureFailure() throws Exception { + void performFailureFailure() throws Exception { JiraCreateIssueNotifier notifier = spy(new JiraCreateIssueNotifier(JIRA_PROJECT, DESCRIPTION, ASSIGNEE, COMPONENT, 1L, 1L, 1)); doReturn(site).when(notifier).getSiteForProject(Mockito.any()); @@ -197,7 +188,7 @@ public void performFailureFailure() throws Exception { @Test @WithoutJenkins - public void performFailureSuccessIssueOpen() throws Exception { + void performFailureSuccessIssueOpen() throws Exception { Long typeId = 1L; Long priorityId = 0L; Integer actionIdOnSuccess = 5; @@ -244,7 +235,7 @@ public void performFailureSuccessIssueOpen() throws Exception { @Test @WithoutJenkins - public void performFailureSuccessIssueClosedWithComponents() throws Exception { + void performFailureSuccessIssueClosedWithComponents() throws Exception { JiraCreateIssueNotifier notifier = spy(new JiraCreateIssueNotifier(JIRA_PROJECT, "", "", "", 1L, 1L, 1)); doReturn(site).when(notifier).getSiteForProject(Mockito.any()); @@ -282,7 +273,7 @@ public void performFailureSuccessIssueClosedWithComponents() throws Exception { @Test @WithoutJenkins - public void isDone() { + void isDone() { assertTrue(JiraCreateIssueNotifier.isDone(new Status(null, null, "Closed", null, null, null))); assertTrue(JiraCreateIssueNotifier.isDone(new Status(null, null, "Done", null, null, null))); assertTrue(JiraCreateIssueNotifier.isDone(new Status(null, null, "Resolved", null, null, null))); @@ -293,7 +284,7 @@ public void isDone() { } @Test - public void doFillPriorityIdItems() throws Exception { + void doFillPriorityIdItems(JenkinsRule j) throws Exception { String credId_1 = "cred-1-id"; String credId_2 = "cred-2-id"; @@ -365,7 +356,7 @@ public void doFillPriorityIdItems() throws Exception { } @Test - public void doFillTypeItems() throws Exception { + void doFillTypeItems(JenkinsRule j) throws Exception { String credId_1 = "cred-1-id"; String credId_2 = "cred-2-id"; @@ -435,4 +426,13 @@ public void doFillTypeItems() throws Exception { assertTrue(options.get(1).name.contains("https://pale-ale.com.au")); } } + + private static File newFolder(File root, String... subDirs) throws IOException { + String subFolder = String.join("/", subDirs); + File result = new File(root, subFolder); + if (!result.mkdirs()) { + throw new IOException("Couldn't create folders " + root); + } + return result; + } } diff --git a/src/test/java/hudson/plugins/jira/JiraCreateReleaseNotesTest.java b/src/test/java/hudson/plugins/jira/JiraCreateReleaseNotesTest.java index 7c9518a26..4296461c2 100644 --- a/src/test/java/hudson/plugins/jira/JiraCreateReleaseNotesTest.java +++ b/src/test/java/hudson/plugins/jira/JiraCreateReleaseNotesTest.java @@ -1,8 +1,8 @@ package hudson.plugins.jira; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.Mockito.doReturn; @@ -29,15 +29,15 @@ import java.util.Map; import java.util.concurrent.TimeoutException; import org.hamcrest.Matchers; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; -@RunWith(MockitoJUnitRunner.class) -public class JiraCreateReleaseNotesTest { +@ExtendWith(MockitoExtension.class) +class JiraCreateReleaseNotesTest { private static final String JIRA_RELEASE = Long.toString(System.currentTimeMillis()); private static final String JIRA_PRJ = "TEST_PRJ"; @@ -46,16 +46,16 @@ public class JiraCreateReleaseNotesTest { private static final String JIRA_VARIABLE = "ReleaseNotes"; private static final String JIRA_OTHER_FILTER = "status in (Resolved, Done, Closed)"; - @Mock + @Mock(strictness = Mock.Strictness.LENIENT) AbstractBuild build; @Mock Launcher launcher; - @Mock + @Mock(strictness = Mock.Strictness.LENIENT) BuildListener buildListener; - @Mock + @Mock(strictness = Mock.Strictness.LENIENT) EnvVars env; @Mock @@ -72,8 +72,8 @@ public class JiraCreateReleaseNotesTest { @Mock Item mockItem; - @Before - public void createCommonMocks() throws IOException, InterruptedException { + @BeforeEach + void createCommonMocks() throws IOException, InterruptedException { when(build.getEnvironment(buildListener)).thenReturn(env); when(buildListener.fatalError(Mockito.anyString(), Mockito.any(Object[].class))) .thenReturn(printWriter); @@ -96,14 +96,14 @@ public void createCommonMocks() throws IOException, InterruptedException { } @Test - public void defaults() { + void defaults() { JiraCreateReleaseNotes jcrn = new JiraCreateReleaseNotes(JIRA_PRJ, JIRA_RELEASE, ""); assertEquals(JiraCreateReleaseNotes.DEFAULT_ENVVAR_NAME, jcrn.getJiraEnvironmentVariable()); assertEquals(JiraCreateReleaseNotes.DEFAULT_FILTER, jcrn.getJiraFilter()); } @Test - public void jiraApiCallDefaultFilter() throws InterruptedException, IOException, TimeoutException { + void jiraApiCallDefaultFilter() throws InterruptedException, IOException, TimeoutException { JiraCreateReleaseNotes jcrn = spy(new JiraCreateReleaseNotes(JIRA_PRJ, JIRA_RELEASE, JIRA_VARIABLE)); doReturn(site).when(jcrn).getSiteForProject(Mockito.any()); jcrn.setUp(build, launcher, buildListener); @@ -111,7 +111,7 @@ public void jiraApiCallDefaultFilter() throws InterruptedException, IOException, } @Test - public void jiraApiCallOtherFilter() throws InterruptedException, IOException, TimeoutException { + void jiraApiCallOtherFilter() throws InterruptedException, IOException, TimeoutException { JiraCreateReleaseNotes jcrn = spy(new JiraCreateReleaseNotes(JIRA_PRJ, JIRA_RELEASE, JIRA_VARIABLE, JIRA_OTHER_FILTER)); doReturn(site).when(jcrn).getSiteForProject(Mockito.any()); @@ -123,7 +123,7 @@ public void jiraApiCallOtherFilter() throws InterruptedException, IOException, T } @Test - public void failBuildOnErrorEmptyProjectKey() throws InterruptedException, IOException { + void failBuildOnErrorEmptyProjectKey() throws InterruptedException, IOException { JiraCreateReleaseNotes jcrn = spy(new JiraCreateReleaseNotes("", JIRA_RELEASE, JIRA_VARIABLE, JIRA_OTHER_FILTER)); doReturn(site).when(jcrn).getSiteForProject(Mockito.any()); @@ -134,7 +134,7 @@ public void failBuildOnErrorEmptyProjectKey() throws InterruptedException, IOExc } @Test - public void failBuildOnErrorEmptyRelease() throws InterruptedException, IOException { + void failBuildOnErrorEmptyRelease() throws InterruptedException, IOException { JiraCreateReleaseNotes jcrn = spy(new JiraCreateReleaseNotes(JIRA_PRJ, "", JIRA_VARIABLE, JIRA_OTHER_FILTER)); doReturn(site).when(jcrn).getSiteForProject(Mockito.any()); BuildListenerResultMethodMock finishedListener = new BuildListenerResultMethodMock(); @@ -144,7 +144,7 @@ public void failBuildOnErrorEmptyRelease() throws InterruptedException, IOExcept } @Test - public void releaseNotesContent() throws Exception { + void releaseNotesContent() throws Exception { JiraCreateReleaseNotes jcrn = spy(new JiraCreateReleaseNotes(JIRA_PRJ, JIRA_RELEASE, JIRA_VARIABLE)); doReturn(site).when(jcrn).getSiteForProject(Mockito.any()); when(site.getReleaseNotesForFixVersion(JIRA_PRJ, JIRA_RELEASE, JiraCreateReleaseNotes.DEFAULT_FILTER)) diff --git a/src/test/java/hudson/plugins/jira/JiraEnvironmentContributingActionTest.java b/src/test/java/hudson/plugins/jira/JiraEnvironmentContributingActionTest.java index fe6faade2..74e59c5bb 100644 --- a/src/test/java/hudson/plugins/jira/JiraEnvironmentContributingActionTest.java +++ b/src/test/java/hudson/plugins/jira/JiraEnvironmentContributingActionTest.java @@ -8,17 +8,17 @@ import hudson.EnvVars; import hudson.model.AbstractBuild; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; -public class JiraEnvironmentContributingActionTest { +class JiraEnvironmentContributingActionTest { private static final String JIRA_URL = "http://example.com"; private static final String JIRA_URL_PROPERTY_NAME = "JIRA_URL"; private static final String ISSUES_PROPERTY_NAME = "JIRA_ISSUES"; private static final String ISSUES_LIST = "ISS-1,ISS-2"; @Test - public void buildEnvVarsEnvIsNull() { + void buildEnvVarsEnvIsNull() { JiraEnvironmentContributingAction action = new JiraEnvironmentContributingAction(ISSUES_LIST, JIRA_URL); AbstractBuild build = mock(AbstractBuild.class); @@ -27,7 +27,7 @@ public void buildEnvVarsEnvIsNull() { } @Test - public void buildEnvVarsAddVariables() { + void buildEnvVarsAddVariables() { JiraEnvironmentContributingAction action = new JiraEnvironmentContributingAction(ISSUES_LIST, JIRA_URL); AbstractBuild build = mock(AbstractBuild.class); EnvVars envVars = mock(EnvVars.class); diff --git a/src/test/java/hudson/plugins/jira/JiraEnvironmentVariableBuilderTest.java b/src/test/java/hudson/plugins/jira/JiraEnvironmentVariableBuilderTest.java index 8670ecee0..3869302b3 100644 --- a/src/test/java/hudson/plugins/jira/JiraEnvironmentVariableBuilderTest.java +++ b/src/test/java/hudson/plugins/jira/JiraEnvironmentVariableBuilderTest.java @@ -4,6 +4,7 @@ import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; @@ -24,12 +25,12 @@ import java.io.PrintStream; import java.util.Arrays; import java.util.LinkedHashSet; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; -public class JiraEnvironmentVariableBuilderTest { +class JiraEnvironmentVariableBuilderTest { private static final String JIRA_URL = "http://example.com"; private static final String JIRA_URL_PROPERTY_NAME = "JIRA_URL"; @@ -52,8 +53,8 @@ public class JiraEnvironmentVariableBuilderTest { PrintStream logger; Node node; - @Before - public void createMocks() throws IOException, InterruptedException { + @BeforeEach + void createMocks() throws IOException, InterruptedException { build = mock(AbstractBuild.class); launcher = mock(Launcher.class); listener = mock(BuildListener.class); @@ -75,26 +76,26 @@ public void createMocks() throws IOException, InterruptedException { } @Test - public void issueSelectorDefaultsToDefault() { + void issueSelectorDefaultsToDefault() { final JiraEnvironmentVariableBuilder builder = new JiraEnvironmentVariableBuilder(null); assertThat(builder.getIssueSelector(), instanceOf(DefaultIssueSelector.class)); } @Test - public void setIssueSelectorPersists() { + void setIssueSelectorPersists() { final JiraEnvironmentVariableBuilder builder = new JiraEnvironmentVariableBuilder(issueSelector); assertThat(builder.getIssueSelector(), is(issueSelector)); } - @Test(expected = AbortException.class) - public void performWithNoSiteFailsBuild() throws InterruptedException, IOException { + @Test + void performWithNoSiteFailsBuild() { JiraEnvironmentVariableBuilder builder = spy(new JiraEnvironmentVariableBuilder(issueSelector)); doReturn(null).when(builder).getSiteForProject(Mockito.any()); - builder.perform(build, launcher, listener); + assertThrows(AbortException.class, () -> builder.perform(build, launcher, listener)); } @Test - public void performAddsAction() throws InterruptedException, IOException { + void performAddsAction() throws InterruptedException, IOException { JiraEnvironmentVariableBuilder builder = spy(new JiraEnvironmentVariableBuilder(issueSelector)); doReturn(site).when(builder).getSiteForProject(Mockito.any()); diff --git a/src/test/java/hudson/plugins/jira/JiraFolderPropertyTest.java b/src/test/java/hudson/plugins/jira/JiraFolderPropertyTest.java index 14bc0b0e2..1b9912313 100644 --- a/src/test/java/hudson/plugins/jira/JiraFolderPropertyTest.java +++ b/src/test/java/hudson/plugins/jira/JiraFolderPropertyTest.java @@ -1,7 +1,7 @@ package hudson.plugins.jira; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import com.cloudbees.hudson.plugins.folder.Folder; import com.cloudbees.hudson.plugins.folder.properties.FolderCredentialsProvider; @@ -11,16 +11,15 @@ import java.util.Arrays; import java.util.List; import java.util.stream.StreamSupport; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; +@WithJenkins public class JiraFolderPropertyTest { - @Rule - public final JenkinsRule r = new JenkinsRule(); @Test - public void configRoundtrip() throws Exception { + void configRoundtrip(JenkinsRule r) throws Exception { Folder d = r.jenkins.createProject(Folder.class, "d"); r.configRoundtrip(d); assertNull(d.getProperties().get(JiraFolderProperty.class)); diff --git a/src/test/java/hudson/plugins/jira/JiraGlobalConfigurationSaveTest.java b/src/test/java/hudson/plugins/jira/JiraGlobalConfigurationSaveTest.java index 4386c459d..74f85c2ef 100644 --- a/src/test/java/hudson/plugins/jira/JiraGlobalConfigurationSaveTest.java +++ b/src/test/java/hudson/plugins/jira/JiraGlobalConfigurationSaveTest.java @@ -8,38 +8,35 @@ import java.net.URL; import java.util.Collections; import java.util.List; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.Issue; -import org.jvnet.hudson.test.RestartableJenkinsRule; +import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; -public class JiraGlobalConfigurationSaveTest { - - @Rule - public final RestartableJenkinsRule r = new RestartableJenkinsRule(); +@WithJenkins +class JiraGlobalConfigurationSaveTest { @Test @Issue("JENKINS-57899") - public void jiraSitesListSaved() throws Exception { + void jiraSitesListSaved(JenkinsRule r) throws Throwable { String jiraUrl = "https://issues.jenkins.io/"; - r.then(r -> { - JiraGlobalConfiguration jiraGlobalConfiguration = JiraGlobalConfiguration.get(); - jiraGlobalConfiguration.setSites(Collections.singletonList(new JiraSite(jiraUrl))); - List sites = jiraGlobalConfiguration.getSites(); - assertThat(sites, is(hasSize(1))); - JiraSite jiraSite = sites.get(0); - URL url = jiraSite.getUrl(); - assertThat(url, is(notNullValue())); - assertThat(url.toString(), is(jiraUrl)); - }); - r.then(r -> { - JiraGlobalConfiguration jiraGlobalConfiguration = JiraGlobalConfiguration.get(); - List sites = jiraGlobalConfiguration.getSites(); - assertThat(sites, is(hasSize(1))); - JiraSite jiraSite = sites.get(0); - URL url = jiraSite.getUrl(); - assertThat(url, is(notNullValue())); - assertThat(url.toString(), is(jiraUrl)); - }); + JiraGlobalConfiguration jiraGlobalConfiguration = JiraGlobalConfiguration.get(); + jiraGlobalConfiguration.setSites(Collections.singletonList(new JiraSite(jiraUrl))); + List sites = jiraGlobalConfiguration.getSites(); + assertThat(sites, is(hasSize(1))); + JiraSite jiraSite = sites.get(0); + URL url = jiraSite.getUrl(); + assertThat(url, is(notNullValue())); + assertThat(url.toString(), is(jiraUrl)); + + r.restart(); + + jiraGlobalConfiguration = JiraGlobalConfiguration.get(); + sites = jiraGlobalConfiguration.getSites(); + assertThat(sites, is(hasSize(1))); + jiraSite = sites.get(0); + url = jiraSite.getUrl(); + assertThat(url, is(notNullValue())); + assertThat(url.toString(), is(jiraUrl)); } } diff --git a/src/test/java/hudson/plugins/jira/JiraGlobalConfigurationTest.java b/src/test/java/hudson/plugins/jira/JiraGlobalConfigurationTest.java index 3a607208d..57a5a327a 100644 --- a/src/test/java/hudson/plugins/jira/JiraGlobalConfigurationTest.java +++ b/src/test/java/hudson/plugins/jira/JiraGlobalConfigurationTest.java @@ -1,24 +1,20 @@ package hudson.plugins.jira; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.*; import com.thoughtworks.xstream.XStream; import hudson.plugins.jira.JiraProjectProperty.DescriptorImpl; import hudson.util.XStream2; import java.io.InputStream; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; -public class JiraGlobalConfigurationTest { - - @Rule - public final JenkinsRule r = new JenkinsRule(); +@WithJenkins +class JiraGlobalConfigurationTest { @Test - public void migrateOldConfiguration() throws Exception { + void migrateOldConfiguration(JenkinsRule r) throws Exception { String url = "https://backwardsCompatURL.com/"; XStream xstream = new XStream2(); JiraSite expected = new JiraSite(url); diff --git a/src/test/java/hudson/plugins/jira/JiraIssueMigratorTest.java b/src/test/java/hudson/plugins/jira/JiraIssueMigratorTest.java index 9ffda79af..fc10b1399 100644 --- a/src/test/java/hudson/plugins/jira/JiraIssueMigratorTest.java +++ b/src/test/java/hudson/plugins/jira/JiraIssueMigratorTest.java @@ -1,6 +1,6 @@ package hudson.plugins.jira; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.anyString; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; @@ -17,10 +17,10 @@ import hudson.model.BuildListener; import java.io.IOException; import java.util.concurrent.TimeoutException; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class JiraIssueMigratorTest { +class JiraIssueMigratorTest { private static final String PROJECT_KEY = "PROJECT"; private static final String RELEASE = "release"; @@ -34,8 +34,8 @@ public class JiraIssueMigratorTest { AbstractProject project; JiraIssueMigrator jiraIssueMigrator; - @Before - public void prepareMocks() throws IOException, TimeoutException, InterruptedException { + @BeforeEach + void prepareMocks() throws IOException, TimeoutException, InterruptedException { build = mock(AbstractBuild.class); launcher = mock(Launcher.class); listener = mock(BuildListener.class); @@ -53,7 +53,7 @@ public void prepareMocks() throws IOException, TimeoutException, InterruptedExce } @Test - public void addingVersion() throws IOException, TimeoutException { + void addingVersion() throws IOException, TimeoutException { boolean addRelease = true; jiraIssueMigrator = spy(new JiraIssueMigrator(PROJECT_KEY, RELEASE, QUERY, null, addRelease)); doReturn(jiraSite).when(jiraIssueMigrator).getJiraSiteForProject(project); @@ -65,7 +65,7 @@ public void addingVersion() throws IOException, TimeoutException { } @Test - public void migratingToVersion() throws IOException, TimeoutException { + void migratingToVersion() throws IOException, TimeoutException { jiraIssueMigrator = spy(new JiraIssueMigrator(PROJECT_KEY, RELEASE, QUERY, null, false)); doReturn(jiraSite).when(jiraIssueMigrator).getJiraSiteForProject(project); boolean result = jiraIssueMigrator.perform(build, launcher, listener); @@ -76,7 +76,7 @@ public void migratingToVersion() throws IOException, TimeoutException { } @Test - public void replacingVersion() throws IOException, TimeoutException { + void replacingVersion() throws IOException, TimeoutException { jiraIssueMigrator = spy(new JiraIssueMigrator(PROJECT_KEY, RELEASE, QUERY, RELEASE_TO_REPLACE, false)); doReturn(jiraSite).when(jiraIssueMigrator).getJiraSiteForProject(project); boolean result = jiraIssueMigrator.perform(build, launcher, listener); diff --git a/src/test/java/hudson/plugins/jira/JiraIssueParameterDefResultTest.java b/src/test/java/hudson/plugins/jira/JiraIssueParameterDefResultTest.java index 0789c7391..f13309b3e 100644 --- a/src/test/java/hudson/plugins/jira/JiraIssueParameterDefResultTest.java +++ b/src/test/java/hudson/plugins/jira/JiraIssueParameterDefResultTest.java @@ -8,15 +8,15 @@ import com.atlassian.jira.rest.client.api.domain.Issue; import com.atlassian.jira.rest.client.api.domain.IssueField; import hudson.plugins.jira.listissuesparameter.JiraIssueParameterDefinition; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class JiraIssueParameterDefResultTest { +class JiraIssueParameterDefResultTest { private Issue issueMock; - @Before - public void prepareMocks() { + @BeforeEach + void prepareMocks() { issueMock = mock(Issue.class); IssueField fieldMock1 = mock(IssueField.class); IssueField fieldMock2 = mock(IssueField.class); @@ -33,14 +33,14 @@ public void prepareMocks() { } @Test - public void testSummaryResult() { + void testSummaryResult() { JiraIssueParameterDefinition.Result result = new JiraIssueParameterDefinition.Result(issueMock, ""); assertThat("Summary", equalTo(result.summary)); } @Test - public void testAltSummaryResultCommaSep() { + void testAltSummaryResultCommaSep() { JiraIssueParameterDefinition.Result result = new JiraIssueParameterDefinition.Result(issueMock, "TestField1,TestField2"); @@ -48,7 +48,7 @@ public void testAltSummaryResultCommaSep() { } @Test - public void testAltSummaryResultCommaSpaceSep() { + void testAltSummaryResultCommaSpaceSep() { JiraIssueParameterDefinition.Result result = new JiraIssueParameterDefinition.Result(issueMock, "TestField1, TestField2"); @@ -56,7 +56,7 @@ public void testAltSummaryResultCommaSpaceSep() { } @Test - public void testAltSummaryResultMissingFieldIgnored() { + void testAltSummaryResultMissingFieldIgnored() { JiraIssueParameterDefinition.Result result = new JiraIssueParameterDefinition.Result(issueMock, "TestField1, TestField4"); @@ -64,7 +64,7 @@ public void testAltSummaryResultMissingFieldIgnored() { } @Test - public void testAltSummaryResultEmptyFieldIgnored() { + void testAltSummaryResultEmptyFieldIgnored() { JiraIssueParameterDefinition.Result result = new JiraIssueParameterDefinition.Result(issueMock, "TestField1, TestField3"); diff --git a/src/test/java/hudson/plugins/jira/JiraIssueUpdateBuilderTest.java b/src/test/java/hudson/plugins/jira/JiraIssueUpdateBuilderTest.java index e86a8bbaf..add3ac4b1 100644 --- a/src/test/java/hudson/plugins/jira/JiraIssueUpdateBuilderTest.java +++ b/src/test/java/hudson/plugins/jira/JiraIssueUpdateBuilderTest.java @@ -21,10 +21,10 @@ import java.io.IOException; import java.io.PrintStream; import java.util.concurrent.TimeoutException; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class JiraIssueUpdateBuilderTest { +class JiraIssueUpdateBuilderTest { private Launcher launcher; private FilePath workspace; @@ -37,8 +37,8 @@ public class JiraIssueUpdateBuilderTest { private Result result; private JiraSite site; - @Before - public void createMocks() throws IOException, InterruptedException { + @BeforeEach + void createMocks() throws IOException, InterruptedException { launcher = mock(Launcher.class); listener = mock(TaskListener.class); env = mock(EnvVars.class); @@ -63,7 +63,7 @@ public void createMocks() throws IOException, InterruptedException { } @Test - public void performNoSite() throws InterruptedException, IOException { + void performNoSite() throws InterruptedException, IOException { JiraIssueUpdateBuilder builder = spy(new JiraIssueUpdateBuilder(null, null, null)); doReturn(null).when(builder).getSiteForJob(any()); builder.perform(build, workspace, launcher, listener); @@ -71,7 +71,7 @@ public void performNoSite() throws InterruptedException, IOException { } @Test - public void performTimeout() throws InterruptedException, IOException, TimeoutException { + void performTimeout() throws InterruptedException, IOException, TimeoutException { JiraIssueUpdateBuilder builder = spy(new JiraIssueUpdateBuilder(null, null, null)); doReturn(site).when(builder).getSiteForJob(any()); doThrow(new TimeoutException()).when(site).progressMatchingIssues(any(), any(), any(), any()); @@ -80,7 +80,7 @@ public void performTimeout() throws InterruptedException, IOException, TimeoutEx } @Test - public void performProgressFails() throws InterruptedException, IOException, TimeoutException { + void performProgressFails() throws InterruptedException, IOException, TimeoutException { JiraIssueUpdateBuilder builder = spy(new JiraIssueUpdateBuilder(null, null, null)); doReturn(site).when(builder).getSiteForJob(any()); doReturn(false).when(site).progressMatchingIssues(anyString(), anyString(), anyString(), any()); @@ -89,7 +89,7 @@ public void performProgressFails() throws InterruptedException, IOException, Tim } @Test - public void performProgressOK() throws InterruptedException, IOException, TimeoutException { + void performProgressOK() throws InterruptedException, IOException, TimeoutException { JiraIssueUpdateBuilder builder = spy(new JiraIssueUpdateBuilder(null, null, null)); doReturn(site).when(builder).getSiteForJob(any()); doReturn(true).when(site).progressMatchingIssues(any(), any(), any(), any()); diff --git a/src/test/java/hudson/plugins/jira/JiraIssueUpdaterTest.java b/src/test/java/hudson/plugins/jira/JiraIssueUpdaterTest.java index cf9fecb40..16ea161fd 100644 --- a/src/test/java/hudson/plugins/jira/JiraIssueUpdaterTest.java +++ b/src/test/java/hudson/plugins/jira/JiraIssueUpdaterTest.java @@ -13,18 +13,18 @@ import java.util.Arrays; import java.util.List; import java.util.Set; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class JiraIssueUpdaterTest { +class JiraIssueUpdaterTest { @Test - public void issueSelectorDefaultsToDefault() { + void issueSelectorDefaultsToDefault() { final JiraIssueUpdater updater = new JiraIssueUpdater(null, null, null); assertThat(updater.getIssueSelector(), instanceOf(DefaultIssueSelector.class)); } @Test - public void setIssueSelectorPersists() { + void setIssueSelectorPersists() { class TestSelector extends AbstractIssueSelector { @Override @@ -38,7 +38,7 @@ public Set findIssueIds(Run run, JiraSite site, TaskListener liste } @Test - public void setScmPersists() { + void setScmPersists() { class TestSCM extends SCM { @Override @@ -52,7 +52,7 @@ public ChangeLogParser createChangeLogParser() { } @Test - public void setLabelsPersists() { + void setLabelsPersists() { List testLabels = Arrays.asList("testLabel1", "testLabel2"); final JiraIssueUpdater updater = new JiraIssueUpdater(null, null, testLabels); diff --git a/src/test/java/hudson/plugins/jira/JiraJobActionTest.java b/src/test/java/hudson/plugins/jira/JiraJobActionTest.java index e5c195b2d..005a5c94d 100644 --- a/src/test/java/hudson/plugins/jira/JiraJobActionTest.java +++ b/src/test/java/hudson/plugins/jira/JiraJobActionTest.java @@ -1,20 +1,19 @@ package hudson.plugins.jira; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.spy; import hudson.plugins.jira.model.JiraIssue; import org.jenkinsci.plugins.workflow.job.WorkflowJob; import org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; -public class JiraJobActionTest { +@WithJenkins +class JiraJobActionTest { JiraSite site; @@ -22,13 +21,10 @@ public class JiraJobActionTest { WorkflowMultiBranchProject mbp; - @Rule - public JenkinsRule r = new JenkinsRule(); - final JiraIssue issue = new JiraIssue("EXAMPLE-123", "I like cake"); - @Before - public void setup() throws Exception { + @BeforeEach + void setup(JenkinsRule r) throws Exception { mbp = r.jenkins.createProject(WorkflowMultiBranchProject.class, "mbp"); site = spy(new JiraSite("https://foo.com")); @@ -37,7 +33,7 @@ public void setup() throws Exception { } @Test - public void detectBranchNameIssue() throws Exception { + void detectBranchNameIssue() throws Exception { job = new WorkflowJob(mbp, "feature/EXAMPLE-123"); JiraJobAction.setAction(job, site); @@ -48,7 +44,7 @@ public void detectBranchNameIssue() throws Exception { } @Test - public void detectBranchNameIssueWithEncodedJobName() throws Exception { + void detectBranchNameIssueWithEncodedJobName() throws Exception { job = new WorkflowJob(mbp, "feature%2FEXAMPLE-123"); JiraJobAction.setAction(job, site); @@ -60,7 +56,7 @@ public void detectBranchNameIssueWithEncodedJobName() throws Exception { } @Test - public void detectBranchNameIssueJustIssueKey() throws Exception { + void detectBranchNameIssueJustIssueKey() throws Exception { job = new WorkflowJob(mbp, "EXAMPLE-123"); JiraJobAction.setAction(job, site); @@ -72,7 +68,7 @@ public void detectBranchNameIssueJustIssueKey() throws Exception { } @Test - public void detectBranchNameIssueNoIssueKey() throws Exception { + void detectBranchNameIssueNoIssueKey() throws Exception { job = new WorkflowJob(mbp, "NOTHING INTERESTING"); JiraJobAction.setAction(job, site); JiraJobAction action = job.getAction(JiraJobAction.class); diff --git a/src/test/java/hudson/plugins/jira/JiraProjectPropertyTest.java b/src/test/java/hudson/plugins/jira/JiraProjectPropertyTest.java index 155c97882..15a88b482 100644 --- a/src/test/java/hudson/plugins/jira/JiraProjectPropertyTest.java +++ b/src/test/java/hudson/plugins/jira/JiraProjectPropertyTest.java @@ -1,31 +1,30 @@ package hudson.plugins.jira; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.*; import com.cloudbees.hudson.plugins.folder.Folder; import hudson.model.FreeStyleProject; import io.jenkins.plugins.casc.misc.ConfiguredWithCode; import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithCodeRule; +import io.jenkins.plugins.casc.misc.junit.jupiter.WithJenkinsConfiguredWithCode; import java.util.ArrayList; import java.util.List; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; -public class JiraProjectPropertyTest { +@WithJenkinsConfiguredWithCode +class JiraProjectPropertyTest { - @Rule - public final JenkinsRule r = new JenkinsConfiguredWithCodeRule(); + private JenkinsRule r; private FreeStyleProject freeStyleProject; private Folder folder; private List firstList; - @Before - public void initialize() throws Exception { + @BeforeEach + void initialize(JenkinsConfiguredWithCodeRule r) throws Exception { + this.r = r; folder = r.jenkins.createProject(Folder.class, "first"); JiraFolderProperty jiraFolderProperty = new JiraFolderProperty(); firstList = new ArrayList<>(); @@ -35,7 +34,7 @@ public void initialize() throws Exception { } @Test - public void getSitesNullWithoutFolder() throws Exception { + void getSitesNullWithoutFolder() throws Exception { FreeStyleProject freeStyleProject = r.createFreeStyleProject(); JiraProjectProperty prop = new JiraProjectProperty(null); freeStyleProject.addProperty(prop); @@ -45,7 +44,7 @@ public void getSitesNullWithoutFolder() throws Exception { } @Test - public void getSitesNullWithFolder() throws Exception { + void getSitesNullWithFolder() throws Exception { freeStyleProject = folder.createProject(FreeStyleProject.class, "something"); JiraProjectProperty prop = new JiraProjectProperty(null); freeStyleProject.addProperty(prop); @@ -56,7 +55,7 @@ public void getSitesNullWithFolder() throws Exception { @Test @ConfiguredWithCode("single-site.yml") - public void getSiteFromProjectProperty() { + void getSiteFromProjectProperty() { JiraProjectProperty prop = new JiraProjectProperty(null); JiraSite site = prop.getSite(); @SuppressWarnings("ConstantConditions") @@ -66,7 +65,7 @@ public void getSiteFromProjectProperty() { @Test @ConfiguredWithCode("single-site.yml") - public void getSiteFromSingleEntry() throws Exception { + void getSiteFromSingleEntry() throws Exception { freeStyleProject = r.createFreeStyleProject(); JiraSite expected = JiraGlobalConfiguration.get().getSites().get(0); JiraProjectProperty prop = new JiraProjectProperty(null); @@ -80,7 +79,7 @@ public void getSiteFromSingleEntry() throws Exception { @Test @ConfiguredWithCode("multiple-sites.yml") - public void getSiteFromFirstGlobalMultipleEntryMultipleSites() throws Exception { + void getSiteFromFirstGlobalMultipleEntryMultipleSites() throws Exception { freeStyleProject = r.createFreeStyleProject(); JiraSite expected = JiraGlobalConfiguration.get().getSites().get(0); JiraProjectProperty prop = new JiraProjectProperty(null); @@ -94,7 +93,7 @@ public void getSiteFromFirstGlobalMultipleEntryMultipleSites() throws Exception @Test @ConfiguredWithCode("multiple-sites.yml") - public void getSiteFromSecondGlobalEntryMultipleSites() throws Exception { + void getSiteFromSecondGlobalEntryMultipleSites() throws Exception { freeStyleProject = r.createFreeStyleProject(); JiraSite expected = new JiraSite("https://jira.com/"); JiraProjectProperty prop = new JiraProjectProperty(expected.getName()); @@ -108,7 +107,7 @@ public void getSiteFromSecondGlobalEntryMultipleSites() throws Exception { @Test @ConfiguredWithCode("single-site.yml") - public void getSiteFromFirstFolderLayer() throws Exception { + void getSiteFromFirstFolderLayer() throws Exception { freeStyleProject = folder.createProject(FreeStyleProject.class, "something"); JiraSite expected = firstList.get(0); JiraProjectProperty prop = new JiraProjectProperty(expected.getName()); @@ -122,7 +121,7 @@ public void getSiteFromFirstFolderLayer() throws Exception { @Test @ConfiguredWithCode("single-site.yml") - public void getSiteFromNestedFolderLayer() throws Exception { + void getSiteFromNestedFolderLayer() throws Exception { Folder secondFolder = folder.createProject(Folder.class, "second"); freeStyleProject = secondFolder.createProject(FreeStyleProject.class, "something"); // testing we can get value from folder above. diff --git a/src/test/java/hudson/plugins/jira/JiraReplaceFixVersionByRegExTest.java b/src/test/java/hudson/plugins/jira/JiraReplaceFixVersionByRegExTest.java index 27186478d..98f662003 100644 --- a/src/test/java/hudson/plugins/jira/JiraReplaceFixVersionByRegExTest.java +++ b/src/test/java/hudson/plugins/jira/JiraReplaceFixVersionByRegExTest.java @@ -17,15 +17,15 @@ import java.util.List; import java.util.concurrent.TimeoutException; import org.apache.commons.collections.CollectionUtils; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; -@RunWith(MockitoJUnitRunner.class) -public class JiraReplaceFixVersionByRegExTest { +@ExtendWith(MockitoExtension.class) +class JiraReplaceFixVersionByRegExTest { private static final String PROJECT_KEY = "myKey"; private static final String TO_VERSION = "toVersion"; @@ -39,13 +39,13 @@ public class JiraReplaceFixVersionByRegExTest { @Mock private JiraRestService service = null; - @Before - public void prepareMocks() throws IOException, InterruptedException { + @BeforeEach + void prepareMocks() throws IOException, InterruptedException { jiraSession = spy(new JiraSession(site, service)); } @Test - public void replaceWithFixVersionByRegex() throws URISyntaxException, TimeoutException { + void replaceWithFixVersionByRegex() throws URISyntaxException, TimeoutException { List myVersions = new ArrayList(); myVersions.add(new ExtendedVersion(new URI("self"), 0L, TO_VERSION, null, false, false, null, null)); diff --git a/src/test/java/hudson/plugins/jira/JiraRestServiceProxyTest.java b/src/test/java/hudson/plugins/jira/JiraRestServiceProxyTest.java index 5adafdd6a..6293bdba7 100644 --- a/src/test/java/hudson/plugins/jira/JiraRestServiceProxyTest.java +++ b/src/test/java/hudson/plugins/jira/JiraRestServiceProxyTest.java @@ -1,8 +1,6 @@ package hudson.plugins.jira; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.*; import hudson.ProxyConfiguration; import hudson.plugins.jira.extension.ExtendedJiraRestClient; @@ -17,43 +15,41 @@ import org.eclipse.jetty.server.HttpConnectionFactory; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; -public class JiraRestServiceProxyTest { +@WithJenkins +class JiraRestServiceProxyTest { private final ConnectionFactory connectionFactory = new HttpConnectionFactory(); private final URI JIRA_URI = URI.create("http://example.com:8080/"); private final String USERNAME = "user"; private final String PASSWORD = "password"; - @Rule - public JenkinsRule j = new JenkinsRule(); - private Server server; private ServerConnector connector; private ExtendedJiraRestClient client; - @Before - public void prepare() throws Exception { + @BeforeEach + void prepare() throws Exception { server = new Server(); connector = new ServerConnector(server, connectionFactory); server.addConnector(connector); server.start(); } - @After - public void dispose() throws Exception { + @AfterEach + void dispose() throws Exception { if (server != null) { server.stop(); } } @Test - public void withProxy() throws Exception { + void withProxy(JenkinsRule r) throws Exception { int localPort = connector.getLocalPort(); Jenkins.get().proxy = new ProxyConfiguration("localhost", localPort); @@ -67,7 +63,7 @@ public void withProxy() throws Exception { } @Test - public void withProxyAndNoProxyHosts() throws Exception { + void withProxyAndNoProxyHosts(JenkinsRule r) throws Exception { int localPort = connector.getLocalPort(); Jenkins.get().proxy = new ProxyConfiguration("localhost", localPort); Jenkins.get().proxy.setNoProxyHost("example.com|google.com"); @@ -76,7 +72,7 @@ public void withProxyAndNoProxyHosts() throws Exception { } @Test - public void withoutProxy() throws Exception { + void withoutProxy(JenkinsRule r) throws Exception { assertNull(getProxyObjectFromRequest()); } diff --git a/src/test/java/hudson/plugins/jira/JiraRestServiceTest.java b/src/test/java/hudson/plugins/jira/JiraRestServiceTest.java index dc88b6831..6cd1aa45c 100644 --- a/src/test/java/hudson/plugins/jira/JiraRestServiceTest.java +++ b/src/test/java/hudson/plugins/jira/JiraRestServiceTest.java @@ -1,6 +1,7 @@ package hudson.plugins.jira; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.any; import static org.mockito.Mockito.anyInt; import static org.mockito.Mockito.anyLong; @@ -16,11 +17,11 @@ import java.net.URI; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeoutException; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; -public class JiraRestServiceTest { +class JiraRestServiceTest { private final URI JIRA_URI = URI.create("http://example.com:8080/"); private final String USERNAME = "user"; @@ -30,8 +31,8 @@ public class JiraRestServiceTest { private Promise promise; private SearchResult searchResult; - @Before - public void createMocks() throws InterruptedException, ExecutionException, TimeoutException { + @BeforeEach + void createMocks() throws InterruptedException, ExecutionException, TimeoutException { client = mock(ExtendedJiraRestClient.class); searchRestClient = mock(SearchRestClient.class); promise = mock(Promise.class); @@ -43,7 +44,7 @@ public void createMocks() throws InterruptedException, ExecutionException, Timeo } @Test - public void baseApiPath() { + void baseApiPath() { JiraRestService service = new JiraRestService(JIRA_URI, client, USERNAME, PASSWORD, JiraSite.DEFAULT_TIMEOUT); assertEquals("/" + JiraRestService.BASE_API_PATH, service.getBaseApiPath()); @@ -52,11 +53,11 @@ public void baseApiPath() { assertEquals("/path/to/jira/" + JiraRestService.BASE_API_PATH, service.getBaseApiPath()); } - @Test(expected = TimeoutException.class) - public void getIssuesFromJqlSearchTimeout() throws TimeoutException, InterruptedException, ExecutionException { + @Test + void getIssuesFromJqlSearchTimeout() throws InterruptedException, ExecutionException, TimeoutException { JiraRestService service = spy(new JiraRestService(JIRA_URI, client, USERNAME, PASSWORD, JiraSite.DEFAULT_TIMEOUT)); doThrow(new TimeoutException()).when(promise).get(Mockito.anyLong(), Mockito.any()); - service.getIssuesFromJqlSearch("*", null); + assertThrows(TimeoutException.class, () -> service.getIssuesFromJqlSearch("*", null)); } } diff --git a/src/test/java/hudson/plugins/jira/JiraSiteSecurity1029Test.java b/src/test/java/hudson/plugins/jira/JiraSiteSecurity1029Test.java index 8aff6474e..d1aaaa4a0 100644 --- a/src/test/java/hudson/plugins/jira/JiraSiteSecurity1029Test.java +++ b/src/test/java/hudson/plugins/jira/JiraSiteSecurity1029Test.java @@ -36,30 +36,24 @@ import org.htmlunit.WebRequest; import org.htmlunit.WebResponse; import org.htmlunit.util.NameValuePair; -import org.junit.After; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.MockAuthorizationStrategy; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; +@WithJenkins public class JiraSiteSecurity1029Test { - @Rule - public JenkinsRule j = new JenkinsRule(); - - { - j.timeout = 0; - } - private Server server; private URI serverUri; private FakeJiraServlet servlet; @Test @Issue("SECURITY-1029") - public void cannotLeakCredentials() throws Exception { - setupServer(); + void cannotLeakCredentials(JenkinsRule j) throws Exception { + setupServer(j); final String ADMIN = "admin"; final String USER = "user"; @@ -245,7 +239,7 @@ public void cannotLeakCredentials() throws Exception { } } - public void setupServer() throws Exception { + public void setupServer(JenkinsRule j) throws Exception { server = new Server(); ServerConnector connector = new ServerConnector(server); // auto-bind to available port @@ -271,8 +265,8 @@ public void setupServer() throws Exception { servlet.setServerUrl(serverUri); } - @After - public void stopEmbeddedJettyServer() { + @AfterEach + void stopEmbeddedJettyServer() { try { server.stop(); } catch (Exception e) { diff --git a/src/test/java/hudson/plugins/jira/JiraSiteTest.java b/src/test/java/hudson/plugins/jira/JiraSiteTest.java index fd5bdc99b..65c3272d8 100644 --- a/src/test/java/hudson/plugins/jira/JiraSiteTest.java +++ b/src/test/java/hudson/plugins/jira/JiraSiteTest.java @@ -4,10 +4,7 @@ import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; @@ -37,33 +34,31 @@ import java.util.Arrays; import java.util.Collections; import jenkins.model.Jenkins; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.WithoutJenkins; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; -public class JiraSiteTest { +@WithJenkins +class JiraSiteTest { private static final String ANY_USER = "Kohsuke"; private static final String ANY_PASSWORD = "Kawaguchi"; - @Rule - public JenkinsRule j = new JenkinsRule(); - private URL validPrimaryUrl; private URL exampleOrg; - @Before - public void init() throws MalformedURLException { + @BeforeEach + void init() throws MalformedURLException { validPrimaryUrl = new URL("https://nonexistent.url"); exampleOrg = new URL("https://example.org/"); } @Test - public void createSessionWithProvidedCredentials() throws FormException { + void createSessionWithProvidedCredentials(JenkinsRule r) throws FormException { JiraSite site = new JiraSite( validPrimaryUrl, null, @@ -83,7 +78,7 @@ public void createSessionWithProvidedCredentials() throws FormException { @Test @Issue("JENKINS-64083") - public void createSessionWithGlobalCredentials() throws FormException { + void createSessionWithGlobalCredentials(JenkinsRule r) throws FormException { JiraSite site = new JiraSite( validPrimaryUrl, null, @@ -102,7 +97,7 @@ public void createSessionWithGlobalCredentials() throws FormException { } @Test - public void createSessionReturnsNullIfCredentialsIsNull() throws FormException { + void createSessionReturnsNullIfCredentialsIsNull(JenkinsRule r) throws FormException { JiraSite site = new JiraSite( validPrimaryUrl, null, @@ -121,7 +116,7 @@ public void createSessionReturnsNullIfCredentialsIsNull() throws FormException { } @Test - public void deserializeMigrateCredentials() throws MalformedURLException, FormException { + void deserializeMigrateCredentials(JenkinsRule j) throws MalformedURLException, FormException { JiraSiteOld old = new JiraSiteOld( validPrimaryUrl, null, ANY_USER, ANY_PASSWORD, false, false, null, false, null, null, true); @@ -154,7 +149,7 @@ public void deserializeMigrateCredentials() throws MalformedURLException, FormEx } @Test - public void deserializeNormal() throws IOException, FormException { + void deserializeNormal(JenkinsRule j) throws IOException, FormException { Domain domain = new Domain( "example", "test domain", @@ -180,7 +175,7 @@ public void deserializeNormal() throws IOException, FormException { @WithoutJenkins @Test - public void deserializeWithoutCredentials() { + void deserializeWithoutCredentials() { JiraSite site = new JiraSite(exampleOrg, null, (String) null, false, false, null, false, null, null, true); XStream2 xStream2 = new XStream2(); @@ -230,7 +225,7 @@ private static class JiraSiteOld extends JiraSite { @Test @WithoutJenkins - public void alternativeURLNotNull() throws FormException { + void alternativeURLNotNull() throws FormException { JiraSite site = new JiraSite( validPrimaryUrl, exampleOrg, @@ -248,7 +243,7 @@ public void alternativeURLNotNull() throws FormException { @Test @WithoutJenkins - public void ensureUrlEndsWithSlash() { + void ensureUrlEndsWithSlash() { JiraSite jiraSite = new JiraSite(validPrimaryUrl.toExternalForm()); jiraSite.setAlternativeUrl(exampleOrg.toExternalForm()); assertTrue(jiraSite.getUrl().toExternalForm().endsWith("/")); @@ -261,7 +256,7 @@ public void ensureUrlEndsWithSlash() { @Test @WithoutJenkins - public void urlNulls() { + void urlNulls() { JiraSite jiraSite = new JiraSite(validPrimaryUrl.toExternalForm()); jiraSite.setAlternativeUrl(" "); assertNotNull(jiraSite.getUrl()); @@ -270,55 +265,59 @@ public void urlNulls() { @Test @WithoutJenkins - public void toUrlConvertsEmptyStringToNull() { + void toUrlConvertsEmptyStringToNull() { URL emptyString = JiraSite.toURL(""); assertNull(emptyString); } @Test @WithoutJenkins - public void toUrlConvertsOnlyWhitespaceToNull() { + void toUrlConvertsOnlyWhitespaceToNull() { URL whitespace = JiraSite.toURL(" "); assertNull(whitespace); } @WithoutJenkins - @Test(expected = AssertionError.class) - public void ensureMainUrlIsMandatory() { - new JiraSite(""); + @Test + void ensureMainUrlIsMandatory() { + assertThrows(AssertionError.class, () -> { + new JiraSite(""); + }); } @Test @WithoutJenkins - public void ensureAlternativeUrlIsNotMandatory() { + void ensureAlternativeUrlIsNotMandatory() { JiraSite jiraSite = new JiraSite(validPrimaryUrl.toExternalForm()); jiraSite.setAlternativeUrl(""); assertNull(jiraSite.getAlternativeUrl()); } @WithoutJenkins - @Test(expected = AssertionError.class) - public void malformedUrl() { - new JiraSite("malformed.url"); + @Test + void malformedUrl() { + assertThrows(AssertionError.class, () -> { + new JiraSite("malformed.url"); + }); } @WithoutJenkins - @Test(expected = AssertionError.class) - public void malformedAlternativeUrl() { + @Test + void malformedAlternativeUrl() { JiraSite jiraSite = new JiraSite(validPrimaryUrl.toExternalForm()); - jiraSite.setAlternativeUrl("malformed.url"); + assertThrows(AssertionError.class, () -> jiraSite.setAlternativeUrl("malformed.url")); } @Test @WithoutJenkins - public void credentialsAreNullByDefault() { + void credentialsAreNullByDefault() { JiraSite jiraSite = new JiraSite(exampleOrg.toExternalForm()); jiraSite.setCredentialsId(""); assertNull(jiraSite.getCredentialsId()); } @Test - public void credentials() throws Exception { + void credentials(JenkinsRule r) throws Exception { JiraSite jiraSite = new JiraSite(exampleOrg.toExternalForm()); String cred = "cred-1"; String user = "user1"; @@ -342,7 +341,7 @@ public void credentials() throws Exception { @Test @WithoutJenkins - public void siteAsProjectProperty() throws Exception { + void siteAsProjectProperty() throws Exception { JiraSite jiraSite = new JiraSite(new URL("https://foo.org/").toExternalForm()); Job job = mock(Job.class); JiraProjectProperty jpp = mock(JiraProjectProperty.class); @@ -353,7 +352,7 @@ public void siteAsProjectProperty() throws Exception { } @Test - public void projectPropertySiteAndParentBothNull() { + void projectPropertySiteAndParentBothNull(JenkinsRule j) { JiraGlobalConfiguration jiraGlobalConfiguration = mock(JiraGlobalConfiguration.class); Job job = mock(Job.class); JiraProjectProperty jpp = mock(JiraProjectProperty.class); @@ -367,18 +366,18 @@ public void projectPropertySiteAndParentBothNull() { } @Test - public void noProjectProperty() throws Exception { + void noProjectProperty(JenkinsRule j) throws Exception { JiraGlobalConfiguration.get().setSites(null); Job job = j.jenkins.createProject(FreeStyleProject.class, "foo"); assertNull(JiraSite.get(job)); } @Test - public void noProjectPropertyUpFoldersWithNoProperty() throws Exception { + void noProjectPropertyUpFoldersWithNoProperty(JenkinsRule j) throws Exception { JiraGlobalConfiguration jiraGlobalConfiguration = mock(JiraGlobalConfiguration.class); - Folder folder2 = spy(createFolder(null)); - Folder folder1 = spy(createFolder(folder2)); + Folder folder2 = spy(createFolder(j, null)); + Folder folder1 = spy(createFolder(j, folder2)); Job job = folder1.createProject(FreeStyleProject.class, "foo"); DescribableList, AbstractFolderPropertyDescriptor> folder1Properties = @@ -394,16 +393,16 @@ public void noProjectPropertyUpFoldersWithNoProperty() throws Exception { } @Test - public void noProjectPropertyFindFolderPropertyWithNullZeroLengthAndValidSites() throws Exception { + void noProjectPropertyFindFolderPropertyWithNullZeroLengthAndValidSites(JenkinsRule j) throws Exception { JiraSite jiraSite1 = new JiraSite(new URL("https://example1.org/").toExternalForm()); JiraSite jiraSite2 = new JiraSite(new URL("https://example2.org/").toExternalForm()); - Folder folder1 = spy(createFolder(null)); + Folder folder1 = spy(createFolder(j, null)); Job job = folder1.createProject(FreeStyleProject.class, "foo"); DescribableList, AbstractFolderPropertyDescriptor> folder1Properties = new DescribableList(Jenkins.get()); - Folder folder2 = spy(createFolder(folder1)); + Folder folder2 = spy(createFolder(j, folder1)); DescribableList, AbstractFolderPropertyDescriptor> folder2Properties = new DescribableList(Jenkins.get()); JiraFolderProperty jfp = new JiraFolderProperty(); @@ -417,7 +416,7 @@ public void noProjectPropertyFindFolderPropertyWithNullZeroLengthAndValidSites() } @Test - public void siteConfiguredGlobally() throws Exception { + void siteConfiguredGlobally(JenkinsRule j) throws Exception { JiraSite jiraSite = new JiraSite(new URL("https://foo.org/").toExternalForm()); JiraGlobalConfiguration.get().setSites(Collections.singletonList(jiraSite)); Job job = mock(Job.class); @@ -428,7 +427,7 @@ public void siteConfiguredGlobally() throws Exception { @Test @WithoutJenkins - public void getIssueWithoutSession() throws Exception { + void getIssueWithoutSession() throws Exception { JiraSite jiraSite = new JiraSite(new URL("https://foo.org/").toExternalForm()); // Verify that no session will be created assertNull(jiraSite.getSession(null)); @@ -436,7 +435,7 @@ public void getIssueWithoutSession() throws Exception { assertNull(issue); } - private Folder createFolder(Folder folder) throws IOException { + private Folder createFolder(JenkinsRule j, Folder folder) throws IOException { return folder == null ? j.jenkins.createProject( Folder.class, "folder" + j.jenkins.getItems().size()) diff --git a/src/test/java/hudson/plugins/jira/MailResolverDisabledTest.java b/src/test/java/hudson/plugins/jira/MailResolverDisabledTest.java index b93909bad..bd1b58d26 100644 --- a/src/test/java/hudson/plugins/jira/MailResolverDisabledTest.java +++ b/src/test/java/hudson/plugins/jira/MailResolverDisabledTest.java @@ -29,25 +29,24 @@ import hudson.model.User; import java.util.Collections; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; /** * @author schristou88 */ -public class MailResolverDisabledTest extends JenkinsRule { - @Rule - public JenkinsRule r = new JenkinsRule(); +@WithJenkins +class MailResolverDisabledTest { - @BeforeClass - public static void setUp() throws Exception { + @BeforeAll + static void setUp() throws Exception { System.setProperty("hudson.plugins.jira.JiraMailAddressResolver.disabled", "true"); } @Test - public void disableEmailResolver() { + void disableEmailResolver(JenkinsRule r) { User user = User.get("bob", true, Collections.emptyMap()); assertThat(JiraMailAddressResolver.resolve(user), is(nullValue())); } diff --git a/src/test/java/hudson/plugins/jira/MailResolverWithExtensionTest.java b/src/test/java/hudson/plugins/jira/MailResolverWithExtensionTest.java index 71aedbaec..2c0fba17f 100644 --- a/src/test/java/hudson/plugins/jira/MailResolverWithExtensionTest.java +++ b/src/test/java/hudson/plugins/jira/MailResolverWithExtensionTest.java @@ -37,23 +37,22 @@ import java.util.Map; import jenkins.model.Jenkins; import jenkins.security.SecurityListener; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.TestExtension; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.security.core.userdetails.UserDetails; -@RunWith(MockitoJUnitRunner.class) -public class MailResolverWithExtensionTest extends JenkinsRule { - @Rule - public JenkinsRule r = new JenkinsRule(); +@WithJenkins +@ExtendWith(MockitoExtension.class) +class MailResolverWithExtensionTest { - @Mock + @Mock(strictness = Mock.Strictness.LENIENT) JiraSite site; JiraSession session; @@ -61,8 +60,8 @@ public class MailResolverWithExtensionTest extends JenkinsRule { @Mock JiraRestService service; - @Before - public void createMocks() throws Exception { + @BeforeEach + void createMocks() throws Exception { session = new JiraSession(site, service); Mockito.when(site.getSession(any())).thenReturn(session); @@ -77,7 +76,7 @@ public void createMocks() throws Exception { } @Test - public void emailResolverWithSecurityExtension() throws Exception { + void emailResolverWithSecurityExtension(JenkinsRule r) throws Exception { HudsonPrivateSecurityRealm realm = new HudsonPrivateSecurityRealm(true); realm.createAccount("foo", "pacific_ale"); diff --git a/src/test/java/hudson/plugins/jira/UnmaskMailTest.java b/src/test/java/hudson/plugins/jira/UnmaskMailTest.java index d1788c531..64b707055 100644 --- a/src/test/java/hudson/plugins/jira/UnmaskMailTest.java +++ b/src/test/java/hudson/plugins/jira/UnmaskMailTest.java @@ -1,17 +1,18 @@ package hudson.plugins.jira; -import org.junit.Assert; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; /** * Test unmasking email. Eg: john dot doe at example dot com to john.doe@example.com * * @author Honza Brázdil */ -public class UnmaskMailTest { +class UnmaskMailTest { @Test - public void unmaskMailTest() { + void unmaskMailTest() { test("user@example.com", "user at example dot com"); test("user@example.com", "user AT example DOT com"); test("user@example.com", "user aT example dOt com"); @@ -44,6 +45,6 @@ public void unmaskMailTest() { } private void test(String expected, String masked) { - Assert.assertEquals(expected, JiraMailAddressResolver.unmaskEmail(masked)); + assertEquals(expected, JiraMailAddressResolver.unmaskEmail(masked)); } } diff --git a/src/test/java/hudson/plugins/jira/UpdaterTest.java b/src/test/java/hudson/plugins/jira/UpdaterTest.java index 3ff8f7778..5a1a8fa62 100644 --- a/src/test/java/hudson/plugins/jira/UpdaterTest.java +++ b/src/test/java/hudson/plugins/jira/UpdaterTest.java @@ -4,6 +4,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doAnswer; @@ -26,6 +27,7 @@ import hudson.scm.ChangeLogSet.Entry; import hudson.scm.EditType; import hudson.scm.SCM; +import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; @@ -40,13 +42,12 @@ import org.hamcrest.Matchers; import org.jenkinsci.plugins.workflow.job.WorkflowJob; import org.jenkinsci.plugins.workflow.job.WorkflowRun; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.WithoutJenkins; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.mockito.Mockito; import org.mockito.stubbing.Answer; @@ -56,11 +57,9 @@ * @author kutzi */ @SuppressWarnings("unchecked") +@WithJenkins public class UpdaterTest { - @Rule - public JenkinsRule rule = new JenkinsRule(); - private Updater updater; private static class MockEntry extends Entry { @@ -87,14 +86,14 @@ public String getMsg() { } } - @Before - public void prepare() { + @BeforeEach + void prepare() { SCM scm = mock(SCM.class); this.updater = new Updater(scm); } @Test - public void getScmCommentsFromPreviousBuilds() { + void getScmCommentsFromPreviousBuilds(JenkinsRule r) { final FreeStyleProject project = mock(FreeStyleProject.class); final FreeStyleBuild build1 = mock(FreeStyleBuild.class); final MockEntry entry1 = new MockEntry("FOOBAR-1: The first build"); @@ -149,7 +148,7 @@ public void getScmCommentsFromPreviousBuilds() { new HashSet(Arrays.asList(new JiraIssue("FOOBAR-1", null), new JiraIssue("FOOBAR-2", null))); updater.submitComments(build2, System.out, "http://jenkins", ids, session, false, false, "", ""); - Assert.assertEquals(2, comments.size()); + assertEquals(2, comments.size()); assertThat(comments.get(0).getBody(), Matchers.containsString(entry1.getMsg())); assertThat(comments.get(1).getBody(), Matchers.containsString(entry2.getMsg())); } @@ -160,7 +159,7 @@ public void getScmCommentsFromPreviousBuilds() { */ @Test @org.jvnet.hudson.test.Issue("4572") - public void comment() { + void comment(JenkinsRule r) { // mock Jira session: JiraSession session = mock(JiraSession.class); final Issue mockIssue = Mockito.mock(Issue.class); @@ -197,10 +196,10 @@ public void comment() { Updater updaterCurrent = new Updater(build.getParent().getScm()); updaterCurrent.submitComments(build, System.out, "http://jenkins", ids, session, false, false, "", ""); - Assert.assertEquals(1, comments.size()); + assertEquals(1, comments.size()); String comment = comments.get(0); - Assert.assertTrue(comment.contains("FOOBAR-4711")); + assertTrue(comment.contains("FOOBAR-4711")); // must also work case-insensitively (JENKINS-4132) comments.clear(); @@ -210,10 +209,10 @@ public void comment() { updaterCurrent.submitComments(build, System.out, "http://jenkins", ids, session, false, false, "", ""); - Assert.assertEquals(1, comments.size()); + assertEquals(1, comments.size()); comment = comments.get(0); - Assert.assertTrue(comment.contains("Foobar-4711")); + assertTrue(comment.contains("Foobar-4711")); } /** @@ -223,7 +222,7 @@ public void comment() { @Test @org.jvnet.hudson.test.Issue("17156") @WithoutJenkins - public void issueIsRemovedFromCarryOverListAfterSubmission() throws RestClientException { + void issueIsRemovedFromCarryOverListAfterSubmission() throws RestClientException { // mock build: FreeStyleBuild build = mock(FreeStyleBuild.class); FreeStyleProject project = mock(FreeStyleProject.class); @@ -287,8 +286,8 @@ public void issueIsRemovedFromCarryOverListAfterSubmission() throws RestClientEx assertThat(issues, is(expectedIssuesToCarryOver)); } - @Rule - public TemporaryFolder folder = new TemporaryFolder(); + @TempDir + public File folder; /** * Test that workflow job - run instance of type WorkflowJob - can @@ -297,10 +296,10 @@ public void issueIsRemovedFromCarryOverListAfterSubmission() throws RestClientEx */ @Test @WithoutJenkins - public void getChangesUsingReflectionForWorkflowJob() throws IOException { + void getChangesUsingReflectionForWorkflowJob() throws IOException { Jenkins jenkins = mock(Jenkins.class); - when(jenkins.getRootDirFor(Mockito.any())).thenReturn(folder.getRoot()); + when(jenkins.getRootDirFor(Mockito.any())).thenReturn(folder); WorkflowJob workflowJob = new WorkflowJob(jenkins, "job"); WorkflowRun workflowRun = new WorkflowRun(workflowJob); @@ -308,15 +307,15 @@ public void getChangesUsingReflectionForWorkflowJob() throws IOException { List> changesUsingReflection = RunScmChangeExtractor.getChangesUsingReflection(workflowRun); - Assert.assertNotNull(changesUsingReflection); - Assert.assertTrue(changesUsingReflection.isEmpty()); + assertNotNull(changesUsingReflection); + assertTrue(changesUsingReflection.isEmpty()); } @WithoutJenkins - @Test(expected = IllegalArgumentException.class) - public void getChangesUsingReflectionForunknownJob() { + @Test + void getChangesUsingReflectionForunknownJob() { Run run = mock(Run.class); - RunScmChangeExtractor.getChangesUsingReflection(run); + assertThrows(IllegalArgumentException.class, () -> RunScmChangeExtractor.getChangesUsingReflection(run)); } /** @@ -325,7 +324,7 @@ public void getChangesUsingReflectionForunknownJob() { */ @Test @WithoutJenkins - public void appendChangeTimestampToDescription() { + void appendChangeTimestampToDescription() { Updater updater = new Updater(null); StringBuilder description = new StringBuilder(); Calendar calendar = Calendar.getInstance(); @@ -342,7 +341,7 @@ public void appendChangeTimestampToDescription() { * */ @Test - public void dateTimeInChangeDescription() { + void dateTimeInChangeDescription(JenkinsRule rule) { rule.getInstance(); Updater updater = new Updater(null); Calendar calendar = Calendar.getInstance(); @@ -379,7 +378,7 @@ public void dateTimeInChangeDescription() { */ @Test @WithoutJenkins - public void appendChangeTimestampToDescriptionNullFormat() { + void appendChangeTimestampToDescriptionNullFormat() { // set default locale -> predictable test without explicit format Locale.setDefault(Locale.ENGLISH); @@ -404,7 +403,7 @@ public void appendChangeTimestampToDescriptionNullFormat() { */ @Test @WithoutJenkins - public void appendChangeTimestampToDescriptionNoFormat() { + void appendChangeTimestampToDescriptionNoFormat() { // set default locale -> predictable test without explicit format Locale.setDefault(Locale.ENGLISH); @@ -428,7 +427,7 @@ public void appendChangeTimestampToDescriptionNoFormat() { * */ @Test - public void tesDescriptionWithAffectedFiles() { + void tesDescriptionWithAffectedFiles(JenkinsRule rule) { rule.getInstance(); Updater updater = new Updater(null); Calendar calendar = Calendar.getInstance(); diff --git a/src/test/java/hudson/plugins/jira/VersionCreatorTest.java b/src/test/java/hudson/plugins/jira/VersionCreatorTest.java index 497f0cad7..10178a80d 100644 --- a/src/test/java/hudson/plugins/jira/VersionCreatorTest.java +++ b/src/test/java/hudson/plugins/jira/VersionCreatorTest.java @@ -18,18 +18,18 @@ import java.io.PrintStream; import java.util.Arrays; import org.joda.time.DateTime; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.stubbing.Answer; -@RunWith(MockitoJUnitRunner.class) -public class VersionCreatorTest { +@ExtendWith(MockitoExtension.class) +class VersionCreatorTest { private static final String JIRA_VER = Long.toString(System.currentTimeMillis()); private static final String JIRA_PRJ = "TEST_PRJ"; private static final String JIRA_VER_PARAM = "${JIRA_VER}"; @@ -68,8 +68,8 @@ public class VersionCreatorTest { private ExtendedVersion existingVersion = new ExtendedVersion(null, ANY_ID, JIRA_VER, null, false, false, ANY_DATE, ANY_DATE); - @Before - public void createMocks() { + @BeforeEach + void createMocks() { when(site.getSession(any())).thenReturn(session); when(env.expand(Mockito.anyString())).thenAnswer((Answer) invocationOnMock -> { Object[] args = invocationOnMock.getArguments(); @@ -87,7 +87,7 @@ public void createMocks() { } @Test - public void callsJiraWithSpecifiedParameters() throws InterruptedException, IOException { + void callsJiraWithSpecifiedParameters() throws InterruptedException, IOException { when(build.getEnvironment(listener)).thenReturn(env); when(site.getSession(any())).thenReturn(session); when(session.getVersions(JIRA_PRJ)).thenReturn(Arrays.asList(existingVersion)); @@ -99,7 +99,7 @@ public void callsJiraWithSpecifiedParameters() throws InterruptedException, IOEx } @Test - public void expandsEnvParameters() throws InterruptedException, IOException { + void expandsEnvParameters() throws InterruptedException, IOException { when(build.getEnvironment(listener)).thenReturn(env); when(site.getSession(any())).thenReturn(session); when(session.getVersions(JIRA_PRJ)).thenReturn(Arrays.asList(existingVersion)); @@ -111,7 +111,7 @@ public void expandsEnvParameters() throws InterruptedException, IOException { } @Test - public void buildDidNotFailWhenVersionExists() throws IOException, InterruptedException { + void buildDidNotFailWhenVersionExists() throws IOException, InterruptedException { when(build.getEnvironment(listener)).thenReturn(env); ExtendedVersion releasedVersion = new ExtendedVersion(null, ANY_ID, JIRA_VER, null, false, true, ANY_DATE, ANY_DATE); diff --git a/src/test/java/hudson/plugins/jira/VersionReleaserTest.java b/src/test/java/hudson/plugins/jira/VersionReleaserTest.java index 72d6ded4a..aab39999e 100644 --- a/src/test/java/hudson/plugins/jira/VersionReleaserTest.java +++ b/src/test/java/hudson/plugins/jira/VersionReleaserTest.java @@ -19,18 +19,18 @@ import java.util.Collections; import java.util.HashSet; import org.joda.time.DateTime; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.stubbing.Answer; -@RunWith(MockitoJUnitRunner.class) -public class VersionReleaserTest { +@ExtendWith(MockitoExtension.class) +class VersionReleaserTest { private static final String JIRA_VER = Long.toString(System.currentTimeMillis()); private static final String JIRA_PRJ = "TEST_PRJ"; private static final String JIRA_DES = "TEST_DES"; @@ -55,7 +55,7 @@ public class VersionReleaserTest { @Mock AbstractProject project; - @Mock + @Mock(strictness = Mock.Strictness.LENIENT) JiraSite site; @Mock @@ -71,8 +71,8 @@ public class VersionReleaserTest { private ExtendedVersion existingVersion = new ExtendedVersion(null, ANY_ID, JIRA_VER, JIRA_DES, false, false, ANY_DATE, ANY_DATE); - @Before - public void createMocks() throws Exception { + @BeforeEach + void createMocks() throws Exception { when(site.getSession(any())).thenReturn(session); when(build.getEnvironment(listener)).thenReturn(env); @@ -94,7 +94,7 @@ public void createMocks() throws Exception { } @Test - public void callsJiraWithSpecifiedParameters() { + void callsJiraWithSpecifiedParameters() { when(session.getVersions(JIRA_PRJ)).thenReturn(Collections.singletonList(existingVersion)); when(site.getVersions(JIRA_PRJ)).thenReturn(new HashSet<>(Arrays.asList(existingVersion))); when(site.getSession(any())).thenReturn(session); @@ -108,7 +108,7 @@ public void callsJiraWithSpecifiedParameters() { } @Test - public void expandsEnvParameters() { + void expandsEnvParameters() { when(session.getVersions(JIRA_PRJ)).thenReturn(Collections.singletonList(existingVersion)); when(site.getVersions(JIRA_PRJ)).thenReturn(new HashSet<>(Arrays.asList(existingVersion))); when(site.getSession(any())).thenReturn(session); @@ -122,7 +122,7 @@ public void expandsEnvParameters() { } @Test - public void buildDidNotFailWhenVersionExists() { + void buildDidNotFailWhenVersionExists() { ExtendedVersion releasedVersion = new ExtendedVersion(null, ANY_ID, JIRA_VER, JIRA_DES, false, true, ANY_DATE, ANY_DATE); when(site.getVersions(JIRA_PRJ)).thenReturn(new HashSet<>(Arrays.asList(releasedVersion))); diff --git a/src/test/java/hudson/plugins/jira/auth/BearerHttpAuthenticationHandlerTest.java b/src/test/java/hudson/plugins/jira/auth/BearerHttpAuthenticationHandlerTest.java index f3556d941..8941311da 100644 --- a/src/test/java/hudson/plugins/jira/auth/BearerHttpAuthenticationHandlerTest.java +++ b/src/test/java/hudson/plugins/jira/auth/BearerHttpAuthenticationHandlerTest.java @@ -4,12 +4,12 @@ import static org.mockito.Mockito.verify; import com.atlassian.httpclient.api.Request; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class BearerHttpAuthenticationHandlerTest { +class BearerHttpAuthenticationHandlerTest { @Test - public void testConfigure() { + void testConfigure() { String token = "token"; BearerHttpAuthenticationHandler handler = new BearerHttpAuthenticationHandler(token); Request.Builder builder = mock(Request.Builder.class); diff --git a/src/test/java/hudson/plugins/jira/auth/JiraRestServiceBearerAuthTest.java b/src/test/java/hudson/plugins/jira/auth/JiraRestServiceBearerAuthTest.java index 0ac9be5d3..4b8bbf3f3 100644 --- a/src/test/java/hudson/plugins/jira/auth/JiraRestServiceBearerAuthTest.java +++ b/src/test/java/hudson/plugins/jira/auth/JiraRestServiceBearerAuthTest.java @@ -1,6 +1,7 @@ package hudson.plugins.jira.auth; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.any; import static org.mockito.Mockito.anyInt; import static org.mockito.Mockito.anyLong; @@ -18,11 +19,11 @@ import java.net.URI; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeoutException; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; -public class JiraRestServiceBearerAuthTest { +class JiraRestServiceBearerAuthTest { private final URI JIRA_URI = URI.create("http://example.com:8080/"); private final String TOKEN = "token"; @@ -31,8 +32,8 @@ public class JiraRestServiceBearerAuthTest { private Promise promise; private SearchResult searchResult; - @Before - public void createMocks() throws InterruptedException, ExecutionException, TimeoutException { + @BeforeEach + void createMocks() throws InterruptedException, ExecutionException, TimeoutException { client = mock(ExtendedJiraRestClient.class); searchRestClient = mock(SearchRestClient.class); promise = mock(Promise.class); @@ -44,7 +45,7 @@ public void createMocks() throws InterruptedException, ExecutionException, Timeo } @Test - public void baseApiPath() { + void baseApiPath() { JiraRestService service = new JiraRestService(JIRA_URI, client, TOKEN, JiraSite.DEFAULT_TIMEOUT); assertEquals("/" + JiraRestService.BASE_API_PATH, service.getBaseApiPath()); @@ -53,10 +54,10 @@ public void baseApiPath() { assertEquals("/path/to/jira/" + JiraRestService.BASE_API_PATH, service.getBaseApiPath()); } - @Test(expected = TimeoutException.class) - public void getIssuesFromJqlSearchTimeout() throws TimeoutException, InterruptedException, ExecutionException { + @Test + void getIssuesFromJqlSearchTimeout() throws ExecutionException, InterruptedException, TimeoutException { JiraRestService service = spy(new JiraRestService(JIRA_URI, client, TOKEN, JiraSite.DEFAULT_TIMEOUT)); doThrow(new TimeoutException()).when(promise).get(Mockito.anyLong(), Mockito.any()); - service.getIssuesFromJqlSearch("*", null); + assertThrows(TimeoutException.class, () -> service.getIssuesFromJqlSearch("*", null)); } } diff --git a/src/test/java/hudson/plugins/jira/pipeline/CommentStepTest.java b/src/test/java/hudson/plugins/jira/pipeline/CommentStepTest.java index 7438d2677..bcd078058 100644 --- a/src/test/java/hudson/plugins/jira/pipeline/CommentStepTest.java +++ b/src/test/java/hudson/plugins/jira/pipeline/CommentStepTest.java @@ -3,7 +3,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.collection.IsCollectionWithSize.hasSize; import static org.hamcrest.core.IsEqual.equalTo; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -23,27 +23,28 @@ import java.util.Map; import org.jenkinsci.plugins.workflow.steps.StepConfigTester; import org.jenkinsci.plugins.workflow.steps.StepContext; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.mockito.Mockito; -public class CommentStepTest { +@WithJenkins +class CommentStepTest { - @ClassRule - public static JenkinsRule jenkinsRule = new JenkinsRule(); + private JenkinsRule jenkinsRule; @Inject CommentStep.DescriptorImpl descriptor; - @Before - public void setUp() { + @BeforeEach + void setUp(JenkinsRule jenkinsRule) { + this.jenkinsRule = jenkinsRule; jenkinsRule.getInstance().getInjector().injectMembers(this); } @Test - public void configRoundTrip() throws Exception { + void configRoundTrip() throws Exception { configRoundTrip("EXAMPLE-1", "comment"); } @@ -56,7 +57,7 @@ private void configRoundTrip(String issueKey, String body) throws Exception { } @Test - public void callSessionAddComment() throws Exception { + void callSessionAddComment() throws Exception { JiraSession session = mock(JiraSession.class); final String issueKey = "KEY"; final String body = "dsgsags"; diff --git a/src/test/java/hudson/plugins/jira/pipeline/IssueFieldUpdateStepTest.java b/src/test/java/hudson/plugins/jira/pipeline/IssueFieldUpdateStepTest.java index d5b5b24e6..d2c7c266c 100644 --- a/src/test/java/hudson/plugins/jira/pipeline/IssueFieldUpdateStepTest.java +++ b/src/test/java/hudson/plugins/jira/pipeline/IssueFieldUpdateStepTest.java @@ -2,8 +2,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; +import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.ArgumentMatchers.anyString; @@ -18,13 +17,13 @@ import hudson.model.AbstractProject; import hudson.model.BuildListener; import hudson.model.Job; -import hudson.model.Result; import hudson.plugins.jira.JiraGlobalConfiguration; import hudson.plugins.jira.JiraSession; import hudson.plugins.jira.JiraSite; import hudson.plugins.jira.model.JiraIssueField; import hudson.plugins.jira.selector.ExplicitIssueSelector; import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithCodeRule; +import io.jenkins.plugins.casc.misc.junit.jupiter.WithJenkinsConfiguredWithCode; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; @@ -32,49 +31,45 @@ import java.util.Collections; import java.util.List; import java.util.Random; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.jvnet.hudson.test.JenkinsRule; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; /** @author Dmitry Frolov tekillaz.dev@gmail.com */ -@RunWith(MockitoJUnitRunner.class) -public class IssueFieldUpdateStepTest { +@WithJenkinsConfiguredWithCode +@ExtendWith(MockitoExtension.class) +class IssueFieldUpdateStepTest { private static final String BUILD_NUMBER_VAR = "${BUILD_NUMBER}"; - @Rule - public JenkinsRule r = new JenkinsConfiguredWithCodeRule(); - - @Mock + @Mock(strictness = Mock.Strictness.LENIENT) JiraSite site; - @Mock + @Mock(strictness = Mock.Strictness.LENIENT) JiraSession session; @Mock PrintStream logger; - @Mock + @Mock(strictness = Mock.Strictness.LENIENT) AbstractBuild build; - @Mock + @Mock(strictness = Mock.Strictness.LENIENT) Launcher launcher; - @Mock + @Mock(strictness = Mock.Strictness.LENIENT) BuildListener listener; @Mock AbstractProject project; - @Mock + @Mock(strictness = Mock.Strictness.LENIENT) Job job; - @Before - public void before() { + @BeforeEach + void before(JenkinsConfiguredWithCodeRule r) { when(build.getParent()).thenReturn(project); when(build.getProject()).thenReturn(project); when(listener.getLogger()).thenReturn(logger); @@ -86,7 +81,7 @@ public void before() { } @Test - public void checkPrepareFieldId() { + void checkPrepareFieldId() { List field_test = Arrays.asList("10100", "customfield_10100", "field_10100"); @@ -94,20 +89,19 @@ public void checkPrepareFieldId() { IssueFieldUpdateStep jifu = new IssueFieldUpdateStep(null, null, ""); for (int i = 0; i < field_test.size(); i++) { - assertEquals("Check field id conversion #" + i, jifu.prepareFieldId(field_test.get(i)), field_after.get(i)); + assertEquals(jifu.prepareFieldId(field_test.get(i)), field_after.get(i), "Check field id conversion #" + i); } } - @Test(expected = IOException.class) - public void shouldFailIfSelectorIsNull() throws InterruptedException, IOException { + @Test + void shouldFailIfSelectorIsNull() throws IOException, InterruptedException { IssueFieldUpdateStep jifu = spy(new IssueFieldUpdateStep(null, "", "")); - jifu.perform(build, null, launcher, listener); - assertSame("Check selector is null", Result.FAILURE, build.getResult()); + assertThrows(IOException.class, () -> jifu.perform(build, null, launcher, listener)); } - @Test // @ConfiguredWithCode("single-site.yml") - public void checkSubmit() throws InterruptedException, IOException { + @Test + void checkSubmit() throws InterruptedException, IOException { Random random = new Random(); Integer randomBuildNumber = random.nextInt(85) + 15; // random number 15 < r < 99 String issueId = "ISSUE-" + random.nextInt(1000) + 999; @@ -135,7 +129,7 @@ public void checkSubmit() throws InterruptedException, IOException { IssueFieldUpdateStep jifu = spy(new IssueFieldUpdateStep(issueSelector, beforeFieldid, beforeFieldValue)); jifu.perform(build, null, launcher, listener); - assertEquals("Check issue value", issuesAfter.get(0), issueId); + assertEquals(issuesAfter.get(0), issueId, "Check issue value"); assertEquals("customfield_" + beforeFieldid, fieldsAfter.get(0).getId()); assertThat(fieldsAfter.get(0).getValue().toString(), containsString("build #" + randomBuildNumber.toString())); diff --git a/src/test/java/hudson/plugins/jira/pipeline/IssueSelectorStepTest.java b/src/test/java/hudson/plugins/jira/pipeline/IssueSelectorStepTest.java index 213fb2fac..d9dc45b33 100644 --- a/src/test/java/hudson/plugins/jira/pipeline/IssueSelectorStepTest.java +++ b/src/test/java/hudson/plugins/jira/pipeline/IssueSelectorStepTest.java @@ -22,16 +22,17 @@ import java.util.HashMap; import java.util.Set; import org.jenkinsci.plugins.workflow.steps.StepContext; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; -@RunWith(MockitoJUnitRunner.class) -public class IssueSelectorStepTest { +@WithJenkins +@ExtendWith(MockitoExtension.class) +class IssueSelectorStepTest { @Inject private IssueSelectorStep.DescriptorImpl descriptor; @@ -39,7 +40,7 @@ public class IssueSelectorStepTest { @Mock private AbstractIssueSelector issueSelector; - @Mock + @Mock(strictness = Mock.Strictness.LENIENT) private TaskListener listener; @Mock @@ -48,17 +49,14 @@ public class IssueSelectorStepTest { @Mock private Run run; - @Mock + @Mock(strictness = Mock.Strictness.LENIENT) private StepContext stepContext; private IssueSelectorStep.IssueSelectorStepExecution stepExecution; private IssueSelectorStep subject; - @ClassRule - public static JenkinsRule jenkinsRule = new JenkinsRule(); - - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp(JenkinsRule jenkinsRule) throws Exception { jenkinsRule.getInstance().getInjector().injectMembers(this); when(listener.getLogger()).thenReturn(logger); @@ -71,7 +69,7 @@ public void setUp() throws Exception { } @Test - public void runWithNullSite() throws Exception { + void runWithNullSite() throws Exception { stepExecution = spy((IssueSelectorStep.IssueSelectorStepExecution) subject.start(stepContext)); // doReturn(Optional.empty()).when(stepExecution).getOptionalJiraSite(); @@ -83,7 +81,7 @@ public void runWithNullSite() throws Exception { } @Test - public void run() throws Exception { + void run() throws Exception { JiraSite site = mock(JiraSite.class); JiraGlobalConfiguration jiraGlobalConfiguration = JiraGlobalConfiguration.get(); jiraGlobalConfiguration.setSites(Collections.singletonList(site)); diff --git a/src/test/java/hudson/plugins/jira/pipeline/SearchIssuesStepTest.java b/src/test/java/hudson/plugins/jira/pipeline/SearchIssuesStepTest.java index 23afe0ab0..23fbbfd61 100644 --- a/src/test/java/hudson/plugins/jira/pipeline/SearchIssuesStepTest.java +++ b/src/test/java/hudson/plugins/jira/pipeline/SearchIssuesStepTest.java @@ -3,7 +3,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.collection.IsCollectionWithSize.hasSize; import static org.hamcrest.core.IsEqual.equalTo; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -24,26 +24,27 @@ import java.util.Map; import org.jenkinsci.plugins.workflow.steps.StepConfigTester; import org.jenkinsci.plugins.workflow.steps.StepContext; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; -public class SearchIssuesStepTest { +@WithJenkins +class SearchIssuesStepTest { - @ClassRule - public static JenkinsRule jenkinsRule = new JenkinsRule(); + private JenkinsRule jenkinsRule; @Inject SearchIssuesStep.DescriptorImpl descriptor; - @Before - public void setUp() { + @BeforeEach + void setUp(JenkinsRule jenkinsRule) throws Exception { + this.jenkinsRule = jenkinsRule; jenkinsRule.getInstance().getInjector().injectMembers(this); } @Test - public void configRoundTrip() throws Exception { + void configRoundTrip() throws Exception { configRoundTrip(""); configRoundTrip("key='EXAMPLE-1'"); } @@ -54,7 +55,7 @@ private void configRoundTrip(String jql) throws Exception { } @Test - public void callGetIssuesFromJqlSearch() throws Exception { + void callGetIssuesFromJqlSearch() throws Exception { JiraSession session = mock(JiraSession.class); String jql = "key='EXAMPLE-1'"; Issue issue = mock(Issue.class); diff --git a/src/test/java/hudson/plugins/jira/selector/DefaultIssueSelectorTest.java b/src/test/java/hudson/plugins/jira/selector/DefaultIssueSelectorTest.java index 523f747f4..70fd5b8f1 100644 --- a/src/test/java/hudson/plugins/jira/selector/DefaultIssueSelectorTest.java +++ b/src/test/java/hudson/plugins/jira/selector/DefaultIssueSelectorTest.java @@ -1,5 +1,7 @@ package hudson.plugins.jira.selector; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -22,11 +24,10 @@ import java.util.Set; import java.util.TreeSet; import java.util.regex.Pattern; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.Issue; -public class DefaultIssueSelectorTest { +class DefaultIssueSelectorTest { private static class MockEntry extends Entry { @@ -54,7 +55,7 @@ public String getMsg() { @Test @Issue("4132") - public void projectNamesAllowed() { + void projectNamesAllowed() { FreeStyleBuild build = mock(FreeStyleBuild.class); ChangeLogSet changeLogSet = mock(ChangeLogSet.class); BuildListener listener = mock(BuildListener.class); @@ -100,8 +101,8 @@ public void projectNamesAllowed() { Set result = new DefaultIssueSelector().findIssueIds(build, site, listener); - Assert.assertEquals(expected.size(), result.size()); - Assert.assertEquals(expected, result); + assertEquals(expected.size(), result.size()); + assertEquals(expected, result); } /** @@ -110,7 +111,7 @@ public void projectNamesAllowed() { */ @Test @Issue("12312") - public void findIssuesWithJiraParameters() { + void findIssuesWithJiraParameters() { FreeStyleBuild build = mock(FreeStyleBuild.class); ChangeLogSet changeLogSet = mock(ChangeLogSet.class); BuildListener listener = mock(BuildListener.class); @@ -132,23 +133,23 @@ public void findIssuesWithJiraParameters() { // Initial state contains zero parameters Set ids = new DefaultIssueSelector().findIssueIds(build, site, listener); - Assert.assertTrue(ids.isEmpty()); + assertTrue(ids.isEmpty()); parameters.add(parameter); ids = new DefaultIssueSelector().findIssueIds(build, site, listener); - Assert.assertEquals(1, ids.size()); - Assert.assertEquals("JIRA-123", ids.iterator().next()); + assertEquals(1, ids.size()); + assertEquals("JIRA-123", ids.iterator().next()); parameters.add(parameterTwo); ids = new DefaultIssueSelector().findIssueIds(build, site, listener); - Assert.assertEquals(2, ids.size()); + assertEquals(2, ids.size()); Set expected = new TreeSet(Arrays.asList("JIRA-123", "JIRA-321")); - Assert.assertEquals(expected, ids); + assertEquals(expected, ids); } @Test @Issue("6043") - public void userPatternNotMatch() { + void userPatternNotMatch() { FreeStyleBuild build = mock(FreeStyleBuild.class); ChangeLogSet changeLogSet = mock(ChangeLogSet.class); when(build.getChangeSet()).thenReturn(changeLogSet); @@ -159,12 +160,12 @@ public void userPatternNotMatch() { Set ids = new LinkedHashSet<>(); DefaultIssueSelector.findIssues(build, ids, Pattern.compile("[(w)]"), mock(BuildListener.class)); - Assert.assertEquals(0, ids.size()); + assertEquals(0, ids.size()); } @Test @Issue("6043") - public void userPatternMatchTwoIssuesInOneComment() { + void userPatternMatchTwoIssuesInOneComment() { FreeStyleBuild build = mock(FreeStyleBuild.class); ChangeLogSet changeLogSet = mock(ChangeLogSet.class); when(build.getChangeSet()).thenReturn(changeLogSet); @@ -182,15 +183,15 @@ public void userPatternMatchTwoIssuesInOneComment() { Set ids = new LinkedHashSet<>(); Pattern pat = Pattern.compile("\\[(\\w+-\\d+)\\]"); DefaultIssueSelector.findIssues(build, ids, pat, mock(BuildListener.class)); - Assert.assertEquals(3, ids.size()); - Assert.assertTrue(ids.contains("TEST-9")); - Assert.assertTrue(ids.contains("FOOBAR-4711")); - Assert.assertTrue(ids.contains("FOOBAR-21")); + assertEquals(3, ids.size()); + assertTrue(ids.contains("TEST-9")); + assertTrue(ids.contains("FOOBAR-4711")); + assertTrue(ids.contains("FOOBAR-21")); } @Test @Issue("6043") - public void userPatternMatch() { + void userPatternMatch() { FreeStyleBuild build = mock(FreeStyleBuild.class); ChangeLogSet changeLogSet = mock(ChangeLogSet.class); when(build.getChangeSet()).thenReturn(changeLogSet); @@ -208,9 +209,9 @@ public void userPatternMatch() { Set ids = new LinkedHashSet<>(); Pattern pat = Pattern.compile("\\[(\\w+-\\d+)\\]"); DefaultIssueSelector.findIssues(build, ids, pat, mock(BuildListener.class)); - Assert.assertEquals(2, ids.size()); - Assert.assertTrue(ids.contains("TEST-9")); - Assert.assertTrue(ids.contains("FOOBAR-4711")); + assertEquals(2, ids.size()); + assertTrue(ids.contains("TEST-9")); + assertTrue(ids.contains("FOOBAR-4711")); } /** @@ -218,7 +219,7 @@ public void userPatternMatch() { * These patterns are used e.g. by the maven release plugin. */ @Test - public void defaultPatternNotToMatchMavenRelease() { + void defaultPatternNotToMatchMavenRelease() { FreeStyleBuild build = mock(FreeStyleBuild.class); ChangeLogSet changeLogSet = mock(ChangeLogSet.class); when(build.getChangeSet()).thenReturn(changeLogSet); @@ -230,6 +231,6 @@ public void defaultPatternNotToMatchMavenRelease() { Set ids = new LinkedHashSet<>(); DefaultIssueSelector.findIssues(build, ids, JiraSite.DEFAULT_ISSUE_PATTERN, null); - Assert.assertEquals(0, ids.size()); + assertEquals(0, ids.size()); } } diff --git a/src/test/java/hudson/plugins/jira/selector/ExplicitIssueSelectorTest.java b/src/test/java/hudson/plugins/jira/selector/ExplicitIssueSelectorTest.java index 74ff8421c..2cef66c7f 100644 --- a/src/test/java/hudson/plugins/jira/selector/ExplicitIssueSelectorTest.java +++ b/src/test/java/hudson/plugins/jira/selector/ExplicitIssueSelectorTest.java @@ -6,14 +6,14 @@ import java.util.Collections; import java.util.Set; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class ExplicitIssueSelectorTest { +class ExplicitIssueSelectorTest { private static final String TEST_KEY = "EXAMPLE-1"; @Test - public void returnsExplicitCollections() { + void returnsExplicitCollections() { ExplicitIssueSelector jqlUpdaterIssueSelector = new ExplicitIssueSelector(Collections.singletonList(TEST_KEY)); Set foundIssueIds = jqlUpdaterIssueSelector.findIssueIds(null, null, null); assertThat(foundIssueIds, hasSize(1)); diff --git a/src/test/java/hudson/plugins/jira/selector/JqlIssueSelectorTest.java b/src/test/java/hudson/plugins/jira/selector/JqlIssueSelectorTest.java index 1ae7df8e7..c220a2f76 100644 --- a/src/test/java/hudson/plugins/jira/selector/JqlIssueSelectorTest.java +++ b/src/test/java/hudson/plugins/jira/selector/JqlIssueSelectorTest.java @@ -16,14 +16,14 @@ import java.util.Collections; import java.util.Set; import java.util.concurrent.TimeoutException; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; -@RunWith(MockitoJUnitRunner.class) -public class JqlIssueSelectorTest { +@ExtendWith(MockitoExtension.class) +class JqlIssueSelectorTest { private static final String TEST_JQL = "key='EXAMPLE-1'"; @@ -39,21 +39,21 @@ public class JqlIssueSelectorTest { @Mock private Run run; - @Before - public void prepare() throws IOException { + @BeforeEach + void prepare() throws IOException { when(run.getParent()).thenReturn(project); when(site.getSession(project)).thenReturn(session); } @Test - public void dontDependOnRunAndTaskListener() { + void dontDependOnRunAndTaskListener() { JqlIssueSelector jqlUpdaterIssueSelector = new JqlIssueSelector(TEST_JQL); Set foundIssues = jqlUpdaterIssueSelector.findIssueIds(run, site, null); assertThat(foundIssues, empty()); } @Test - public void callGetIssuesFromJqlSearch() throws IOException, TimeoutException { + void callGetIssuesFromJqlSearch() throws IOException, TimeoutException { Issue issue = mock(Issue.class); when(issue.getKey()).thenReturn("EXAMPLE-1"); when(session.getIssuesFromJqlSearch(TEST_JQL)).thenReturn(Collections.singletonList(issue)); diff --git a/src/test/java/hudson/plugins/jira/selector/perforce/JobIssueSelectorTest.java b/src/test/java/hudson/plugins/jira/selector/perforce/JobIssueSelectorTest.java index c57bcb6cb..44c2b7c4f 100644 --- a/src/test/java/hudson/plugins/jira/selector/perforce/JobIssueSelectorTest.java +++ b/src/test/java/hudson/plugins/jira/selector/perforce/JobIssueSelectorTest.java @@ -1,5 +1,7 @@ package hudson.plugins.jira.selector.perforce; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -17,8 +19,7 @@ import java.util.List; import java.util.Set; import java.util.TreeSet; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public abstract class JobIssueSelectorTest { @@ -48,18 +49,18 @@ public void findsIssuesWithJiraParameters() { JobIssueSelector jobIssueSelector = createJobIssueSelector(); // Initial state contains zero parameters ids = jobIssueSelector.findIssueIds(build, jiraSite, listener); - Assert.assertTrue(ids.isEmpty()); + assertTrue(ids.isEmpty()); parameters.add(parameter); ids = jobIssueSelector.findIssueIds(build, jiraSite, listener); - Assert.assertEquals(1, ids.size()); - Assert.assertEquals("JIRA-123", ids.iterator().next()); + assertEquals(1, ids.size()); + assertEquals("JIRA-123", ids.iterator().next()); parameters.add(parameterTwo); ids = jobIssueSelector.findIssueIds(build, jiraSite, listener); - Assert.assertEquals(2, ids.size()); + assertEquals(2, ids.size()); Set expected = new TreeSet(Arrays.asList("JIRA-123", "JIRA-321")); - Assert.assertEquals(expected, ids); + assertEquals(expected, ids); } @Test @@ -85,8 +86,8 @@ public void findsCarriedOnIssues() { JobIssueSelector jobIssueSelector = createJobIssueSelector(); Set ids = jobIssueSelector.findIssueIds(build, jiraSite, listener); - Assert.assertEquals(1, ids.size()); + assertEquals(1, ids.size()); Set expected = new TreeSet<>(Collections.singletonList("GC-131")); - Assert.assertEquals(expected, ids); + assertEquals(expected, ids); } } diff --git a/src/test/java/hudson/plugins/jira/selector/perforce/P4JobIssueSelectorTest.java b/src/test/java/hudson/plugins/jira/selector/perforce/P4JobIssueSelectorTest.java index 4348336a4..86d31c62b 100644 --- a/src/test/java/hudson/plugins/jira/selector/perforce/P4JobIssueSelectorTest.java +++ b/src/test/java/hudson/plugins/jira/selector/perforce/P4JobIssueSelectorTest.java @@ -1,5 +1,6 @@ package hudson.plugins.jira.selector.perforce; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -15,13 +16,12 @@ import java.util.Set; import org.jenkinsci.plugins.p4.changes.P4ChangeEntry; import org.jenkinsci.plugins.p4.changes.P4ChangeSet; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class P4JobIssueSelectorTest extends JobIssueSelectorTest { +class P4JobIssueSelectorTest extends JobIssueSelectorTest { @Test - public void findsTwoP4Jobs() { + void findsTwoP4Jobs() { final String jobIdIW1231 = "IW-1231"; final String jobIdEC3453 = "EC-3453"; @@ -59,8 +59,8 @@ public void findsTwoP4Jobs() { P4JobIssueSelector selector = new P4JobIssueSelector(); Set result = selector.findIssueIds(build, jiraSite, listener); - Assert.assertEquals(expected.size(), result.size()); - Assert.assertEquals(expected, result); + assertEquals(expected.size(), result.size()); + assertEquals(expected, result); } @Override diff --git a/src/test/java/hudson/plugins/jira/versionparameter/JiraVersionParameterDefinitionTest.java b/src/test/java/hudson/plugins/jira/versionparameter/JiraVersionParameterDefinitionTest.java index 457c58cd8..13ed8c65d 100644 --- a/src/test/java/hudson/plugins/jira/versionparameter/JiraVersionParameterDefinitionTest.java +++ b/src/test/java/hudson/plugins/jira/versionparameter/JiraVersionParameterDefinitionTest.java @@ -1,16 +1,16 @@ package hudson.plugins.jira.versionparameter; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import hudson.cli.CLICommand; import hudson.model.ParameterDefinition; import hudson.model.ParameterValue; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class JiraVersionParameterDefinitionTest { +class JiraVersionParameterDefinitionTest { @Test - public void parameterValueMethodOverrides() throws Exception { + void parameterValueMethodOverrides() throws Exception { ParameterDefinition definition = new JiraVersionParameterDefinition("pname", "pdesc", "JIRAKEY", null, "false", "false"); CLICommand cliCommand = mock(CLICommand.class); diff --git a/src/test/java/hudson/plugins/jira/versionparameter/VersionComparatorTest.java b/src/test/java/hudson/plugins/jira/versionparameter/VersionComparatorTest.java index 2cc23a270..96d7db881 100644 --- a/src/test/java/hudson/plugins/jira/versionparameter/VersionComparatorTest.java +++ b/src/test/java/hudson/plugins/jira/versionparameter/VersionComparatorTest.java @@ -1,19 +1,19 @@ package hudson.plugins.jira.versionparameter; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import com.atlassian.jira.rest.client.api.domain.Version; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import org.hamcrest.collection.ArrayMatching; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class VersionComparatorTest { +class VersionComparatorTest { @Test - public void complexCompare() { + void complexCompare() { String[] input = { "9.9.9.9.9", "V-5.2.3", @@ -49,7 +49,7 @@ public void complexCompare() { } @Test - public void singleComparisonsTests() { + void singleComparisonsTests() { assertEquals(0, compare("1.1.1.1", "1.1.1.1")); assertEquals(-1, compare("A-1.1.1.1", "1.1.1.1")); @@ -77,7 +77,7 @@ private int compare(String v1, String v2) { } @Test - public void getNumberVersionTest() { + void getNumberVersionTest() { assertEquals("2.3.4", VersionComparator.INSTANCE.getNumberVersion("PDFREPORT-2.3.4")); } } From 0e5429badde339d0ba556c32fac2b753c6b89f09 Mon Sep 17 00:00:00 2001 From: strangelookingnerd Date: Tue, 28 Jan 2025 09:26:38 +0100 Subject: [PATCH 2/3] Migrate tests to JUnit5 * Use JUnit5 annotations and imports * Cleanup assertions * Remove public visibility from test classes and methods --- .../hudson/plugins/jira/JiraBuildActionTest.java | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/src/test/java/hudson/plugins/jira/JiraBuildActionTest.java b/src/test/java/hudson/plugins/jira/JiraBuildActionTest.java index 24e7a20c6..562098b64 100644 --- a/src/test/java/hudson/plugins/jira/JiraBuildActionTest.java +++ b/src/test/java/hudson/plugins/jira/JiraBuildActionTest.java @@ -2,23 +2,20 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import hudson.model.Job; import hudson.model.Run; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.jvnet.hudson.test.recipes.LocalData; /** * Place needed resources in src/test/resources * */ -public class JiraBuildActionTest { - - @Rule - public JenkinsRule r = new JenkinsRule(); +class JiraBuildActionTest { /** * Test if existing serialized JiraBuildAction information will be loaded after upgrading jira @@ -26,7 +23,8 @@ public class JiraBuildActionTest { */ @Test @LocalData - public void binaryCompatibility() { + @WithJenkins + void binaryCompatibility(JenkinsRule r) throws Exception { assertEquals("Jenkins JiraBuildActionTest config", r.jenkins.getSystemMessage()); Job job = r.getInstance().getItemByFullName("/project", Job.class); From bffdb1de836ce3e00419cb508aa8cad579fb704a Mon Sep 17 00:00:00 2001 From: strangelookingnerd <49242855+strangelookingnerd@users.noreply.github.com> Date: Tue, 4 Feb 2025 11:10:45 +0100 Subject: [PATCH 3/3] Bump plugin-pom to 5.7 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index cb0be1870..9875f667c 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ org.jenkins-ci.plugins plugin - 5.6 + 5.7