From 45ab81fbbf36b73f0b5b6e39463472af2986dbea Mon Sep 17 00:00:00 2001 From: "ibrahim.atcha" Date: Wed, 1 Mar 2023 19:07:28 +0000 Subject: [PATCH 1/4] updates dependencies moves to junit 5 refactors code generally --- build.gradle | 22 ++-- traverson4j-core/build.gradle | 2 +- .../traverson/TraversonBuilder.java | 2 +- .../conversion/FastJsonResourceConverter.java | 13 ++- .../traverson/link/BasicLinkDiscoverer.java | 2 +- .../traverson/link/LinkDiscoverer.java | 2 +- .../link/hal/EmbeddedArrayNameHandler.java | 5 +- .../traverson/link/hal/EmbeddedResolver.java | 11 +- .../traverson/link/hal/HalEntityResolver.java | 4 +- .../traverson/link/hal/HalLinkDiscoverer.java | 2 +- .../traverson/link/hal/LinksRelHandler.java | 4 +- .../traverson/link/hal/LinksResolver.java | 8 +- .../link/hal/RelByArrayIndexDiscoverer.java | 6 +- .../hal/RelByArrayPropertyDiscoverer.java | 6 +- .../TraversonBuilderFollowsTest.java | 69 ++++++------ .../traverson/TraversonBuilderTest.java | 105 +++++++++--------- .../autotrader/traverson/TraversonTest.java | 12 +- .../conversion/ByteArrayConverterTest.java | 16 +-- .../FastJsonResourceConverterTest.java | 26 ++--- .../conversion/InputStreamConverterTest.java | 14 +-- .../ResourceConversionServiceTest.java | 43 ++++--- .../StringResourceConverterTest.java | 16 +-- .../exception/HttpExceptionTest.java | 6 +- .../IllegalHttpStatusExceptionTest.java | 6 +- .../traverson/http/FormBodyTest.java | 12 +- .../traverson/http/ResponseTest.java | 54 +++++---- .../traverson/http/TextBodyTest.java | 14 +-- .../http/multipart/BodyPartTest.java | 12 +- .../multipart/SimpleMultipartBodyTest.java | 14 +-- .../link/BasicLinkDiscovererTest.java | 26 ++--- .../traverson/link/HalLinkDiscovererTest.java | 42 +++---- .../hal/EmbeddedArrayNameHandlerTest.java | 26 ++--- .../link/hal/LinksRelHandlerTest.java | 26 ++--- .../hal/RelByArrayIndexDiscovererTest.java | 86 ++++++++------ .../hal/RelByArrayPropertyDiscovererTest.java | 69 ++++++------ traverson4j-hc5/build.gradle | 2 +- .../ApacheHttpTraversonClientAdapter.java | 2 +- .../http/ApacheHttpConvertersTest.java | 48 ++++---- .../ApacheHttpTraversonClientAdapterTest.java | 48 ++++---- .../traverson/http/IntegrationTest.java | 34 +++--- .../traverson/http/TemplateUriUtilsTest.java | 25 ++--- .../http/entity/BodyFactoryTest.java | 39 ++++--- .../entity/BodyPartEntityConverterTest.java | 27 ++--- .../entity/FormDataEntityConverterTest.java | 18 +-- .../http/entity/TextEntityConverterTest.java | 20 ++-- traverson4j-jackson2/build.gradle | 2 +- .../JacksonResourceConverterTest.java | 24 ++-- 47 files changed, 551 insertions(+), 521 deletions(-) diff --git a/build.gradle b/build.gradle index aaeff62..68d32b4 100644 --- a/build.gradle +++ b/build.gradle @@ -1,6 +1,7 @@ plugins { - id "com.github.spotbugs" version "4.7.0" apply false - id "org.owasp.dependencycheck" version "6.1.5" apply false + id "java" + id "com.github.spotbugs" version "4.7.3" apply false + id "org.owasp.dependencycheck" version "8.1.2" apply false id "io.github.gradle-nexus.publish-plugin" version "1.1.0" } @@ -30,12 +31,19 @@ subprojects { mavenCentral() } + test { + useJUnitPlatform() + } + dependencies { - testImplementation 'junit:junit:4.12', - 'com.google.guava:guava:18.0', - 'org.mockito:mockito-core:3.6.28', - 'org.assertj:assertj-core:3.11.1', - 'org.apache.commons:commons-lang3:3.4' + testImplementation 'org.junit.jupiter:junit-jupiter-api:5.9.2', + 'org.junit.jupiter:junit-jupiter-params:5.9.2', + 'org.junit.jupiter:junit-jupiter-engine:5.9.2', + 'com.google.guava:guava:31.1-jre', + 'org.mockito:mockito-core:5.1.1', + 'org.mockito:mockito-junit-jupiter:5.1.1', + 'org.assertj:assertj-core:3.24.2', + 'org.apache.commons:commons-lang3:3.12.0' } jacocoTestCoverageVerification { diff --git a/traverson4j-core/build.gradle b/traverson4j-core/build.gradle index 661e4e8..79f705f 100644 --- a/traverson4j-core/build.gradle +++ b/traverson4j-core/build.gradle @@ -1,3 +1,3 @@ dependencies { - api 'com.alibaba:fastjson:2.0.22' + api 'com.alibaba.fastjson2:fastjson2:2.0.0' } diff --git a/traverson4j-core/src/main/java/uk/co/autotrader/traverson/TraversonBuilder.java b/traverson4j-core/src/main/java/uk/co/autotrader/traverson/TraversonBuilder.java index 460440b..1e4235e 100644 --- a/traverson4j-core/src/main/java/uk/co/autotrader/traverson/TraversonBuilder.java +++ b/traverson4j-core/src/main/java/uk/co/autotrader/traverson/TraversonBuilder.java @@ -1,6 +1,6 @@ package uk.co.autotrader.traverson; -import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson2.JSONObject; import uk.co.autotrader.traverson.http.AuthCredential; import uk.co.autotrader.traverson.exception.IllegalHttpStatusException; import uk.co.autotrader.traverson.http.*; diff --git a/traverson4j-core/src/main/java/uk/co/autotrader/traverson/conversion/FastJsonResourceConverter.java b/traverson4j-core/src/main/java/uk/co/autotrader/traverson/conversion/FastJsonResourceConverter.java index c0bc8d4..e383c22 100644 --- a/traverson4j-core/src/main/java/uk/co/autotrader/traverson/conversion/FastJsonResourceConverter.java +++ b/traverson4j-core/src/main/java/uk/co/autotrader/traverson/conversion/FastJsonResourceConverter.java @@ -1,8 +1,8 @@ package uk.co.autotrader.traverson.conversion; -import com.alibaba.fastjson.JSONException; -import com.alibaba.fastjson.JSONObject; -import com.alibaba.fastjson.parser.Feature; +import com.alibaba.fastjson2.JSON; +import com.alibaba.fastjson2.JSONException; +import com.alibaba.fastjson2.JSONObject; import uk.co.autotrader.traverson.exception.ConversionException; import java.io.InputStream; @@ -19,7 +19,12 @@ public JSONObject convert(InputStream resource, Class retu String resourceAsString = null; try { resourceAsString = new StringResourceConverter().convert(resource, String.class); - return JSONObject.parseObject(resourceAsString, Feature.OrderedField); + + if (resourceAsString.isEmpty()) { + return null; + } + + return JSON.parseObject(resourceAsString); } catch (JSONException ex) { throw new ConversionException("Failed to parse to JSONObject", resourceAsString, ex); } diff --git a/traverson4j-core/src/main/java/uk/co/autotrader/traverson/link/BasicLinkDiscoverer.java b/traverson4j-core/src/main/java/uk/co/autotrader/traverson/link/BasicLinkDiscoverer.java index 9ce2cda..1fd75cf 100644 --- a/traverson4j-core/src/main/java/uk/co/autotrader/traverson/link/BasicLinkDiscoverer.java +++ b/traverson4j-core/src/main/java/uk/co/autotrader/traverson/link/BasicLinkDiscoverer.java @@ -1,6 +1,6 @@ package uk.co.autotrader.traverson.link; -import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson2.JSONObject; import uk.co.autotrader.traverson.exception.UnknownRelException; public class BasicLinkDiscoverer implements LinkDiscoverer { diff --git a/traverson4j-core/src/main/java/uk/co/autotrader/traverson/link/LinkDiscoverer.java b/traverson4j-core/src/main/java/uk/co/autotrader/traverson/link/LinkDiscoverer.java index 872cb00..ce09c83 100644 --- a/traverson4j-core/src/main/java/uk/co/autotrader/traverson/link/LinkDiscoverer.java +++ b/traverson4j-core/src/main/java/uk/co/autotrader/traverson/link/LinkDiscoverer.java @@ -1,6 +1,6 @@ package uk.co.autotrader.traverson.link; -import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson2.JSONObject; public interface LinkDiscoverer { String findHref(JSONObject responseEntity, String rel); diff --git a/traverson4j-core/src/main/java/uk/co/autotrader/traverson/link/hal/EmbeddedArrayNameHandler.java b/traverson4j-core/src/main/java/uk/co/autotrader/traverson/link/hal/EmbeddedArrayNameHandler.java index a535060..eadedfa 100644 --- a/traverson4j-core/src/main/java/uk/co/autotrader/traverson/link/hal/EmbeddedArrayNameHandler.java +++ b/traverson4j-core/src/main/java/uk/co/autotrader/traverson/link/hal/EmbeddedArrayNameHandler.java @@ -1,7 +1,6 @@ package uk.co.autotrader.traverson.link.hal; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson2.JSONArray; +import com.alibaba.fastjson2.JSONObject; import uk.co.autotrader.traverson.link.LinkDiscoverer; import static java.util.Collections.emptyList; diff --git a/traverson4j-core/src/main/java/uk/co/autotrader/traverson/link/hal/EmbeddedResolver.java b/traverson4j-core/src/main/java/uk/co/autotrader/traverson/link/hal/EmbeddedResolver.java index eeef551..41c828d 100644 --- a/traverson4j-core/src/main/java/uk/co/autotrader/traverson/link/hal/EmbeddedResolver.java +++ b/traverson4j-core/src/main/java/uk/co/autotrader/traverson/link/hal/EmbeddedResolver.java @@ -1,7 +1,8 @@ package uk.co.autotrader.traverson.link.hal; -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; + +import com.alibaba.fastjson2.JSONArray; +import com.alibaba.fastjson2.JSONObject; import java.util.HashMap; import java.util.Map; @@ -17,7 +18,7 @@ public JSONArray findJSONArrayRelation(JSONObject halResource, String relationTy } Object maybeJsonArray = embeddedResources.get(relationType); - if (maybeJsonArray == null || !(maybeJsonArray instanceof JSONArray)) { + if (!(maybeJsonArray instanceof JSONArray)) { return new JSONArray(); } @@ -33,9 +34,9 @@ public String resolveLink(JSONObject jsonObject) { public Map> describeRelations(JSONObject resource) { JSONObject embeddedResources = getEmbeddedSection(resource); - Map> relations = new HashMap>(); + Map> relations = new HashMap<>(); if (embeddedResources != null) { - SortedSet sortedRels = new TreeSet(); + SortedSet sortedRels = new TreeSet<>(); sortedRels.addAll(embeddedResources.keySet()); relations.put("'_embedded'", sortedRels); } diff --git a/traverson4j-core/src/main/java/uk/co/autotrader/traverson/link/hal/HalEntityResolver.java b/traverson4j-core/src/main/java/uk/co/autotrader/traverson/link/hal/HalEntityResolver.java index c34acb4..01c1234 100644 --- a/traverson4j-core/src/main/java/uk/co/autotrader/traverson/link/hal/HalEntityResolver.java +++ b/traverson4j-core/src/main/java/uk/co/autotrader/traverson/link/hal/HalEntityResolver.java @@ -1,7 +1,7 @@ package uk.co.autotrader.traverson.link.hal; -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson2.JSONArray; +import com.alibaba.fastjson2.JSONObject; import java.util.Map; import java.util.SortedSet; diff --git a/traverson4j-core/src/main/java/uk/co/autotrader/traverson/link/hal/HalLinkDiscoverer.java b/traverson4j-core/src/main/java/uk/co/autotrader/traverson/link/hal/HalLinkDiscoverer.java index 7083968..fcd6a1d 100644 --- a/traverson4j-core/src/main/java/uk/co/autotrader/traverson/link/hal/HalLinkDiscoverer.java +++ b/traverson4j-core/src/main/java/uk/co/autotrader/traverson/link/hal/HalLinkDiscoverer.java @@ -1,6 +1,6 @@ package uk.co.autotrader.traverson.link.hal; -import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson2.JSONObject; import uk.co.autotrader.traverson.link.LinkDiscoverer; import java.util.Arrays; diff --git a/traverson4j-core/src/main/java/uk/co/autotrader/traverson/link/hal/LinksRelHandler.java b/traverson4j-core/src/main/java/uk/co/autotrader/traverson/link/hal/LinksRelHandler.java index b79c23f..00a8a43 100644 --- a/traverson4j-core/src/main/java/uk/co/autotrader/traverson/link/hal/LinksRelHandler.java +++ b/traverson4j-core/src/main/java/uk/co/autotrader/traverson/link/hal/LinksRelHandler.java @@ -1,6 +1,6 @@ package uk.co.autotrader.traverson.link.hal; -import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson2.JSONObject; import uk.co.autotrader.traverson.exception.UnknownRelException; import uk.co.autotrader.traverson.link.LinkDiscoverer; @@ -22,7 +22,7 @@ public String findHref(JSONObject resource, String rel) { } private SortedSet sort(Set set) { - SortedSet sorted = new TreeSet(); + SortedSet sorted = new TreeSet<>(); sorted.addAll(set); return sorted; } diff --git a/traverson4j-core/src/main/java/uk/co/autotrader/traverson/link/hal/LinksResolver.java b/traverson4j-core/src/main/java/uk/co/autotrader/traverson/link/hal/LinksResolver.java index 82bcf23..d9be02f 100644 --- a/traverson4j-core/src/main/java/uk/co/autotrader/traverson/link/hal/LinksResolver.java +++ b/traverson4j-core/src/main/java/uk/co/autotrader/traverson/link/hal/LinksResolver.java @@ -1,7 +1,7 @@ package uk.co.autotrader.traverson.link.hal; -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson2.JSONArray; +import com.alibaba.fastjson2.JSONObject; import java.util.Map; import java.util.SortedSet; @@ -14,7 +14,7 @@ class LinksResolver implements HalEntityResolver { @Override public JSONArray findJSONArrayRelation(JSONObject halResource, String relationType) { Object maybeJsonArray = getLinksSection(halResource).get(relationType); - if (maybeJsonArray == null || !(maybeJsonArray instanceof JSONArray)) { + if (!(maybeJsonArray instanceof JSONArray)) { return new JSONArray(); } @@ -28,7 +28,7 @@ public String resolveLink(JSONObject jsonObject) { @Override public Map> describeRelations(JSONObject resource) { - SortedSet sortedRels = new TreeSet(); + SortedSet sortedRels = new TreeSet<>(); sortedRels.addAll(getLinksSection(resource).keySet()); return singletonMap("'_links'", sortedRels); } diff --git a/traverson4j-core/src/main/java/uk/co/autotrader/traverson/link/hal/RelByArrayIndexDiscoverer.java b/traverson4j-core/src/main/java/uk/co/autotrader/traverson/link/hal/RelByArrayIndexDiscoverer.java index f5f2af1..e4ec822 100644 --- a/traverson4j-core/src/main/java/uk/co/autotrader/traverson/link/hal/RelByArrayIndexDiscoverer.java +++ b/traverson4j-core/src/main/java/uk/co/autotrader/traverson/link/hal/RelByArrayIndexDiscoverer.java @@ -1,7 +1,7 @@ package uk.co.autotrader.traverson.link.hal; -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson2.JSONArray; +import com.alibaba.fastjson2.JSONObject; import uk.co.autotrader.traverson.exception.UnknownRelException; import uk.co.autotrader.traverson.link.LinkDiscoverer; @@ -52,7 +52,7 @@ private String findLink(JSONObject resource, String relName, int arrayIndex) { } private UnknownRelException createUnknownRelException(JSONObject resource, String relName, int arrayIndex) { - Map> rels = new HashMap>(); + Map> rels = new HashMap<>(); for (HalEntityResolver resolver : this.halEntityResolvers) { rels.putAll(resolver.describeRelations(resource)); } diff --git a/traverson4j-core/src/main/java/uk/co/autotrader/traverson/link/hal/RelByArrayPropertyDiscoverer.java b/traverson4j-core/src/main/java/uk/co/autotrader/traverson/link/hal/RelByArrayPropertyDiscoverer.java index 935b95f..da64930 100644 --- a/traverson4j-core/src/main/java/uk/co/autotrader/traverson/link/hal/RelByArrayPropertyDiscoverer.java +++ b/traverson4j-core/src/main/java/uk/co/autotrader/traverson/link/hal/RelByArrayPropertyDiscoverer.java @@ -1,7 +1,7 @@ package uk.co.autotrader.traverson.link.hal; -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson2.JSONArray; +import com.alibaba.fastjson2.JSONObject; import uk.co.autotrader.traverson.exception.UnknownRelException; import uk.co.autotrader.traverson.link.LinkDiscoverer; @@ -56,7 +56,7 @@ private String findLink(JSONObject resource, String relName, String propertyName } private UnknownRelException createUnknownRelException(JSONObject resource, String relName, String propertyName, String propertyValue) { - Map> rels = new HashMap>(); + Map> rels = new HashMap<>(); for (HalEntityResolver resolver : this.halEntityResolvers) { rels.putAll(resolver.describeRelations(resource)); } diff --git a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/TraversonBuilderFollowsTest.java b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/TraversonBuilderFollowsTest.java index 9129af3..b25e497 100644 --- a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/TraversonBuilderFollowsTest.java +++ b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/TraversonBuilderFollowsTest.java @@ -1,15 +1,14 @@ package uk.co.autotrader.traverson; -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson2.JSON; +import com.alibaba.fastjson2.JSONObject; import com.google.common.base.Charsets; import com.google.common.io.Resources; -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.invocation.InvocationOnMock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.stubbing.Answer; import uk.co.autotrader.traverson.exception.UnknownRelException; import uk.co.autotrader.traverson.http.Request; @@ -19,50 +18,46 @@ import java.io.IOException; import static com.google.common.io.Resources.getResource; -import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class TraversonBuilderFollowsTest { +@ExtendWith(MockitoExtension.class) +class TraversonBuilderFollowsTest { @Mock private TraversonClient client; private TraversonBuilder testSubject; - @Before - public void mockClientToResolveUrlsFromClasspath() { + @BeforeEach + void mockClientToResolveUrlsFromClasspath() { when(this.client.execute(any(Request.class), any(Class.class))).thenAnswer( - new Answer>() { - @Override - public Response answer(InvocationOnMock invocation) throws Throwable { - Request request = invocation.getArgument(0, Request.class); - JSONObject resource = getJsonResource(request.getUrl()); - - Response response = new Response(); - if (resource != null) { - response.setStatusCode(200); - response.setResource(resource); - } else { - response.setStatusCode(404); - } - - return response; + (Answer>) invocation -> { + Request request = invocation.getArgument(0, Request.class); + JSONObject resource = getJsonResource(request.getUrl()); + + Response response = new Response(); + if (resource != null) { + response.setStatusCode(200); + response.setResource(resource); + } else { + response.setStatusCode(404); } + + return response; } ); } - @Before - public void instantiateNewBuilder() { + @BeforeEach + void instantiateNewBuilder() { this.testSubject = new TraversonBuilder(this.client); } @Test - public void follows_GivenSimpleRelation_FollowsLinkInLinksBlock() throws Exception { + void follows_GivenSimpleRelation_FollowsLinkInLinksBlock() { JSONObject result = this.testSubject.jsonHal() .from("hal-traverson-builder-data.json") .follow("makes") @@ -73,7 +68,7 @@ public void follows_GivenSimpleRelation_FollowsLinkInLinksBlock() throws Excepti } @Test - public void follows_GivenRelByPropertyMatchingBothLinksAndEmbedded_FollowsLinkInLinksBlock() { + void follows_GivenRelByPropertyMatchingBothLinksAndEmbedded_FollowsLinkInLinksBlock() { JSONObject result = this.testSubject.jsonHal() .from("hal-traverson-builder-data.json") .follow("vegetables[name:turnip]") @@ -84,7 +79,7 @@ public void follows_GivenRelByPropertyMatchingBothLinksAndEmbedded_FollowsLinkIn } @Test - public void follows_GivenRelByProperty_FollowsLinkInEmbeddedBlock() { + void follows_GivenRelByProperty_FollowsLinkInEmbeddedBlock() { JSONObject result = this.testSubject.jsonHal() .from("hal-traverson-builder-data.json") .follow("ships[name:tug-boat]") @@ -95,7 +90,7 @@ public void follows_GivenRelByProperty_FollowsLinkInEmbeddedBlock() { } @Test - public void follows_GivenRelByPropertyThatIsNotAnArray_throwsException() throws Exception { + void follows_GivenRelByPropertyThatIsNotAnArray_throwsException() { try { this.testSubject.jsonHal() .from("hal-traverson-builder-data.json") @@ -110,7 +105,7 @@ public void follows_GivenRelByPropertyThatIsNotAnArray_throwsException() throws } @Test - public void follows_GivenRelByArrayMatchingBothLinksAndEmbedded_FollowsLinkInEmbeddedBlock() throws Exception { + void follows_GivenRelByArrayMatchingBothLinksAndEmbedded_FollowsLinkInEmbeddedBlock() { JSONObject result = this.testSubject.jsonHal() .from("hal-traverson-builder-data.json") .follow("vegetables[1]") @@ -121,7 +116,7 @@ public void follows_GivenRelByArrayMatchingBothLinksAndEmbedded_FollowsLinkInEmb } @Test - public void follows_GivenRelByArrayThatIsNotAnArray_throwsException() throws Exception { + void follows_GivenRelByArrayThatIsNotAnArray_throwsException() { try { this.testSubject.jsonHal() .from("hal-traverson-builder-data.json") @@ -136,7 +131,7 @@ public void follows_GivenRelByArrayThatIsNotAnArray_throwsException() throws Exc } @Test - public void follow_GivenSimpleRelThatMatchesNamePropertyOfSomethingInEmbeddedBlock_followsLink() throws Exception { + void follow_GivenSimpleRelThatMatchesNamePropertyOfSomethingInEmbeddedBlock_followsLink() { JSONObject result = this.testSubject.jsonHal() .from("hal-traverson-builder-data.json") .follow("tug-boat") @@ -150,7 +145,7 @@ private JSONObject getJsonResource(String resource) { try { return JSON.parseObject(Resources.toString(getResource(resource), Charsets.UTF_8)); } catch (IOException e) { - System.out.println(format("Failed to locate/read test resource '%s'", resource)); + System.out.printf("Failed to locate/read test resource '%s'%n", resource); return null; } } diff --git a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/TraversonBuilderTest.java b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/TraversonBuilderTest.java index 84b288c..aa48962 100644 --- a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/TraversonBuilderTest.java +++ b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/TraversonBuilderTest.java @@ -1,17 +1,16 @@ package uk.co.autotrader.traverson; -import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson2.JSONObject; import com.google.common.collect.ImmutableMap; import org.apache.commons.lang3.reflect.FieldUtils; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Assertions; +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.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import uk.co.autotrader.traverson.exception.IncompleteTraversalException; import uk.co.autotrader.traverson.http.*; import uk.co.autotrader.traverson.link.BasicLinkDiscoverer; @@ -27,8 +26,8 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; -@RunWith(MockitoJUnitRunner.class) -public class TraversonBuilderTest { +@ExtendWith(MockitoExtension.class) +class TraversonBuilderTest { private TraversonBuilder builder; @Mock private TraversonClient client; @@ -41,11 +40,9 @@ public class TraversonBuilderTest { @Mock private Deque relsToFollow; @Captor - private ArgumentCaptor> relsCaptor; + private ArgumentCaptor> relsCaptor; @Mock private LinkDiscoverer linkDiscoverer; - @Rule - public ExpectedException exception = ExpectedException.none(); @Mock public Response firstResponse; @Mock @@ -53,8 +50,8 @@ public class TraversonBuilderTest { @Mock public Response stringResponse; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { builder = new TraversonBuilder(client); FieldUtils.writeDeclaredField(builder, "linkDiscoverer", linkDiscoverer, true); } @@ -64,27 +61,27 @@ private Request reflectionGetRequest() throws IllegalAccessException { } @Test - public void from_SetsUrl() throws Exception { + void from_SetsUrl() throws Exception { assertThat(builder.from("http://localhost:8080")).isEqualTo(builder); assertThat(reflectionGetRequest().getUrl()).isEqualTo("http://localhost:8080"); } @Test - public void json_SetsAcceptTypeAndLinkDiscoverer() throws Exception { + void json_SetsAcceptTypeAndLinkDiscoverer() throws Exception { assertThat(builder.json()).isEqualTo(builder); assertThat(reflectionGetRequest().getAcceptMimeType()).isEqualTo("application/json"); assertThat(FieldUtils.readDeclaredField(builder, "linkDiscoverer", true)).isInstanceOf(BasicLinkDiscoverer.class); } @Test - public void jsoHal_SetsAcceptTypeAndLinkDiscoverer() throws Exception { + void jsoHal_SetsAcceptTypeAndLinkDiscoverer() throws Exception { assertThat(builder.jsonHal()).isEqualTo(builder); assertThat(reflectionGetRequest().getAcceptMimeType()).isEqualTo("application/hal+json"); assertThat(FieldUtils.readDeclaredField(builder, "linkDiscoverer", true)).isInstanceOf(HalLinkDiscoverer.class); } @Test - public void follow_ReplacesRels() throws Exception { + void follow_ReplacesRels() throws Exception { FieldUtils.writeField(builder, "relsToFollow", relsToFollow, true); builder.follow("A", "B", "C"); @@ -95,17 +92,18 @@ public void follow_ReplacesRels() throws Exception { } @Test - public void withQueryParam_IncrementallyAddsQueryParams() throws Exception { + void withQueryParam_IncrementallyAddsQueryParams() throws Exception { assertThat(builder.withQueryParam("key1", "value1")).isEqualTo(builder); assertThat(builder.withQueryParam("key2", "value2")).isEqualTo(builder); Map> queryParams = reflectionGetRequest().getQueryParameters(); - assertThat(queryParams).hasSize(2); - assertThat(queryParams).containsOnly(entry("key1", newArrayList("value1")), entry("key2", newArrayList("value2"))); + assertThat(queryParams) + .hasSize(2) + .containsOnly(entry("key1", newArrayList("value1")), entry("key2", newArrayList("value2"))); } @Test - public void withQueryParam_SetsQueryParams() throws Exception { + void withQueryParam_SetsQueryParams() throws Exception { assertThat(builder.withQueryParam("key1", "value1")).isEqualTo(builder); List value = newArrayList("value1"); @@ -114,7 +112,7 @@ public void withQueryParam_SetsQueryParams() throws Exception { } @Test - public void withQueryParam_AddsSingleQueryParamWithMultipleValues() throws Exception { + void withQueryParam_AddsSingleQueryParamWithMultipleValues() throws Exception { assertThat(builder.withQueryParam("key", "value1", "value2", "value3")).isEqualTo(builder); Map> queryParams = reflectionGetRequest().getQueryParameters(); assertThat(queryParams).hasSize(1); @@ -124,7 +122,7 @@ public void withQueryParam_AddsSingleQueryParamWithMultipleValues() throws Excep } @Test - public void withQueryParam_AddsQueryParamsForExistingKeysAndDoesNotOverwrite() throws Exception { + void withQueryParam_AddsQueryParamsForExistingKeysAndDoesNotOverwrite() throws Exception { builder.withQueryParam("key", "value1"); Map> queryParams = reflectionGetRequest().getQueryParameters(); @@ -138,7 +136,7 @@ public void withQueryParam_AddsQueryParamsForExistingKeysAndDoesNotOverwrite() t } @Test - public void withTemplateParam_IncrementallyAddsTemplateParams() throws Exception { + void withTemplateParam_IncrementallyAddsTemplateParams() throws Exception { assertThat(builder.withTemplateParam("key1", "value1")).isEqualTo(builder); assertThat(builder.withTemplateParam("key2", "value2")).isEqualTo(builder); Map> templateParams = reflectionGetRequest().getTemplateParams(); @@ -148,7 +146,7 @@ public void withTemplateParam_IncrementallyAddsTemplateParams() throws Exception } @Test - public void withTemplateParam_AddsSingleTemplateParamWithMultipleValues() throws Exception { + void withTemplateParam_AddsSingleTemplateParamWithMultipleValues() throws Exception { assertThat(builder.withTemplateParam("key", "value1", "value2", "value3")).isEqualTo(builder); Map> templateParams = reflectionGetRequest().getTemplateParams(); assertThat(templateParams).hasSize(1); @@ -158,7 +156,7 @@ public void withTemplateParam_AddsSingleTemplateParamWithMultipleValues() throws } @Test - public void withTemplateParam_SetsQueryParams() throws Exception { + void withTemplateParam_SetsQueryParams() throws Exception { assertThat(builder.withTemplateParam("key1", "value1")).isEqualTo(builder); Map> templateParams = Collections.singletonMap("key1", Arrays.asList("value1")); @@ -166,7 +164,7 @@ public void withTemplateParam_SetsQueryParams() throws Exception { } @Test - public void withTemplateParam_AddsTemplateParamsForExistingKeysAndDoesNotOverwrite() throws Exception { + void withTemplateParam_AddsTemplateParamsForExistingKeysAndDoesNotOverwrite() throws Exception { builder.withTemplateParam("key", "value1"); Map> templateParams = reflectionGetRequest().getTemplateParams(); @@ -180,7 +178,7 @@ public void withTemplateParam_AddsTemplateParamsForExistingKeysAndDoesNotOverwri } @Test - public void addHeader_IncrementallyAddsHeaders() throws Exception { + void addHeader_IncrementallyAddsHeaders() throws Exception { assertThat(builder.withHeader("key1", "value1")).isEqualTo(builder); assertThat(builder.withHeader("key2", "value2")).isEqualTo(builder); Map headers = reflectionGetRequest().getHeaders(); @@ -188,7 +186,7 @@ public void addHeader_IncrementallyAddsHeaders() throws Exception { } @Test - public void withHeaders_SetsHeaders() throws Exception { + void withHeaders_SetsHeaders() throws Exception { Map headers = new HashMap<>(); headers.put("key1", "value1"); assertThat(builder.withHeader("key1", "value1")).isEqualTo(builder); @@ -196,7 +194,7 @@ public void withHeaders_SetsHeaders() throws Exception { } @Test - public void withAuth_SetsCredentials() throws Exception { + void withAuth_SetsCredentials() throws Exception { assertThat(builder.withAuth("user", "password")).isEqualTo(builder); List authCredentials = reflectionGetRequest().getAuthCredentials(); @@ -209,7 +207,7 @@ public void withAuth_SetsCredentials() throws Exception { } @Test - public void withAuth_SetsCredentialsIncludingHostname() throws Exception { + void withAuth_SetsCredentialsIncludingHostname() throws Exception { assertThat(builder.withAuth("user", "password", "autotrader.co.uk")).isEqualTo(builder); List authCredentials = reflectionGetRequest().getAuthCredentials(); @@ -222,7 +220,7 @@ public void withAuth_SetsCredentialsIncludingHostname() throws Exception { } @Test - public void withAuth_SetsCredentialsIncludingPreemptiveAuthentication() throws Exception { + void withAuth_SetsCredentialsIncludingPreemptiveAuthentication() throws Exception { assertThat(builder.withAuth("user", "password", "autotrader.co.uk", true)).isEqualTo(builder); List authCredentials = reflectionGetRequest().getAuthCredentials(); @@ -235,7 +233,7 @@ public void withAuth_SetsCredentialsIncludingPreemptiveAuthentication() throws E } @Test - public void withAuth_AppendsCredentials() throws Exception { + void withAuth_AppendsCredentials() throws Exception { assertThat(builder.withAuth("user", "password", "autotrader.co.uk").withAuth("user2", "password2")).isEqualTo(builder); List authCredentials = reflectionGetRequest().getAuthCredentials(); @@ -250,7 +248,7 @@ public void withAuth_AppendsCredentials() throws Exception { } @Test - public void get_GivenInputs_BuildsRequestAndExecutes() throws Exception { + void get_GivenInputs_BuildsRequestAndExecutes() throws Exception { when(client.execute(any(Request.class), eq(JSONObject.class))).thenReturn(firstResponse); Response response = builder.get(); @@ -262,7 +260,7 @@ public void get_GivenInputs_BuildsRequestAndExecutes() throws Exception { } @Test - public void post_GivenInputs_BuildsRequestAndExecutes() throws Exception { + void post_GivenInputs_BuildsRequestAndExecutes() throws Exception { when(client.execute(any(Request.class), eq(JSONObject.class))).thenReturn(firstResponse); Response response = builder.post(body); @@ -274,7 +272,7 @@ public void post_GivenInputs_BuildsRequestAndExecutes() throws Exception { } @Test - public void post_GivenInputsAndReturnType_BuildsRequestAndExecutes() throws Exception { + void post_GivenInputsAndReturnType_BuildsRequestAndExecutes() throws Exception { when(client.execute(any(Request.class), eq(String.class))).thenReturn(stringResponse); Response response = builder.post(body, String.class); @@ -286,7 +284,7 @@ public void post_GivenInputsAndReturnType_BuildsRequestAndExecutes() throws Exce } @Test - public void put_GivenInputs_BuildsRequestAndExecutes() throws Exception { + void put_GivenInputs_BuildsRequestAndExecutes() throws Exception { when(client.execute(any(Request.class), eq(JSONObject.class))).thenReturn(firstResponse); Response response = builder.put(body); @@ -298,7 +296,7 @@ public void put_GivenInputs_BuildsRequestAndExecutes() throws Exception { } @Test - public void put_GivenInputsAndReturnType_BuildsRequestAndExecutes() throws Exception { + void put_GivenInputsAndReturnType_BuildsRequestAndExecutes() throws Exception { when(client.execute(any(Request.class), eq(String.class))).thenReturn(stringResponse); Response response = builder.put(body, String.class); @@ -310,7 +308,7 @@ public void put_GivenInputsAndReturnType_BuildsRequestAndExecutes() throws Excep } @Test - public void patch_GivenInputs_BuildsRequestAndExecutes() throws Exception { + void patch_GivenInputs_BuildsRequestAndExecutes() throws Exception { when(client.execute(any(Request.class), eq(JSONObject.class))).thenReturn(firstResponse); Response response = builder.patch(body); @@ -323,7 +321,7 @@ public void patch_GivenInputs_BuildsRequestAndExecutes() throws Exception { @Test - public void patch_GivenInputsAndReturnType_BuildsRequestAndExecutes() throws Exception { + void patch_GivenInputsAndReturnType_BuildsRequestAndExecutes() throws Exception { when(client.execute(any(Request.class), eq(String.class))).thenReturn(stringResponse); Response response = builder.patch(body, String.class); @@ -335,7 +333,7 @@ public void patch_GivenInputsAndReturnType_BuildsRequestAndExecutes() throws Exc } @Test - public void delete_GivenInputs_BuildsRequestAndExecutes() throws Exception { + void delete_GivenInputs_BuildsRequestAndExecutes() throws Exception { when(client.execute(any(Request.class), eq(JSONObject.class))).thenReturn(firstResponse); Response response = builder.delete(); @@ -347,7 +345,7 @@ public void delete_GivenInputs_BuildsRequestAndExecutes() throws Exception { } @Test - public void delete_GivenInputsAndReturnType_BuildsRequestAndExecutes() throws Exception { + void delete_GivenInputsAndReturnType_BuildsRequestAndExecutes() throws Exception { when(client.execute(any(Request.class), eq(String.class))).thenReturn(stringResponse); Response response = builder.delete(String.class); @@ -359,7 +357,7 @@ public void delete_GivenInputsAndReturnType_BuildsRequestAndExecutes() throws Ex } @Test - public void get_GivenRelToFollow_NavigatesToLastRelThenPerformsMethod() throws Exception { + void get_GivenRelToFollow_NavigatesToLastRelThenPerformsMethod() throws Exception { when(firstResponse.isSuccessful()).thenReturn(true); when(firstResponse.getResource()).thenReturn(resource); when(client.execute(reflectionGetRequest(), JSONObject.class)).thenReturn(firstResponse).thenReturn(secondResponse); @@ -375,7 +373,7 @@ public void get_GivenRelToFollow_NavigatesToLastRelThenPerformsMethod() throws E @Test - public void post_GivenRelToFollow_NavigatesToLastRelThenPerformsMethod() throws Exception { + void post_GivenRelToFollow_NavigatesToLastRelThenPerformsMethod() throws Exception { when(firstResponse.isSuccessful()).thenReturn(true); when(firstResponse.getResource()).thenReturn(resource); when(client.execute(reflectionGetRequest(), JSONObject.class)).thenReturn(firstResponse).thenReturn(secondResponse); @@ -390,7 +388,7 @@ public void post_GivenRelToFollow_NavigatesToLastRelThenPerformsMethod() throws } @Test - public void put_GivenRelToFollow_NavigatesToLastRelThenPerformsMethod() throws Exception { + void put_GivenRelToFollow_NavigatesToLastRelThenPerformsMethod() throws Exception { when(firstResponse.isSuccessful()).thenReturn(true); when(firstResponse.getResource()).thenReturn(resource); when(client.execute(reflectionGetRequest(), JSONObject.class)).thenReturn(firstResponse).thenReturn(secondResponse); @@ -405,7 +403,7 @@ public void put_GivenRelToFollow_NavigatesToLastRelThenPerformsMethod() throws E } @Test - public void patch_GivenRelToFollow_NavigatesToLastRelThenPerformsMethod() throws Exception { + void patch_GivenRelToFollow_NavigatesToLastRelThenPerformsMethod() throws Exception { when(firstResponse.isSuccessful()).thenReturn(true); when(firstResponse.getResource()).thenReturn(resource); when(client.execute(reflectionGetRequest(), JSONObject.class)).thenReturn(firstResponse).thenReturn(secondResponse); @@ -420,7 +418,7 @@ public void patch_GivenRelToFollow_NavigatesToLastRelThenPerformsMethod() throws } @Test - public void delete_GivenRelToFollow_NavigatesToLastRelThenPerformsMethod() throws Exception { + void delete_GivenRelToFollow_NavigatesToLastRelThenPerformsMethod() throws Exception { when(firstResponse.isSuccessful()).thenReturn(true); when(firstResponse.getResource()).thenReturn(resource); when(client.execute(reflectionGetRequest(), JSONObject.class)).thenReturn(firstResponse).thenReturn(secondResponse); @@ -435,19 +433,20 @@ public void delete_GivenRelToFollow_NavigatesToLastRelThenPerformsMethod() throw } @Test - public void get_GivenRelToFollow_ThrowsExceptionWhenANonSuccessfulResponseIsReturnedMidwayThroughTraversing() throws Exception { + void get_GivenRelToFollow_ThrowsExceptionWhenANonSuccessfulResponseIsReturnedMidwayThroughTraversing() throws Exception { when(firstResponse.getUri()).thenReturn(URI.create("http://brokenurl.com/not_found")); when(firstResponse.isSuccessful()).thenReturn(false); when(firstResponse.getStatusCode()).thenReturn(404); when(client.execute(reflectionGetRequest(), JSONObject.class)).thenReturn(firstResponse); - exception.expect(IncompleteTraversalException.class); - exception.expectMessage("Received status code 404 from url http://brokenurl.com/not_found"); - Response response = builder.from("http://localhost/").follow("rel").get(); + IncompleteTraversalException exception = Assertions.assertThrows(IncompleteTraversalException.class, () -> { + Response response = builder.from("http://localhost/").follow("rel").get(); + assertThat(response).isEqualTo(firstResponse); + }); + assertThat(exception.getMessage()).isEqualTo("Received status code 404 from url http://brokenurl.com/not_found"); Request request = reflectionGetRequest(); verify(client, times(1)).execute(request, JSONObject.class); - assertThat(response).isEqualTo(firstResponse); assertThat(request.getUrl()).isEqualTo("http://localhost/"); assertThat(request.getMethod()).isEqualTo(Method.GET); verifyNoInteractions(linkDiscoverer); diff --git a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/TraversonTest.java b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/TraversonTest.java index abbe372..264527c 100644 --- a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/TraversonTest.java +++ b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/TraversonTest.java @@ -2,19 +2,19 @@ import org.apache.commons.lang3.reflect.FieldUtils; -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.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import uk.co.autotrader.traverson.http.Request; import uk.co.autotrader.traverson.http.TraversonClient; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(MockitoJUnitRunner.class) -public class TraversonTest { +@ExtendWith(MockitoExtension.class) +class TraversonTest { @Mock private TraversonClient traversonClient; @@ -22,7 +22,7 @@ public class TraversonTest { private ArgumentCaptor requestCaptor; @Test - public void from_GivenUrl_ReturnsTraversonBuilder() throws Exception { + void from_GivenUrl_ReturnsTraversonBuilder() throws Exception { Traverson traverson = new Traverson(traversonClient); TraversonBuilder builder = traverson.from("https://localhost:8080"); diff --git a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/conversion/ByteArrayConverterTest.java b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/conversion/ByteArrayConverterTest.java index d3d6604..d1d88b4 100644 --- a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/conversion/ByteArrayConverterTest.java +++ b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/conversion/ByteArrayConverterTest.java @@ -1,7 +1,7 @@ package uk.co.autotrader.traverson.conversion; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import uk.co.autotrader.traverson.exception.ConversionException; @@ -14,21 +14,21 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -public class ByteArrayConverterTest { +class ByteArrayConverterTest { private ByteArrayConverter converter; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() { converter = new ByteArrayConverter(); } @Test - public void getDestinationType_ReturnsByteArrayClass() throws Exception { + void getDestinationType_ReturnsByteArrayClass() { assertThat(converter.getDestinationType()).isEqualTo(byte[].class); } @Test - public void convert_ReturnsTheInputString() throws Exception { + void convert_ReturnsTheInputString() throws Exception { byte[] bytes = new byte[] {1, 2, 3}; InputStream inputStream = Mockito.spy(new ByteArrayInputStream(bytes)); @@ -37,7 +37,7 @@ public void convert_ReturnsTheInputString() throws Exception { } @Test - public void convert_WrapsIOExceptionInConversionException() throws Exception { + void convert_WrapsIOExceptionInConversionException() throws Exception { InputStream inputStream = Mockito.mock(InputStream.class); when(inputStream.readAllBytes()).thenThrow(new IOException()); diff --git a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/conversion/FastJsonResourceConverterTest.java b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/conversion/FastJsonResourceConverterTest.java index 2bda9e7..5c16792 100644 --- a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/conversion/FastJsonResourceConverterTest.java +++ b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/conversion/FastJsonResourceConverterTest.java @@ -1,10 +1,10 @@ package uk.co.autotrader.traverson.conversion; -import com.alibaba.fastjson.JSONException; -import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson2.JSONException; +import com.alibaba.fastjson2.JSONObject; import org.assertj.core.data.MapEntry; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import uk.co.autotrader.traverson.exception.ConversionException; import java.io.ByteArrayInputStream; @@ -14,23 +14,23 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -public class FastJsonResourceConverterTest { +class FastJsonResourceConverterTest { private FastJsonResourceConverter converter; - @Before - public void setUp() { + @BeforeEach + void setUp() { converter = new FastJsonResourceConverter(); } @Test - public void getDestinationType_ReturnsJSONObject() { + void getDestinationType_ReturnsJSONObject() { assertThat(converter.getDestinationType()).isEqualTo(JSONObject.class); } @Test - public void convert_GivenJsonString_ParsesJsonCorrectly() { - String resourceAsString = "{'name':'test', 'anotherName':'comes before the first one alphabetically'}"; + void convert_GivenJsonString_ParsesJsonCorrectly() { + String resourceAsString = "{\"name\":\"test\", \"anotherName\":\"comes before the first one alphabetically\"}"; JSONObject resource = converter.convert(toInputStream(resourceAsString), JSONObject.class); @@ -38,7 +38,7 @@ public void convert_GivenJsonString_ParsesJsonCorrectly() { } @Test - public void convert_GivenXMLString_ThrowsConversionException() { + void convert_GivenXMLString_ThrowsConversionException() { final String resourceAsString = "<_links>http://localhost"; assertThatThrownBy(() -> converter.convert(toInputStream(resourceAsString), JSONObject.class)) @@ -51,7 +51,7 @@ public void convert_GivenXMLString_ThrowsConversionException() { } @Test - public void convert_GivenEmptyString_ReturnNull() { + void convert_GivenEmptyJson_ReturnNull() { String resourceAsString = ""; JSONObject resource = converter.convert(toInputStream(resourceAsString), JSONObject.class); @@ -60,7 +60,7 @@ public void convert_GivenEmptyString_ReturnNull() { } @Test - public void convert_GivenNullString_ReturnNull() { + void convert_GivenEmptyString_ReturnNull() { String resourceAsString = ""; JSONObject resource = converter.convert(toInputStream(resourceAsString), JSONObject.class); diff --git a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/conversion/InputStreamConverterTest.java b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/conversion/InputStreamConverterTest.java index 6bb1082..22c6ad3 100644 --- a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/conversion/InputStreamConverterTest.java +++ b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/conversion/InputStreamConverterTest.java @@ -1,28 +1,28 @@ package uk.co.autotrader.traverson.conversion; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.io.InputStream; import static org.assertj.core.api.Assertions.assertThat; -public class InputStreamConverterTest { +class InputStreamConverterTest { private InputStreamConverter converter; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() { converter = new InputStreamConverter(); } @Test - public void getDestinationType_ReturnsInputStreamClass() { + void getDestinationType_ReturnsInputStreamClass() { assertThat(converter.getDestinationType()).isEqualTo(InputStream.class); } @Test - public void convert_ReturnsInputStreamAsIs() { + void convert_ReturnsInputStreamAsIs() { InputStream expectedStream = Mockito.mock(InputStream.class); assertThat(converter.convert(expectedStream, InputStream.class)).isSameAs(expectedStream); diff --git a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/conversion/ResourceConversionServiceTest.java b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/conversion/ResourceConversionServiceTest.java index 9e8add1..487e121 100644 --- a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/conversion/ResourceConversionServiceTest.java +++ b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/conversion/ResourceConversionServiceTest.java @@ -1,13 +1,11 @@ package uk.co.autotrader.traverson.conversion; -import com.alibaba.fastjson.JSONObject; -import org.hamcrest.CoreMatchers; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; +import com.alibaba.fastjson2.JSONObject; +import org.junit.jupiter.api.Assertions; +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; import uk.co.autotrader.traverson.exception.ConversionException; import java.io.ByteArrayInputStream; @@ -19,12 +17,10 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class ResourceConversionServiceTest { +@ExtendWith(MockitoExtension.class) +class ResourceConversionServiceTest { private final ResourceConversionService service = ResourceConversionService.getInstance(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); @Mock private ResourceConverter converter; @Mock @@ -33,7 +29,7 @@ public class ResourceConversionServiceTest { private InputStream inputStream; @Test - public void init_EnsuresThatTheDefaultConvertersAreRegistered() { + void init_EnsuresThatTheDefaultConvertersAreRegistered() { Map, ResourceConverter> converters = service.getConvertersByClass(); assertThat(converters).isNotEmpty(); @@ -41,16 +37,17 @@ public void init_EnsuresThatTheDefaultConvertersAreRegistered() { } @Test - public void convert_GivenUnsupportedResponseType_ThrowsException() { - expectedException.expect(ConversionException.class); - expectedException.expectCause(CoreMatchers.nullValue(Throwable.class)); - expectedException.expectMessage("Unsupported return type of uk.co.autotrader.traverson.conversion.UnsupportedType"); + void convert_GivenUnsupportedResponseType_ThrowsException() { + ConversionException exception = Assertions.assertThrows(ConversionException.class, () -> { + service.convert(inputStream, UnsupportedType.class); + }); - service.convert(inputStream, UnsupportedType.class); + assertThat(exception.getCause()).isNull(); + assertThat(exception.getMessage()).isEqualTo("Unsupported return type of uk.co.autotrader.traverson.conversion.UnsupportedType"); } @Test - public void addConverter_RegistersTheConverterForUseLater() { + void addConverter_RegistersTheConverterForUseLater() { SupportedType result = service.convert(inputStream, SupportedType.class); @@ -59,8 +56,8 @@ public void addConverter_RegistersTheConverterForUseLater() { } @Test - public void convert_GivenRequestForFastJSON_EnsuresTheFastJsonConverterIsLoaded() { - String resourceAsString = "{'name':'test'}"; + void convert_GivenRequestForFastJSON_EnsuresTheFastJsonConverterIsLoaded() { + String resourceAsString = "{\"name\":\"test\"}"; JSONObject resource = service.convert(toInputStream(resourceAsString), JSONObject.class); @@ -69,7 +66,7 @@ public void convert_GivenRequestForFastJSON_EnsuresTheFastJsonConverterIsLoaded( @Test - public void convert_GivenRequestForString_EnsuresTheStringConverterIsLoaded() { + void convert_GivenRequestForString_EnsuresTheStringConverterIsLoaded() { String resourceAsString = "{'name':'test'}"; String resource = service.convert(toInputStream(resourceAsString), String.class); @@ -77,7 +74,7 @@ public void convert_GivenRequestForString_EnsuresTheStringConverterIsLoaded() { } @Test - public void convert_GivenRequestForByteArray_EnsuresTheStringConverterIsLoaded() { + void convert_GivenRequestForByteArray_EnsuresTheStringConverterIsLoaded() { byte[] bytes = new byte[] {0, 1, 2, 3}; ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); @@ -87,7 +84,7 @@ public void convert_GivenRequestForByteArray_EnsuresTheStringConverterIsLoaded() } @Test - public void convert_GivenTheConvertersAreLoadedInAnyOrder_TheConversionServiceWillTraverseTheClassHierarchyUntilAMatch() { + void convert_GivenTheConvertersAreLoadedInAnyOrder_TheConversionServiceWillTraverseTheClassHierarchyUntilAMatch() { String resourceAsString = "1234"; InputStream resourceStream = toInputStream(resourceAsString); when(failingConverter.getDestinationType()).thenReturn(Object.class); diff --git a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/conversion/StringResourceConverterTest.java b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/conversion/StringResourceConverterTest.java index 355688b..2a79b62 100644 --- a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/conversion/StringResourceConverterTest.java +++ b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/conversion/StringResourceConverterTest.java @@ -1,7 +1,7 @@ package uk.co.autotrader.traverson.conversion; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import uk.co.autotrader.traverson.exception.ConversionException; @@ -15,22 +15,22 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -public class StringResourceConverterTest { +class StringResourceConverterTest { private StringResourceConverter converter; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() { converter = new StringResourceConverter(); } @Test - public void getDestinationType_ReturnsString() throws Exception { + void getDestinationType_ReturnsString() { assertThat(converter.getDestinationType()).isEqualTo(String.class); } @Test - public void convert_ReturnsTheInputString() throws Exception { + void convert_ReturnsTheInputString() throws Exception { String resourceAsString = "My Resource"; InputStream inputStream = Mockito.spy(new ByteArrayInputStream(resourceAsString.getBytes(StandardCharsets.UTF_8))); @@ -39,7 +39,7 @@ public void convert_ReturnsTheInputString() throws Exception { } @Test - public void convert_WrapsIOExceptionInConversionException() throws Exception { + void convert_WrapsIOExceptionInConversionException() throws Exception { InputStream inputStream = Mockito.mock(InputStream.class); when(inputStream.readAllBytes()).thenThrow(new IOException()); diff --git a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/exception/HttpExceptionTest.java b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/exception/HttpExceptionTest.java index 6c330a6..bece104 100644 --- a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/exception/HttpExceptionTest.java +++ b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/exception/HttpExceptionTest.java @@ -1,15 +1,15 @@ package uk.co.autotrader.traverson.exception; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; import static org.assertj.core.api.Assertions.assertThat; -public class HttpExceptionTest { +class HttpExceptionTest { @Test - public void init_OverridesMessageAndCauseConstructor() throws Exception { + void init_OverridesMessageAndCauseConstructor() { IOException cause = new IOException(); HttpException exception = new HttpException("My Message", cause); diff --git a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/exception/IllegalHttpStatusExceptionTest.java b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/exception/IllegalHttpStatusExceptionTest.java index 9c82474..4eac10e 100644 --- a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/exception/IllegalHttpStatusExceptionTest.java +++ b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/exception/IllegalHttpStatusExceptionTest.java @@ -1,16 +1,16 @@ package uk.co.autotrader.traverson.exception; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.net.URI; import static org.assertj.core.api.Assertions.assertThat; -public class IllegalHttpStatusExceptionTest { +class IllegalHttpStatusExceptionTest { @Test - public void init_SetsStatusAndUriFields() throws Exception { + void init_SetsStatusAndUriFields() { URI uri = URI.create("http://localhost"); IllegalHttpStatusException exception = new IllegalHttpStatusException(404, uri); diff --git a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/http/FormBodyTest.java b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/http/FormBodyTest.java index a768437..f48a51f 100644 --- a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/http/FormBodyTest.java +++ b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/http/FormBodyTest.java @@ -1,17 +1,17 @@ package uk.co.autotrader.traverson.http; import com.google.common.base.Charsets; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.junit.MockitoJUnitRunner; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.junit.jupiter.MockitoExtension; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(MockitoJUnitRunner.class) -public class FormBodyTest { +@ExtendWith(MockitoExtension.class) +class FormBodyTest { @Test - public void init_GivenValues_SetsProperties() { + void init_GivenValues_SetsProperties() { FormDataBody body = new FormDataBody(Charsets.UTF_8, new FormDataBody.NameValuePair("name", "value")); diff --git a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/http/ResponseTest.java b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/http/ResponseTest.java index ea724ab..6c08db7 100644 --- a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/http/ResponseTest.java +++ b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/http/ResponseTest.java @@ -1,27 +1,38 @@ package uk.co.autotrader.traverson.http; -import com.alibaba.fastjson.JSONObject; -import org.junit.Test; -import org.junit.runner.RunWith; +import com.alibaba.fastjson2.JSONObject; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.net.URI; import java.util.Map; +import java.util.stream.Stream; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(MockitoJUnitRunner.class) -public class ResponseTest { +@ExtendWith(MockitoExtension.class) +class ResponseTest { @Mock private Map headers; + private static Stream unsuccessfulStatusCodes() { + return Stream.of( + Arguments.of(500), + Arguments.of(404), + Arguments.of(302)); + } + @Test - public void pojo() throws Exception { + void pojo() { URI uri = URI.create("http://localhost"); JSONObject resource = new JSONObject(); - Response response = new Response(); + Response response = new Response<>(); response.setResource(resource); response.setStatusCode(200); response.setUri(uri); @@ -33,32 +44,17 @@ public void pojo() throws Exception { assertThat(response.getResponseHeaders()).isEqualTo(headers); } - @Test - public void isSuccessful_Given500StatusCode_ReturnsFalse() throws Exception { - Response response = new Response(); - response.setStatusCode(500); - - assertThat(response.isSuccessful()).isFalse(); - } - - @Test - public void isSuccessful_Given404StatusCode_ReturnsFalse() { - Response response = new Response(); - response.setStatusCode(404); - - assertThat(response.isSuccessful()).isFalse(); - } - - @Test - public void isSuccessful_Given302StatusCode_ReturnsFalse() { + @ParameterizedTest(name = "given{0}StatusCode_isSuccessfulReturnsFalse") + @MethodSource("unsuccessfulStatusCodes") + void isSuccessful_GivenUnsuccessfulStatusCode_ReturnsFalse(int statusCode) { Response response = new Response(); - response.setStatusCode(302); + response.setStatusCode(statusCode); assertThat(response.isSuccessful()).isFalse(); } @Test - public void isSuccessful_Given201StatusCode_ReturnsTrue() { + void isSuccessful_Given201StatusCode_ReturnsTrue() { Response response = new Response(); response.setStatusCode(201); @@ -66,7 +62,7 @@ public void isSuccessful_Given201StatusCode_ReturnsTrue() { } @Test - public void addResponseHeader_AppendsTheUniqueHeaders() { + void addResponseHeader_AppendsTheUniqueHeaders() { Response response = new Response(); response.addResponseHeader("key1", "value1"); response.addResponseHeader("key2", "value2"); diff --git a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/http/TextBodyTest.java b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/http/TextBodyTest.java index 9e1cb4b..e2ddc83 100644 --- a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/http/TextBodyTest.java +++ b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/http/TextBodyTest.java @@ -1,17 +1,17 @@ package uk.co.autotrader.traverson.http; import com.google.common.base.Charsets; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.junit.MockitoJUnitRunner; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.junit.jupiter.MockitoExtension; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(MockitoJUnitRunner.class) -public class TextBodyTest { +@ExtendWith(MockitoExtension.class) +class TextBodyTest { @Test - public void init_GivenValues_SetsProperties() throws Exception { + void init_GivenValues_SetsProperties() { TextBody body = new TextBody("data", "contentType", Charsets.UTF_8); assertThat(body.getContent()).isEqualTo("data"); @@ -20,7 +20,7 @@ public void init_GivenValues_SetsProperties() throws Exception { } @Test - public void legacyinit_GivenValues_SetsProperties() throws Exception { + void legacyinit_GivenValues_SetsProperties() { TextBody body = new TextBody("data", "contentType"); assertThat(body.getContent()).isEqualTo("data"); diff --git a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/http/multipart/BodyPartTest.java b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/http/multipart/BodyPartTest.java index b8260b7..e02a8aa 100644 --- a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/http/multipart/BodyPartTest.java +++ b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/http/multipart/BodyPartTest.java @@ -1,18 +1,18 @@ package uk.co.autotrader.traverson.http.multipart; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.junit.MockitoJUnitRunner; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.junit.jupiter.MockitoExtension; import uk.co.autotrader.traverson.http.SimpleMultipartBody; import java.nio.charset.StandardCharsets; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(MockitoJUnitRunner.class) -public class BodyPartTest { +@ExtendWith(MockitoExtension.class) +class BodyPartTest { @Test - public void init_GivenValues_SetsProperties() { + void init_GivenValues_SetsProperties() { SimpleMultipartBody.BodyPart multipart = new SimpleMultipartBody.BodyPart("name", "data".getBytes(StandardCharsets.UTF_8), "contentType", "filename"); assertThat(multipart.getName()).isEqualTo("name"); diff --git a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/http/multipart/SimpleMultipartBodyTest.java b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/http/multipart/SimpleMultipartBodyTest.java index 9ddee74..b3647f7 100644 --- a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/http/multipart/SimpleMultipartBodyTest.java +++ b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/http/multipart/SimpleMultipartBodyTest.java @@ -1,23 +1,23 @@ package uk.co.autotrader.traverson.http.multipart; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.junit.MockitoJUnitRunner; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.junit.jupiter.MockitoExtension; import uk.co.autotrader.traverson.http.SimpleMultipartBody; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; -@RunWith(MockitoJUnitRunner.class) -public class SimpleMultipartBodyTest { +@ExtendWith(MockitoExtension.class) +class SimpleMultipartBodyTest { @Test - public void getContentType_ReturnsNull() { + void getContentType_ReturnsNull() { assertThat(new SimpleMultipartBody().getContentType()).isNull(); } @Test - public void init_GivenValues_SetsProperties() { + void init_GivenValues_SetsProperties() { SimpleMultipartBody.BodyPart[] bodyParts = new SimpleMultipartBody.BodyPart[]{mock(SimpleMultipartBody.BodyPart.class), mock(SimpleMultipartBody.BodyPart.class)}; SimpleMultipartBody body = new SimpleMultipartBody(bodyParts); diff --git a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/link/BasicLinkDiscovererTest.java b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/link/BasicLinkDiscovererTest.java index 2ab5b5e..95a16aa 100644 --- a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/link/BasicLinkDiscovererTest.java +++ b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/link/BasicLinkDiscovererTest.java @@ -1,30 +1,30 @@ package uk.co.autotrader.traverson.link; -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson2.JSON; +import com.alibaba.fastjson2.JSONObject; import com.google.common.io.Resources; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.junit.MockitoJUnitRunner; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.junit.jupiter.MockitoExtension; import uk.co.autotrader.traverson.exception.UnknownRelException; import java.nio.charset.Charset; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; -@RunWith(MockitoJUnitRunner.class) -public class BasicLinkDiscovererTest { +@ExtendWith(MockitoExtension.class) +class BasicLinkDiscovererTest { private LinkDiscoverer linkDiscoverer; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() { linkDiscoverer = new BasicLinkDiscoverer(); } @Test - public void findHref_GivenBasicHypermediaResource_ReturnsHref() throws Exception { + void findHref_GivenBasicHypermediaResource_ReturnsHref() throws Exception { String fileContents = Resources.toString(Resources.getResource("basic-hypermedia-simple.json"), Charset.defaultCharset()); JSONObject json = JSON.parseObject(fileContents); @@ -34,7 +34,7 @@ public void findHref_GivenBasicHypermediaResource_ReturnsHref() throws Exception } @Test - public void findHref_GivenBasicHypermediaResourceAndRelNotExisting_ThrowsException() throws Exception { + void findHref_GivenBasicHypermediaResourceAndRelNotExisting_ThrowsException() throws Exception { String fileContents = Resources.toString(Resources.getResource("basic-hypermedia-simple.json"), Charset.defaultCharset()); JSONObject json = JSON.parseObject(fileContents); diff --git a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/link/HalLinkDiscovererTest.java b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/link/HalLinkDiscovererTest.java index 2abd810..1d9b53f 100644 --- a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/link/HalLinkDiscovererTest.java +++ b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/link/HalLinkDiscovererTest.java @@ -1,13 +1,13 @@ package uk.co.autotrader.traverson.link; -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson2.JSON; +import com.alibaba.fastjson2.JSONObject; import com.google.common.io.Resources; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.junit.MockitoJUnitRunner; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.junit.jupiter.MockitoExtension; import uk.co.autotrader.traverson.exception.UnknownRelException; import uk.co.autotrader.traverson.link.hal.HalLinkDiscoverer; @@ -16,19 +16,19 @@ import static com.google.common.io.Resources.getResource; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; -@RunWith(MockitoJUnitRunner.class) -public class HalLinkDiscovererTest { +@ExtendWith(MockitoExtension.class) +class HalLinkDiscovererTest { private LinkDiscoverer linkDiscoverer; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() { this.linkDiscoverer = new HalLinkDiscoverer(); } @Test - public void findHref_GivenHalResource_ReturnsSelfHref() throws Exception { + void findHref_GivenHalResource_ReturnsSelfHref() throws Exception { JSONObject json = getJsonResource("hal-simple.json"); String url = this.linkDiscoverer.findHref(json, "self"); @@ -37,7 +37,7 @@ public void findHref_GivenHalResource_ReturnsSelfHref() throws Exception { } @Test - public void findHref_GivenRelDoesntExist_ThrowsUnknownRelException() throws Exception { + void findHref_GivenRelDoesntExist_ThrowsUnknownRelException() throws Exception { JSONObject json = getJsonResource("hal-simple.json"); try { @@ -50,7 +50,7 @@ public void findHref_GivenRelDoesntExist_ThrowsUnknownRelException() throws Exce } @Test - public void findHref_GivenHalResourceAndDomainsRel_ReturnsDomainsHref() throws Exception { + void findHref_GivenHalResourceAndDomainsRel_ReturnsDomainsHref() throws Exception { JSONObject json = getJsonResource("hal-simple.json"); String url = this.linkDiscoverer.findHref(json, "domains"); @@ -59,7 +59,7 @@ public void findHref_GivenHalResourceAndDomainsRel_ReturnsDomainsHref() throws E } @Test - public void findHref_GivenHalResourceWithEmbedded_ReturnsSelfHrefForFirstItemMatchedByName() throws Exception { + void findHref_GivenHalResourceWithEmbedded_ReturnsSelfHrefForFirstItemMatchedByName() throws Exception { JSONObject json = getJsonResource("hal-embedded.json"); String url = this.linkDiscoverer.findHref(json, "AutoTrader"); @@ -68,7 +68,7 @@ public void findHref_GivenHalResourceWithEmbedded_ReturnsSelfHrefForFirstItemMat } @Test - public void findHref_GivenHalResourceWithEmbeddedAndRelDoesNotMatchNamedItem_ReturnsSelfHrefFromRootLinks() throws Exception { + void findHref_GivenHalResourceWithEmbeddedAndRelDoesNotMatchNamedItem_ReturnsSelfHrefFromRootLinks() throws Exception { JSONObject json = getJsonResource("hal-embedded.json"); String url = this.linkDiscoverer.findHref(json, "self"); @@ -77,7 +77,7 @@ public void findHref_GivenHalResourceWithEmbeddedAndRelDoesNotMatchNamedItem_Ret } @Test - public void findHref_GivenHalResourceWithEmptyEmbedded_ReturnsSelfHrefFromRootLinks() throws Exception { + void findHref_GivenHalResourceWithEmptyEmbedded_ReturnsSelfHrefFromRootLinks() throws Exception { JSONObject json = getJsonResource("hal-empty-embedded.json"); String url = this.linkDiscoverer.findHref(json, "self"); @@ -86,7 +86,7 @@ public void findHref_GivenHalResourceWithEmptyEmbedded_ReturnsSelfHrefFromRootLi } @Test - public void findHref_GivenHalResourceWithLinkArray_ReturnsMatchingHrefFromArray() throws Exception { + void findHref_GivenHalResourceWithLinkArray_ReturnsMatchingHrefFromArray() throws Exception { JSONObject json = getJsonResource("hal-keyed-link-rels.json"); String url = this.linkDiscoverer.findHref(json, "section[name:turnip]"); @@ -95,7 +95,7 @@ public void findHref_GivenHalResourceWithLinkArray_ReturnsMatchingHrefFromArray( } @Test - public void findHref_GivenPropertyBasedRelDoesntExist_throwsException() throws Exception { + void findHref_GivenPropertyBasedRelDoesntExist_throwsException() throws Exception { JSONObject json = getJsonResource("hal-traverson-builder-data.json"); try { @@ -109,7 +109,7 @@ public void findHref_GivenPropertyBasedRelDoesntExist_throwsException() throws E } @Test - public void findHref_GivenHalResourceWithLinkArrayIndex_ReturnsMatchingHrefFromArray() throws Exception { + void findHref_GivenHalResourceWithLinkArrayIndex_ReturnsMatchingHrefFromArray() throws Exception { JSONObject json = getJsonResource("hal-keyed-link-rels.json"); String url = this.linkDiscoverer.findHref(json, "section[1]"); @@ -118,7 +118,7 @@ public void findHref_GivenHalResourceWithLinkArrayIndex_ReturnsMatchingHrefFromA } @Test - public void findHref_GivenNonExistentArrayIndex_throwsException() throws Exception { + void findHref_GivenNonExistentArrayIndex_throwsException() throws Exception { JSONObject json = getJsonResource("hal-traverson-builder-data.json"); try { diff --git a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/link/hal/EmbeddedArrayNameHandlerTest.java b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/link/hal/EmbeddedArrayNameHandlerTest.java index f632010..0309a13 100644 --- a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/link/hal/EmbeddedArrayNameHandlerTest.java +++ b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/link/hal/EmbeddedArrayNameHandlerTest.java @@ -1,29 +1,29 @@ package uk.co.autotrader.traverson.link.hal; -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson2.JSON; +import com.alibaba.fastjson2.JSONObject; import com.google.common.io.Resources; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.junit.MockitoJUnitRunner; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.junit.jupiter.MockitoExtension; import java.nio.charset.Charset; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(MockitoJUnitRunner.class) -public class EmbeddedArrayNameHandlerTest { +@ExtendWith(MockitoExtension.class) +class EmbeddedArrayNameHandlerTest { private EmbeddedArrayNameHandler handler; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() { this.handler = new EmbeddedArrayNameHandler(); } @Test - public void findRef_GivenNamedEntityExists_ReturnsSelfLinkOfUrl() throws Exception { + void findRef_GivenNamedEntityExists_ReturnsSelfLinkOfUrl() throws Exception { String fileContents = Resources.toString(Resources.getResource("hal-embedded.json"), Charset.defaultCharset()); JSONObject json = JSON.parseObject(fileContents); @@ -33,7 +33,7 @@ public void findRef_GivenNamedEntityExists_ReturnsSelfLinkOfUrl() throws Excepti } @Test - public void findRef_GivenNameOfEntityThatDoesNotExist_ReturnsNull() throws Exception { + void findRef_GivenNameOfEntityThatDoesNotExist_ReturnsNull() throws Exception { String fileContents = Resources.toString(Resources.getResource("hal-embedded.json"), Charset.defaultCharset()); JSONObject json = JSON.parseObject(fileContents); @@ -43,7 +43,7 @@ public void findRef_GivenNameOfEntityThatDoesNotExist_ReturnsNull() throws Excep } @Test - public void findRef_GivenResourceWithNoEmbedded_ReturnsNull() throws Exception { + void findRef_GivenResourceWithNoEmbedded_ReturnsNull() throws Exception { String fileContents = Resources.toString(Resources.getResource("hal-simple.json"), Charset.defaultCharset()); JSONObject json = JSON.parseObject(fileContents); diff --git a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/link/hal/LinksRelHandlerTest.java b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/link/hal/LinksRelHandlerTest.java index c9c502c..c4d2f5f 100644 --- a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/link/hal/LinksRelHandlerTest.java +++ b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/link/hal/LinksRelHandlerTest.java @@ -1,31 +1,31 @@ package uk.co.autotrader.traverson.link.hal; -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson2.JSON; +import com.alibaba.fastjson2.JSONObject; import com.google.common.io.Resources; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.junit.MockitoJUnitRunner; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.junit.jupiter.MockitoExtension; import uk.co.autotrader.traverson.exception.UnknownRelException; import java.nio.charset.Charset; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; -@RunWith(MockitoJUnitRunner.class) -public class LinksRelHandlerTest { +@ExtendWith(MockitoExtension.class) +class LinksRelHandlerTest { private LinksRelHandler handler; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() { this.handler = new LinksRelHandler(); } @Test - public void findHref_GivenJsonContainsExpectedRel_ReturnsHref() throws Exception { + void findHref_GivenJsonContainsExpectedRel_ReturnsHref() throws Exception { String fileContents = Resources.toString(Resources.getResource("hal-simple.json"), Charset.defaultCharset()); JSONObject json = JSON.parseObject(fileContents); @@ -35,7 +35,7 @@ public void findHref_GivenJsonContainsExpectedRel_ReturnsHref() throws Exception } @Test - public void findHref_GivenJsonDoesNotContainExpectedRel_ThrowsException() throws Exception { + void findHref_GivenJsonDoesNotContainExpectedRel_ThrowsException() throws Exception { String fileContents = Resources.toString(Resources.getResource("hal-simple.json"), Charset.defaultCharset()); JSONObject json = JSON.parseObject(fileContents); diff --git a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/link/hal/RelByArrayIndexDiscovererTest.java b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/link/hal/RelByArrayIndexDiscovererTest.java index 5eba95a..85c3849 100644 --- a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/link/hal/RelByArrayIndexDiscovererTest.java +++ b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/link/hal/RelByArrayIndexDiscovererTest.java @@ -1,58 +1,60 @@ package uk.co.autotrader.traverson.link.hal; -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson2.JSON; +import com.alibaba.fastjson2.JSONObject; import com.google.common.io.Resources; import org.assertj.core.api.Condition; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import uk.co.autotrader.traverson.exception.UnknownRelException; import java.io.IOException; import java.nio.charset.Charset; +import java.util.stream.Stream; import static com.google.common.io.Resources.getResource; import static org.assertj.core.api.Assertions.anyOf; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; -@RunWith(Parameterized.class) -public class RelByArrayIndexDiscovererTest { +class RelByArrayIndexDiscovererTest { - @Parameters(name = "{0}") - public static Object[][] arrayIndexHandlers() { - return new Object[][]{ - {new LinksResolver()}, - {new EmbeddedResolver()} - }; + private static Stream arrayIndexHandlers() { + return Stream.of( + Arguments.of(new LinksResolver()), + Arguments.of(new EmbeddedResolver()) + ); } - public RelByArrayIndexDiscovererTest(HalEntityResolver testEntityResolver) { - this.testHandler = new RelByArrayIndexDiscoverer(testEntityResolver); - } - - private final RelByArrayIndexDiscoverer testHandler; + private RelByArrayIndexDiscoverer testHandler; - @Test - public void findHref_GivenNonMatchingSyntax_ReturnsNull() throws Exception { + @ParameterizedTest + @MethodSource("arrayIndexHandlers") + void findHref_GivenNonMatchingSyntax_ReturnsNull(HalEntityResolver testEntityResolver) throws Exception { + testHandler = new RelByArrayIndexDiscoverer(testEntityResolver); assertThat(this.testHandler.findHref(testJson(), "self")).isNull(); } - @Test - public void findHref_GivenNonNumber_ReturnsNull() throws Exception { + @ParameterizedTest + @MethodSource("arrayIndexHandlers") + void findHref_GivenNonNumber_ReturnsNull(HalEntityResolver testEntityResolver) throws Exception { + testHandler = new RelByArrayIndexDiscoverer(testEntityResolver); assertThat(this.testHandler.findHref(testJson(), "array[first]")).isNull(); } - @Test - public void findHref_GivenNegativeNumber_ReturnsNull() throws Exception { + @ParameterizedTest + @MethodSource("arrayIndexHandlers") + void findHref_GivenNegativeNumber_ReturnsNull(HalEntityResolver testEntityResolver) throws Exception { + testHandler = new RelByArrayIndexDiscoverer(testEntityResolver); assertThat(this.testHandler.findHref(testJson(), "array[-1]")).isNull(); } - @Test - public void findHref_GivenRelDoesntExist_throwsException() throws Exception { + @ParameterizedTest + @MethodSource("arrayIndexHandlers") + void findHref_GivenRelDoesntExist_throwsException(HalEntityResolver testEntityResolver) throws Exception { try { + testHandler = new RelByArrayIndexDiscoverer(testEntityResolver); this.testHandler.findHref(testJson(), "doesnt-exist[0]"); fail("Should throw exception"); } catch (UnknownRelException e) { @@ -64,9 +66,11 @@ public void findHref_GivenRelDoesntExist_throwsException() throws Exception { } } - @Test - public void findHref_GivenNonArrayRel_throwsException() throws Exception { + @ParameterizedTest + @MethodSource("arrayIndexHandlers") + void findHref_GivenNonArrayRel_throwsException(HalEntityResolver testEntityResolver) throws Exception { try { + testHandler = new RelByArrayIndexDiscoverer(testEntityResolver); this.testHandler.findHref(testJson(), "not-array[0]"); fail("Should throw exception"); } catch (UnknownRelException e) { @@ -78,10 +82,12 @@ public void findHref_GivenNonArrayRel_throwsException() throws Exception { } } - @Test - public void findHref_GivenResourceWithNoEmbeddedAndUnknownRel_throwsException() throws Exception { + @ParameterizedTest + @MethodSource("arrayIndexHandlers") + void findHref_GivenResourceWithNoEmbeddedAndUnknownRel_throwsException(HalEntityResolver testEntityResolver) throws Exception { try { JSONObject resource = JSON.parseObject(Resources.toString(getResource("hal-simple.json"), Charset.defaultCharset())); + testHandler = new RelByArrayIndexDiscoverer(testEntityResolver); this.testHandler.findHref(resource, "not-exists[0]"); fail("Should throw exception"); } catch (UnknownRelException e) { @@ -90,19 +96,25 @@ public void findHref_GivenResourceWithNoEmbeddedAndUnknownRel_throwsException() } } - @Test - public void findHref_GivenArrayPosition_ReturnsHref() throws Exception { + @ParameterizedTest + @MethodSource("arrayIndexHandlers") + void findHref_GivenArrayPosition_ReturnsHref(HalEntityResolver testEntityResolver) throws Exception { + testHandler = new RelByArrayIndexDiscoverer(testEntityResolver); assertThat(this.testHandler.findHref(testJson(), "array[0]")).isEqualTo("http://first"); } - @Test - public void findHref_GivenSecondArrayPosition_ReturnsHref() throws Exception { + @ParameterizedTest + @MethodSource("arrayIndexHandlers") + void findHref_GivenSecondArrayPosition_ReturnsHref(HalEntityResolver testEntityResolver) throws Exception { + testHandler = new RelByArrayIndexDiscoverer(testEntityResolver); assertThat(this.testHandler.findHref(testJson(), "array[1]")).isEqualTo("http://second"); } - @Test - public void findHref_GivenNonExistentArrayPosition_throwsException() throws Exception { + @ParameterizedTest + @MethodSource("arrayIndexHandlers") + void findHref_GivenNonExistentArrayPosition_throwsException(HalEntityResolver testEntityResolver) throws Exception { try { + testHandler = new RelByArrayIndexDiscoverer(testEntityResolver); this.testHandler.findHref(testJson(), "array[2]"); fail("Should throw exception"); } catch (UnknownRelException e) { diff --git a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/link/hal/RelByArrayPropertyDiscovererTest.java b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/link/hal/RelByArrayPropertyDiscovererTest.java index 0f1e017..8ab7e27 100644 --- a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/link/hal/RelByArrayPropertyDiscovererTest.java +++ b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/link/hal/RelByArrayPropertyDiscovererTest.java @@ -1,46 +1,45 @@ package uk.co.autotrader.traverson.link.hal; -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson2.JSON; +import com.alibaba.fastjson2.JSONObject; import com.google.common.base.Charsets; import com.google.common.io.Resources; import org.assertj.core.api.Condition; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import uk.co.autotrader.traverson.exception.UnknownRelException; +import java.util.stream.Stream; + import static com.google.common.io.Resources.getResource; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.condition.AnyOf.anyOf; -@RunWith(Parameterized.class) -public class RelByArrayPropertyDiscovererTest { +class RelByArrayPropertyDiscovererTest { - @Parameters - public static Object[][] handlers() { - return new Object[][]{ - {new LinksResolver()}, - {new EmbeddedResolver()} - }; + private static Stream handlers() { + return Stream.of( + Arguments.of(new LinksResolver()), + Arguments.of(new EmbeddedResolver()) + ); } - private final RelByArrayPropertyDiscoverer testSubject; - - public RelByArrayPropertyDiscovererTest(HalEntityResolver halEntityResolver) { - this.testSubject = new RelByArrayPropertyDiscoverer(halEntityResolver); - } + private RelByArrayPropertyDiscoverer testSubject; - @Test - public void findHref_GivenRelWithoutProperty_ReturnsNull() throws Exception { + @ParameterizedTest + @MethodSource("handlers") + void findHref_GivenRelWithoutProperty_ReturnsNull(HalEntityResolver halEntityResolver) throws Exception { + testSubject = new RelByArrayPropertyDiscoverer(halEntityResolver); assertThat(this.testSubject.findHref(testJson(), "self")).isNull(); } - @Test - public void findHref_GivenNonExistentRel_throwsException() throws Exception { + @ParameterizedTest + @MethodSource("handlers") + void findHref_GivenNonExistentRel_throwsException(HalEntityResolver halEntityResolver) throws Exception { try { + testSubject = new RelByArrayPropertyDiscoverer(halEntityResolver); this.testSubject.findHref(testJson(), "non-existent[key:value]"); fail("Should throw exception"); } catch (UnknownRelException e) { @@ -51,14 +50,18 @@ public void findHref_GivenNonExistentRel_throwsException() throws Exception { } } - @Test - public void findHref_GivenRelWithPropertyThatExists_ReturnsRelatedHref() throws Exception { + @ParameterizedTest + @MethodSource("handlers") + void findHref_GivenRelWithPropertyThatExists_ReturnsRelatedHref(HalEntityResolver halEntityResolver) throws Exception { + testSubject = new RelByArrayPropertyDiscoverer(halEntityResolver); assertThat(this.testSubject.findHref(testJson(), "section[name:turnip]")).isEqualTo("http://turnip-link"); } - @Test - public void findHref_GivenRelWithPropertyNotExisting_throwsException() throws Exception { + @ParameterizedTest + @MethodSource("handlers") + void findHref_GivenRelWithPropertyNotExisting_throwsException(HalEntityResolver halEntityResolver) throws Exception { try { + testSubject = new RelByArrayPropertyDiscoverer(halEntityResolver); this.testSubject.findHref(testJson(), "section[name:notexist]"); fail("Should throw exception"); } catch (UnknownRelException e) { @@ -69,9 +72,11 @@ public void findHref_GivenRelWithPropertyNotExisting_throwsException() throws Ex } } - @Test - public void findHref_GivenRelThatIsntArray_throwsException() throws Exception { + @ParameterizedTest + @MethodSource("handlers") + void findHref_GivenRelThatIsntArray_throwsException(HalEntityResolver halEntityResolver) throws Exception { try { + testSubject = new RelByArrayPropertyDiscoverer(halEntityResolver); this.testSubject.findHref(testJson(), "self[prop:value]"); fail("Should throw exception"); } catch (UnknownRelException e) { @@ -82,8 +87,10 @@ public void findHref_GivenRelThatIsntArray_throwsException() throws Exception { } } - @Test - public void findHref_GivenRelWithDuplicateMatchingProperties_ReturnsFirstMatch() throws Exception { + @ParameterizedTest + @MethodSource("handlers") + void findHref_GivenRelWithDuplicateMatchingProperties_ReturnsFirstMatch(HalEntityResolver halEntityResolver) throws Exception { + testSubject = new RelByArrayPropertyDiscoverer(halEntityResolver); assertThat(this.testSubject.findHref(testJson(), "duplicates[name:dupe]")).isEqualTo("http://duplicate-link-1"); } diff --git a/traverson4j-hc5/build.gradle b/traverson4j-hc5/build.gradle index 7305b8a..3e5f1d1 100644 --- a/traverson4j-hc5/build.gradle +++ b/traverson4j-hc5/build.gradle @@ -2,5 +2,5 @@ dependencies { api 'org.apache.httpcomponents.client5:httpclient5:5.2.1', 'com.damnhandy:handy-uri-templates:2.1.8' - testImplementation "com.github.tomakehurst:wiremock-jre8:2.27.0" + testImplementation "com.github.tomakehurst:wiremock-jre8-standalone:2.35.0" } diff --git a/traverson4j-hc5/src/main/java/uk/co/autotrader/traverson/http/ApacheHttpTraversonClientAdapter.java b/traverson4j-hc5/src/main/java/uk/co/autotrader/traverson/http/ApacheHttpTraversonClientAdapter.java index fa38728..b0cb2b1 100644 --- a/traverson4j-hc5/src/main/java/uk/co/autotrader/traverson/http/ApacheHttpTraversonClientAdapter.java +++ b/traverson4j-hc5/src/main/java/uk/co/autotrader/traverson/http/ApacheHttpTraversonClientAdapter.java @@ -1,6 +1,6 @@ package uk.co.autotrader.traverson.http; -import com.alibaba.fastjson.util.IOUtils; +import com.alibaba.fastjson2.util.IOUtils; import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; import org.apache.hc.client5.http.impl.classic.HttpClients; diff --git a/traverson4j-hc5/src/test/java/uk/co/autotrader/traverson/http/ApacheHttpConvertersTest.java b/traverson4j-hc5/src/test/java/uk/co/autotrader/traverson/http/ApacheHttpConvertersTest.java index c03a744..72091c3 100644 --- a/traverson4j-hc5/src/test/java/uk/co/autotrader/traverson/http/ApacheHttpConvertersTest.java +++ b/traverson4j-hc5/src/test/java/uk/co/autotrader/traverson/http/ApacheHttpConvertersTest.java @@ -6,12 +6,12 @@ import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; import org.apache.hc.core5.http.*; import org.apache.hc.core5.http.message.BasicHeader; -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; import uk.co.autotrader.traverson.conversion.ResourceConversionService; import uk.co.autotrader.traverson.http.entity.BodyFactory; @@ -23,8 +23,8 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.*; -@RunWith(MockitoJUnitRunner.class) -public class ApacheHttpConvertersTest { +@ExtendWith(MockitoExtension.class) +class ApacheHttpConvertersTest { private ApacheHttpConverters apacheHttpUriConverter; @Mock private BodyFactory bodyFactory; @@ -39,13 +39,13 @@ public class ApacheHttpConvertersTest { @Mock private AuthCredential authCredential; - @Before - public void setUp() { + @BeforeEach + void setUp() { apacheHttpUriConverter = new ApacheHttpConverters(bodyFactory, uriUtils, conversionService); } @Test - public void toRequest_SetsHttpVerb() { + void toRequest_SetsHttpVerb() { Request request = new Request(); request.setMethod(Method.PATCH); @@ -55,7 +55,7 @@ public void toRequest_SetsHttpVerb() { } @Test - public void toRequest_SetsUrl() throws Exception { + void toRequest_SetsUrl() throws Exception { Request request = new Request(); request.setMethod(Method.GET); String url = "http://localhost:8080/"; @@ -68,7 +68,7 @@ public void toRequest_SetsUrl() throws Exception { } @Test - public void toRequest_AppendsQueryParams() throws Exception { + void toRequest_AppendsQueryParams() throws Exception { Request request = new Request(); request.setMethod(Method.GET); String url = "http://localhost:8080"; @@ -83,7 +83,7 @@ public void toRequest_AppendsQueryParams() throws Exception { } @Test - public void toRequest_ExpandsTemplateUriBeforeBuildingRequest() throws Exception { + void toRequest_ExpandsTemplateUriBeforeBuildingRequest() throws Exception { Request request = new Request(); request.setMethod(Method.GET); String url = "http://localhost:8080/{tmp1}/stuff{?tmp2}"; @@ -99,7 +99,7 @@ public void toRequest_ExpandsTemplateUriBeforeBuildingRequest() throws Exception } @Test - public void toRequest_SetsHeaders() { + void toRequest_SetsHeaders() { Request request = new Request(); request.setMethod(Method.GET); request.addHeader("header1", "value1"); @@ -112,7 +112,7 @@ public void toRequest_SetsHeaders() { } @Test - public void toRequest_SetsAcceptHeader() { + void toRequest_SetsAcceptHeader() { Request request = new Request(); request.setMethod(Method.GET); request.setAcceptMimeType("application/json"); @@ -123,7 +123,7 @@ public void toRequest_SetsAcceptHeader() { } @Test - public void toRequest_SetsHttpEntity() { + void toRequest_SetsHttpEntity() { Body body = mock(Body.class); Request request = new Request(); request.setMethod(Method.PUT); @@ -136,7 +136,7 @@ public void toRequest_SetsHttpEntity() { } @Test - public void toResponse_BuildsResponseCorrectly() throws Exception { + void toResponse_BuildsResponseCorrectly() throws Exception { HttpRequest request = mock(HttpRequest.class); URI requestUri = new URI("http://localhost"); @@ -155,7 +155,7 @@ public void toResponse_BuildsResponseCorrectly() throws Exception { } @Test - public void toResponse_GivenResponseHasEntity_ConvertsAndSetsResource() throws Exception { + void toResponse_GivenResponseHasEntity_ConvertsAndSetsResource() throws Exception { HttpRequest request = mock(HttpRequest.class); URI requestUri = new URI("http://localhost"); String expectedJson = "{'name':'test'}"; @@ -174,7 +174,7 @@ public void toResponse_GivenResponseHasEntity_ConvertsAndSetsResource() throws E } @Test - public void constructCredentialsProviderAndAuthCache_ifNoHostnameReturnsAnyAuthScope() { + void constructCredentialsProviderAndAuthCache_ifNoHostnameReturnsAnyAuthScope() { BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider(); ApacheHttpTraversonClientAdapter apacheHttpTraversonClientAdapter = new ApacheHttpTraversonClientAdapter(); AuthCache authCache = new BasicAuthCache(); @@ -184,12 +184,12 @@ public void constructCredentialsProviderAndAuthCache_ifNoHostnameReturnsAnyAuthS apacheHttpTraversonClientAdapter.apacheHttpUriConverter.constructCredentialsProviderAndAuthCache(basicCredentialsProvider, authCache, authCredential); - assertThat(basicCredentialsProvider.toString()).isEqualTo("[ ://:]"); + assertThat(basicCredentialsProvider).hasToString("[ ://:]"); assertThat(authCache.get(new HttpHost("hostname"))).isNull(); } @Test - public void constructCredentialsProviderAndAuthCache_setsHostnameInAuthScope() { + void constructCredentialsProviderAndAuthCache_setsHostnameInAuthScope() { BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider(); ApacheHttpTraversonClientAdapter apacheHttpTraversonClientAdapter = new ApacheHttpTraversonClientAdapter(); AuthCache authCache = new BasicAuthCache(); @@ -200,12 +200,12 @@ public void constructCredentialsProviderAndAuthCache_setsHostnameInAuthScope() { apacheHttpTraversonClientAdapter.apacheHttpUriConverter.constructCredentialsProviderAndAuthCache(basicCredentialsProvider, authCache, authCredential); - assertThat(basicCredentialsProvider.toString()).isEqualTo("[ http://hostname:]"); + assertThat(basicCredentialsProvider).hasToString("[ http://hostname:]"); assertThat(authCache.get(new HttpHost("hostname"))).isNull(); } @Test - public void constructCredentialsProviderAndAuthCache_setsHostnameAndBasicAuth() { + void constructCredentialsProviderAndAuthCache_setsHostnameAndBasicAuth() { BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider(); AuthCache authCache = new BasicAuthCache(); ApacheHttpTraversonClientAdapter apacheHttpTraversonClientAdapter = new ApacheHttpTraversonClientAdapter(); @@ -217,12 +217,12 @@ public void constructCredentialsProviderAndAuthCache_setsHostnameAndBasicAuth() apacheHttpTraversonClientAdapter.apacheHttpUriConverter.constructCredentialsProviderAndAuthCache(basicCredentialsProvider, authCache, authCredential); - assertThat(basicCredentialsProvider.toString()).isEqualTo("[ http://hostname:]"); + assertThat(basicCredentialsProvider).hasToString("[ http://hostname:]"); assertThat(authCache.get(new HttpHost("hostname")).getName()).isEqualTo("Basic"); } @Test - public void constructCredentialsProviderAndAuthCache_throwsExceptionWhenHostnameContainsSpaces() { + void constructCredentialsProviderAndAuthCache_throwsExceptionWhenHostnameContainsSpaces() { BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider(); ApacheHttpTraversonClientAdapter apacheHttpTraversonClientAdapter = new ApacheHttpTraversonClientAdapter(); AuthCache authCache = new BasicAuthCache(); diff --git a/traverson4j-hc5/src/test/java/uk/co/autotrader/traverson/http/ApacheHttpTraversonClientAdapterTest.java b/traverson4j-hc5/src/test/java/uk/co/autotrader/traverson/http/ApacheHttpTraversonClientAdapterTest.java index bacf9d0..7960eee 100644 --- a/traverson4j-hc5/src/test/java/uk/co/autotrader/traverson/http/ApacheHttpTraversonClientAdapterTest.java +++ b/traverson4j-hc5/src/test/java/uk/co/autotrader/traverson/http/ApacheHttpTraversonClientAdapterTest.java @@ -1,16 +1,16 @@ package uk.co.autotrader.traverson.http; -import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson2.JSONObject; import org.apache.commons.lang3.reflect.FieldUtils; import org.apache.hc.client5.http.classic.methods.HttpUriRequest; import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; import org.apache.hc.client5.http.protocol.HttpClientContext; -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; import uk.co.autotrader.traverson.exception.HttpException; import java.io.IOException; @@ -22,8 +22,8 @@ import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.*; -@RunWith(MockitoJUnitRunner.class) -public class ApacheHttpTraversonClientAdapterTest { +@ExtendWith(MockitoExtension.class) +class ApacheHttpTraversonClientAdapterTest { private ApacheHttpTraversonClientAdapter clientAdapter; @Mock private CloseableHttpClient httpClient; @@ -39,19 +39,19 @@ public class ApacheHttpTraversonClientAdapterTest { private Request request; private Response expectedResponse; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { clientAdapter = new ApacheHttpTraversonClientAdapter(httpClient); FieldUtils.writeField(clientAdapter, "apacheHttpUriConverter", apacheHttpConverters, true); request = new Request(); expectedResponse = new Response<>(); - when(apacheHttpConverters.toRequest(request)).thenReturn(httpRequest); - when(apacheHttpConverters.toResponse(httpResponse, JSONObject.class, httpRequest.getUri())).thenReturn(expectedResponse); - when(apacheHttpConverters.toHttpClientContext(request)).thenReturn(clientContext); } @Test - public void execute_GivenGetRequest_ReturnsResponse() throws Exception { + void execute_GivenGetRequest_ReturnsResponse() throws Exception { + when(apacheHttpConverters.toRequest(request)).thenReturn(httpRequest); + when(apacheHttpConverters.toResponse(httpResponse, JSONObject.class, httpRequest.getUri())).thenReturn(expectedResponse); + when(apacheHttpConverters.toHttpClientContext(request)).thenReturn(clientContext); when(httpClient.execute(httpRequest, clientContext)).thenReturn(httpResponse); Response response = clientAdapter.execute(request, JSONObject.class); @@ -61,10 +61,13 @@ public void execute_GivenGetRequest_ReturnsResponse() throws Exception { } @Test - public void execute_GivenGetRequestForInputStream_ReturnsResponseButDoesntCloseTheResponse() throws Exception { - when(httpClient.execute(httpRequest, clientContext)).thenReturn(httpResponse); + void execute_GivenGetRequestForInputStream_ReturnsResponseButDoesntCloseTheResponse() throws Exception { Response expectedStreamResponse = new Response<>(); + + when(apacheHttpConverters.toRequest(request)).thenReturn(httpRequest); when(apacheHttpConverters.toResponse(httpResponse, InputStream.class, httpRequest.getUri())).thenReturn(expectedStreamResponse); + when(apacheHttpConverters.toHttpClientContext(request)).thenReturn(clientContext); + when(httpClient.execute(httpRequest, clientContext)).thenReturn(httpResponse); Response response = clientAdapter.execute(request, InputStream.class); @@ -73,9 +76,11 @@ public void execute_GivenGetRequestForInputStream_ReturnsResponseButDoesntCloseT } @Test - public void execute_GivenIOExceptionIsThrown_WrapsInTraversonException() throws Exception { - when(httpClient.execute(eq(httpRequest), any(HttpClientContext.class))).thenReturn(httpResponse); + void execute_GivenIOExceptionIsThrown_WrapsInTraversonException() throws Exception { + when(apacheHttpConverters.toRequest(request)).thenReturn(httpRequest); when(apacheHttpConverters.toResponse(httpResponse, JSONObject.class, httpRequest.getUri())).thenThrow(new IOException()); + when(apacheHttpConverters.toHttpClientContext(request)).thenReturn(clientContext); + when(httpClient.execute(eq(httpRequest), any(HttpClientContext.class))).thenReturn(httpResponse); assertThatThrownBy(() -> clientAdapter.execute(request, JSONObject.class)).isInstanceOf(HttpException.class); @@ -83,10 +88,13 @@ public void execute_GivenIOExceptionIsThrown_WrapsInTraversonException() throws } @Test - public void execute_GivenRuntimeExceptionIsThrown_ClosesInputStreamAndReturnsOriginalException() throws Exception { + void execute_GivenRuntimeExceptionIsThrown_ClosesInputStreamAndReturnsOriginalException() throws Exception { NullPointerException nullPointerException = new NullPointerException(); - when(httpClient.execute(eq(httpRequest), any(HttpClientContext.class))).thenReturn(httpResponse); + + when(apacheHttpConverters.toRequest(request)).thenReturn(httpRequest); when(apacheHttpConverters.toResponse(httpResponse, JSONObject.class, httpRequest.getUri())).thenThrow(nullPointerException); + when(apacheHttpConverters.toHttpClientContext(request)).thenReturn(clientContext); + when(httpClient.execute(eq(httpRequest), any(HttpClientContext.class))).thenReturn(httpResponse); assertThatThrownBy(() -> clientAdapter.execute(request, JSONObject.class)).isSameAs(nullPointerException); @@ -94,7 +102,7 @@ public void execute_GivenRuntimeExceptionIsThrown_ClosesInputStreamAndReturnsOri } @Test - public void init_SetsDefaultHttpClient() throws Exception { + void init_SetsDefaultHttpClient() throws Exception { ApacheHttpTraversonClientAdapter apacheHttpTraversonClientAdapter = new ApacheHttpTraversonClientAdapter(); assertThat(FieldUtils.readField(apacheHttpTraversonClientAdapter, "adapterClient", true)).isNotNull(); diff --git a/traverson4j-hc5/src/test/java/uk/co/autotrader/traverson/http/IntegrationTest.java b/traverson4j-hc5/src/test/java/uk/co/autotrader/traverson/http/IntegrationTest.java index 1e6ccbe..1ec16ea 100644 --- a/traverson4j-hc5/src/test/java/uk/co/autotrader/traverson/http/IntegrationTest.java +++ b/traverson4j-hc5/src/test/java/uk/co/autotrader/traverson/http/IntegrationTest.java @@ -1,12 +1,12 @@ package uk.co.autotrader.traverson.http; -import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson2.JSONObject; import com.github.tomakehurst.wiremock.WireMockServer; import com.github.tomakehurst.wiremock.client.WireMock; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import uk.co.autotrader.traverson.Traverson; import java.io.IOException; @@ -22,25 +22,25 @@ public class IntegrationTest { private final Traverson traverson = new Traverson(new ApacheHttpTraversonClientAdapter()); - @BeforeClass - public static void beforeClass() throws Exception { + @BeforeAll + public static void beforeClass() { wireMockServer = new WireMockServer(8089); wireMockServer.start(); } - @AfterClass - public static void afterClass() throws Exception { + @AfterAll + public static void afterClass() { wireMockServer.stop(); wireMockServer.resetAll(); } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() { wireMockServer.resetAll(); } @Test - public void inputStream_allowsClientsToRequestTheBodyAsInputStreamWithoutClosingTheHttpConnection() throws IOException { + void inputStream_allowsClientsToRequestTheBodyAsInputStreamWithoutClosingTheHttpConnection() throws IOException { String htmlBody = ""; wireMockServer.stubFor(get(urlEqualTo("/")) .willReturn(WireMock.status(200).withBody(htmlBody))); @@ -55,7 +55,7 @@ public void inputStream_allowsClientsToRequestTheBodyAsInputStreamWithoutClosing } @Test - public void acceptHeaderCanBeSet() throws IOException { + void acceptHeaderCanBeSet() throws IOException { String htmlBody = ""; wireMockServer.stubFor(get(urlEqualTo("/")).willReturn(WireMock.status(200).withBody(htmlBody))); @@ -66,7 +66,7 @@ public void acceptHeaderCanBeSet() throws IOException { } @Test - public void requestBody_SimpleTextBodyIsSerializedAndPostedCorrectly() { + void requestBody_SimpleTextBodyIsSerializedAndPostedCorrectly() { wireMockServer.stubFor(patch(urlEqualTo("/records/1")) .willReturn(WireMock.status(202))); Response response = traverson.from("http://localhost:8089/records/1") @@ -77,7 +77,7 @@ public void requestBody_SimpleTextBodyIsSerializedAndPostedCorrectly() { } @Test - public void requestBody_MultipartBodyIsSerializedAndPostedCorrectly() { + void requestBody_MultipartBodyIsSerializedAndPostedCorrectly() { byte[] data = new byte[]{0x00, 0x01, 0x02}; wireMockServer.stubFor(post("/records") .withMultipartRequestBody(aMultipart() @@ -96,7 +96,7 @@ public void requestBody_MultipartBodyIsSerializedAndPostedCorrectly() { } @Test - public void basicAuthentication_ReactsToUnauthorizedStatusAndAuthenticateHeader() { + void basicAuthentication_ReactsToUnauthorizedStatusAndAuthenticateHeader() { wireMockServer.stubFor(get("/restricted-area") .inScenario("Restricted access").whenScenarioStateIs(STARTED) .willSetStateTo("First request made") @@ -116,7 +116,7 @@ public void basicAuthentication_ReactsToUnauthorizedStatusAndAuthenticateHeader( } @Test - public void basicAuthentication_GivenPreemptiveAuthenticationSetToTrue_SendsUsernameAndPasswordWithoutNeedingAnUnauthorizedResponse() { + void basicAuthentication_GivenPreemptiveAuthenticationSetToTrue_SendsUsernameAndPasswordWithoutNeedingAnUnauthorizedResponse() { wireMockServer.stubFor(get("/restricted-area") .withBasicAuth("MyUsername", "MyPassword") .willReturn(ok())); diff --git a/traverson4j-hc5/src/test/java/uk/co/autotrader/traverson/http/TemplateUriUtilsTest.java b/traverson4j-hc5/src/test/java/uk/co/autotrader/traverson/http/TemplateUriUtilsTest.java index 1c4f4fa..1613457 100644 --- a/traverson4j-hc5/src/test/java/uk/co/autotrader/traverson/http/TemplateUriUtilsTest.java +++ b/traverson4j-hc5/src/test/java/uk/co/autotrader/traverson/http/TemplateUriUtilsTest.java @@ -1,10 +1,9 @@ package uk.co.autotrader.traverson.http; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.junit.MockitoJUnitRunner; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Arrays; import java.util.HashMap; @@ -13,18 +12,18 @@ import static org.assertj.core.api.Assertions.assertThat; -@RunWith(MockitoJUnitRunner.class) -public class TemplateUriUtilsTest { +@ExtendWith(MockitoExtension.class) +class TemplateUriUtilsTest { private TemplateUriUtils templateUriUtils; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() { templateUriUtils = new TemplateUriUtils(); } @Test - public void expandTemplateUri_GivenTemplateUriAndTemplateParams_ExpandsTemplate() throws Exception { + void expandTemplateUri_GivenTemplateUriAndTemplateParams_ExpandsTemplate() { String input = "http://example.autotrader.co.uk/dealers{?dealerId*,otherParam}"; Map> templateParams = new HashMap>(); templateParams.put("dealerId", Arrays.asList("123")); @@ -36,7 +35,7 @@ public void expandTemplateUri_GivenTemplateUriAndTemplateParams_ExpandsTemplate( } @Test - public void expandTemplateUri_GivenTemplateUriAndUnusedTemplateParams_ExpandsTemplate() throws Exception { + void expandTemplateUri_GivenTemplateUriAndUnusedTemplateParams_ExpandsTemplate() { String input = "http://example.autotrader.co.uk/dealers{?dealerId,otherParam}"; Map> templateParams = new HashMap>(); templateParams.put("notFound", Arrays.asList("dummy")); @@ -47,7 +46,7 @@ public void expandTemplateUri_GivenTemplateUriAndUnusedTemplateParams_ExpandsTem } @Test - public void expandTemplateUri_GivenTemplateUriAndNoTemplateParams_ExpandsTemplate() throws Exception { + void expandTemplateUri_GivenTemplateUriAndNoTemplateParams_ExpandsTemplate() { String input = "http://example.autotrader.co.uk/dealers{?dealerId,otherParam}"; Map> templateParams = new HashMap>(); @@ -58,7 +57,7 @@ public void expandTemplateUri_GivenTemplateUriAndNoTemplateParams_ExpandsTemplat @Test - public void expandTemplateUri_GivenTemplateUriAndMultipleOfTheSameTemplateParam_ExpandsTemplate() throws Exception { + void expandTemplateUri_GivenTemplateUriAndMultipleOfTheSameTemplateParam_ExpandsTemplate() { String input = "http://example.autotrader.co.uk/dealers{?dealerId*,otherParam}"; Map> templateParams = new HashMap>(); templateParams.put("dealerId", Arrays.asList("1234", "4567", "78910")); diff --git a/traverson4j-hc5/src/test/java/uk/co/autotrader/traverson/http/entity/BodyFactoryTest.java b/traverson4j-hc5/src/test/java/uk/co/autotrader/traverson/http/entity/BodyFactoryTest.java index 0d38b55..8c2b11c 100644 --- a/traverson4j-hc5/src/test/java/uk/co/autotrader/traverson/http/entity/BodyFactoryTest.java +++ b/traverson4j-hc5/src/test/java/uk/co/autotrader/traverson/http/entity/BodyFactoryTest.java @@ -1,20 +1,19 @@ package uk.co.autotrader.traverson.http.entity; import org.apache.hc.core5.http.HttpEntity; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Assertions; +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; import uk.co.autotrader.traverson.http.Body; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class BodyFactoryTest { +@ExtendWith(MockitoExtension.class) +class BodyFactoryTest { private BodyFactory bodyFactory; @Mock private HttpEntityConverter converter; @@ -22,26 +21,30 @@ public class BodyFactoryTest { private Body body; @Mock private HttpEntity entity; - @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() { bodyFactory = new BodyFactory(); - when(converter.toEntity(body)).thenReturn(entity); } @Test - public void toEntity_GivenConverterIsRegistered_ReturnsConvertedResult() throws Exception { + void toEntity_GivenConverterIsRegistered_ReturnsConvertedResult() { + when(converter.toEntity(body)).thenReturn(entity); BodyFactory.register(body.getClass(), converter); assertThat(bodyFactory.toEntity(body)).isEqualTo(entity); } @Test - public void toEntity_GivenConverterIsNotRegistered_ThrowsException() throws Exception { - expectedException.expect(UnsupportedOperationException.class); - expectedException.expectMessage("Not supported Request body, the supported types are "); + void toEntity_GivenConverterIsNotRegistered_ThrowsException() { + UnsupportedOperationException exception = Assertions.assertThrows(UnsupportedOperationException.class, () -> { + HttpEntity newEntity = bodyFactory.toEntity(body); + assertThat(newEntity).isEqualTo(entity); + }); - assertThat(bodyFactory.toEntity(body)).isEqualTo(entity); + assertThat(exception.getMessage()) + .contains("Not supported Request body, the supported types are") + .contains("class uk.co.autotrader.traverson.http.SimpleMultipartBody") + .contains("class uk.co.autotrader.traverson.http.TextBody") + .contains("class uk.co.autotrader.traverson.http.FormDataBody"); } } diff --git a/traverson4j-hc5/src/test/java/uk/co/autotrader/traverson/http/entity/BodyPartEntityConverterTest.java b/traverson4j-hc5/src/test/java/uk/co/autotrader/traverson/http/entity/BodyPartEntityConverterTest.java index 6aa7411..b0705dc 100644 --- a/traverson4j-hc5/src/test/java/uk/co/autotrader/traverson/http/entity/BodyPartEntityConverterTest.java +++ b/traverson4j-hc5/src/test/java/uk/co/autotrader/traverson/http/entity/BodyPartEntityConverterTest.java @@ -1,10 +1,10 @@ package uk.co.autotrader.traverson.http.entity; import org.apache.hc.core5.http.HttpEntity; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.junit.MockitoJUnitRunner; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.junit.jupiter.MockitoExtension; import uk.co.autotrader.traverson.http.SimpleMultipartBody; import java.io.ByteArrayOutputStream; @@ -13,18 +13,18 @@ import static org.assertj.core.api.Assertions.assertThat; -@RunWith(MockitoJUnitRunner.class) -public class BodyPartEntityConverterTest { +@ExtendWith(MockitoExtension.class) +class BodyPartEntityConverterTest { private MultipartEntityConverter converter; - @Before - public void setUp() { + @BeforeEach + void setUp() { converter = new MultipartEntityConverter(); } @Test - public void toEntity_GivenTextBody_ReturnsStringEntity() throws Exception { + void toEntity_GivenTextBody_ReturnsStringEntity() throws Exception { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); HttpEntity entity = converter.toEntity(new SimpleMultipartBody(new SimpleMultipartBody.BodyPart("file", "data".getBytes(StandardCharsets.UTF_8), "contentType", "filename"))); @@ -32,9 +32,10 @@ public void toEntity_GivenTextBody_ReturnsStringEntity() throws Exception { assertThat(entity.getContentType()).matches(Pattern.compile("multipart/form-data; charset=ISO-8859-1; boundary=.*")); entity.writeTo(outputStream); String content = new String(outputStream.toByteArray(), StandardCharsets.UTF_8); - assertThat(content).matches(Pattern.compile(".*name=\"file\".*", Pattern.DOTALL | Pattern.MULTILINE)); - assertThat(content).matches(Pattern.compile(".*filename=\"filename\".*", Pattern.DOTALL | Pattern.MULTILINE)); - assertThat(content).matches(Pattern.compile(".*Content-Type: contenttype.*", Pattern.DOTALL | Pattern.MULTILINE)); - assertThat(content).matches(Pattern.compile(".*data.*", Pattern.DOTALL | Pattern.MULTILINE)); + assertThat(content) + .matches(Pattern.compile(".*name=\"file\".*", Pattern.DOTALL | Pattern.MULTILINE)) + .matches(Pattern.compile(".*filename=\"filename\".*", Pattern.DOTALL | Pattern.MULTILINE)) + .matches(Pattern.compile(".*Content-Type: contenttype.*", Pattern.DOTALL | Pattern.MULTILINE)) + .matches(Pattern.compile(".*data.*", Pattern.DOTALL | Pattern.MULTILINE)); } } diff --git a/traverson4j-hc5/src/test/java/uk/co/autotrader/traverson/http/entity/FormDataEntityConverterTest.java b/traverson4j-hc5/src/test/java/uk/co/autotrader/traverson/http/entity/FormDataEntityConverterTest.java index 7d55711..a76f539 100644 --- a/traverson4j-hc5/src/test/java/uk/co/autotrader/traverson/http/entity/FormDataEntityConverterTest.java +++ b/traverson4j-hc5/src/test/java/uk/co/autotrader/traverson/http/entity/FormDataEntityConverterTest.java @@ -3,28 +3,28 @@ import com.google.common.base.Charsets; import org.apache.hc.client5.http.entity.UrlEncodedFormEntity; import org.apache.hc.core5.http.HttpEntity; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.junit.MockitoJUnitRunner; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.junit.jupiter.MockitoExtension; import uk.co.autotrader.traverson.http.FormDataBody; import java.io.ByteArrayInputStream; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(MockitoJUnitRunner.class) -public class FormDataEntityConverterTest { +@ExtendWith(MockitoExtension.class) +class FormDataEntityConverterTest { private FormDataEntityConverter converter; - @Before - public void setUp() { + @BeforeEach + void setUp() { converter = new FormDataEntityConverter(); } @Test - public void toEntity_GivenTextBody_ReturnsStringEntity() throws Exception { + void toEntity_GivenTextBody_ReturnsStringEntity() throws Exception { HttpEntity entity = converter.toEntity(new FormDataBody(Charsets.UTF_8, new FormDataBody.NameValuePair("name", "value"))); diff --git a/traverson4j-hc5/src/test/java/uk/co/autotrader/traverson/http/entity/TextEntityConverterTest.java b/traverson4j-hc5/src/test/java/uk/co/autotrader/traverson/http/entity/TextEntityConverterTest.java index 4937458..f45a7ef 100644 --- a/traverson4j-hc5/src/test/java/uk/co/autotrader/traverson/http/entity/TextEntityConverterTest.java +++ b/traverson4j-hc5/src/test/java/uk/co/autotrader/traverson/http/entity/TextEntityConverterTest.java @@ -3,28 +3,28 @@ import com.google.common.base.Charsets; import org.apache.hc.core5.http.HttpEntity; import org.apache.hc.core5.http.io.entity.StringEntity; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.junit.MockitoJUnitRunner; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.junit.jupiter.MockitoExtension; import uk.co.autotrader.traverson.http.TextBody; import java.io.ByteArrayInputStream; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(MockitoJUnitRunner.class) -public class TextEntityConverterTest { +@ExtendWith(MockitoExtension.class) +class TextEntityConverterTest { private TextEntityConverter converter; - @Before - public void setUp() { + @BeforeEach + void setUp() { converter = new TextEntityConverter(); } @Test - public void toEntity_GivenTextBody_ReturnsStringEntity() throws Exception { + void toEntity_GivenTextBody_ReturnsStringEntity() throws Exception { HttpEntity entity = converter.toEntity(new TextBody("data££", "text/plain", Charsets.UTF_8)); assertThat(entity).isInstanceOf(StringEntity.class); @@ -33,7 +33,7 @@ public void toEntity_GivenTextBody_ReturnsStringEntity() throws Exception { } @Test - public void toEntity_GivenTextBody_WithNoCharsetDefined_ReturnsStringEntityUsingApacheDefault() throws Exception { + void toEntity_GivenTextBody_WithNoCharsetDefined_ReturnsStringEntityUsingApacheDefault() throws Exception { HttpEntity entity = converter.toEntity(new TextBody("data££", "text/plain")); assertThat(entity).isInstanceOf(StringEntity.class); diff --git a/traverson4j-jackson2/build.gradle b/traverson4j-jackson2/build.gradle index 9330410..2b707cf 100644 --- a/traverson4j-jackson2/build.gradle +++ b/traverson4j-jackson2/build.gradle @@ -1,3 +1,3 @@ dependencies { - api 'com.fasterxml.jackson.core:jackson-databind:2.13.3' + api 'com.fasterxml.jackson.core:jackson-databind:2.14.2' } diff --git a/traverson4j-jackson2/src/test/java/uk/co/autotrader/traverson/conversion/JacksonResourceConverterTest.java b/traverson4j-jackson2/src/test/java/uk/co/autotrader/traverson/conversion/JacksonResourceConverterTest.java index 24fd14f..bc9aa61 100644 --- a/traverson4j-jackson2/src/test/java/uk/co/autotrader/traverson/conversion/JacksonResourceConverterTest.java +++ b/traverson4j-jackson2/src/test/java/uk/co/autotrader/traverson/conversion/JacksonResourceConverterTest.java @@ -4,12 +4,12 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.io.Resources; import org.apache.commons.lang3.reflect.FieldUtils; -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; import uk.co.autotrader.traverson.exception.ConversionException; import java.io.ByteArrayInputStream; @@ -23,25 +23,25 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class JacksonResourceConverterTest { +@ExtendWith(MockitoExtension.class) +class JacksonResourceConverterTest { private JacksonResourceConverter converter; @Mock private ObjectMapper objectMapper; - @Before - public void setUp() { + @BeforeEach + void setUp() { converter = new JacksonResourceConverter(); } @Test - public void canConvert_ReturnsTrue() { + void canConvert_ReturnsTrue() { assertThat(converter.getDestinationType()).isEqualTo(Object.class); } @Test - public void convert_GivenJsonStringAndValidStructuredPojo_ReturnsMappedPojo() throws Exception { + void convert_GivenJsonStringAndValidStructuredPojo_ReturnsMappedPojo() throws Exception { String resourceAsString = Resources.toString(Resources.getResource("hal-embedded.json"), Charset.defaultCharset()); InputStream resource = Mockito.spy(new ByteArrayInputStream(resourceAsString.getBytes(StandardCharsets.UTF_8))); @@ -59,7 +59,7 @@ public void convert_GivenJsonStringAndValidStructuredPojo_ReturnsMappedPojo() th } @Test - public void convert_GivenTheObjectMapperThrowsJacksonException_WrapsInConversionException() throws Exception { + void convert_GivenTheObjectMapperThrowsJacksonException_WrapsInConversionException() throws Exception { final String resourceAsString = "{}"; JsonProcessingException jsonProcessingException = Mockito.mock(JsonProcessingException.class); when(objectMapper.readValue(resourceAsString, Domains.class)).thenThrow(jsonProcessingException); @@ -77,7 +77,7 @@ public void convert_GivenTheObjectMapperThrowsJacksonException_WrapsInConversion } @Test - public void convert_GivenTheObjectMapperThrowsARuntimeException_WrapsInConversionException() throws Exception { + void convert_GivenTheObjectMapperThrowsARuntimeException_WrapsInConversionException() throws Exception { final String resourceAsString = "{}"; RuntimeException runtimeException = new RuntimeException("Error happened"); when(objectMapper.readValue(resourceAsString, Domains.class)).thenThrow(runtimeException); From 3fc04dd00bf18e65ed109e2abdb2196445111dcd Mon Sep 17 00:00:00 2001 From: "ibrahim.atcha" Date: Thu, 2 Mar 2023 07:47:24 +0000 Subject: [PATCH 2/4] changes parmeterized test to use value source instead of method source --- .../co/autotrader/traverson/http/ResponseTest.java | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/http/ResponseTest.java b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/http/ResponseTest.java index 6c08db7..aea461d 100644 --- a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/http/ResponseTest.java +++ b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/http/ResponseTest.java @@ -4,14 +4,12 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import java.net.URI; import java.util.Map; -import java.util.stream.Stream; import static org.assertj.core.api.Assertions.assertThat; @@ -21,13 +19,6 @@ class ResponseTest { @Mock private Map headers; - private static Stream unsuccessfulStatusCodes() { - return Stream.of( - Arguments.of(500), - Arguments.of(404), - Arguments.of(302)); - } - @Test void pojo() { URI uri = URI.create("http://localhost"); @@ -45,7 +36,7 @@ void pojo() { } @ParameterizedTest(name = "given{0}StatusCode_isSuccessfulReturnsFalse") - @MethodSource("unsuccessfulStatusCodes") + @ValueSource(ints = {500, 404, 302}) void isSuccessful_GivenUnsuccessfulStatusCode_ReturnsFalse(int statusCode) { Response response = new Response(); response.setStatusCode(statusCode); From 5b64aaa625debfe091b800fb55cd1f756137fe12 Mon Sep 17 00:00:00 2001 From: "ibrahim.atcha" Date: Tue, 7 Mar 2023 16:07:27 +0000 Subject: [PATCH 3/4] refactors paramterized test classes --- .../hal/RelByArrayIndexDiscovererTest.java | 212 ++++++++++-------- .../hal/RelByArrayPropertyDiscovererTest.java | 163 ++++++++------ 2 files changed, 202 insertions(+), 173 deletions(-) diff --git a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/link/hal/RelByArrayIndexDiscovererTest.java b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/link/hal/RelByArrayIndexDiscovererTest.java index 85c3849..77ed471 100644 --- a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/link/hal/RelByArrayIndexDiscovererTest.java +++ b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/link/hal/RelByArrayIndexDiscovererTest.java @@ -3,139 +3,153 @@ import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.JSONObject; import com.google.common.io.Resources; -import org.assertj.core.api.Condition; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.api.Test; import uk.co.autotrader.traverson.exception.UnknownRelException; import java.io.IOException; import java.nio.charset.Charset; -import java.util.stream.Stream; import static com.google.common.io.Resources.getResource; -import static org.assertj.core.api.Assertions.anyOf; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.*; class RelByArrayIndexDiscovererTest { - private static Stream arrayIndexHandlers() { - return Stream.of( - Arguments.of(new LinksResolver()), - Arguments.of(new EmbeddedResolver()) - ); - } - - private RelByArrayIndexDiscoverer testHandler; + private static final LinksResolver LINKS_RESOLVER = new LinksResolver(); + private static final EmbeddedResolver EMBEDDED_RESOLVER = new EmbeddedResolver(); + private final RelByArrayIndexDiscoverer testHandler = new RelByArrayIndexDiscoverer(LINKS_RESOLVER, EMBEDDED_RESOLVER); - @ParameterizedTest - @MethodSource("arrayIndexHandlers") - void findHref_GivenNonMatchingSyntax_ReturnsNull(HalEntityResolver testEntityResolver) throws Exception { - testHandler = new RelByArrayIndexDiscoverer(testEntityResolver); + @Test + void findHref_GivenNonMatchingSyntax_ReturnsNull() throws Exception { assertThat(this.testHandler.findHref(testJson(), "self")).isNull(); } - @ParameterizedTest - @MethodSource("arrayIndexHandlers") - void findHref_GivenNonNumber_ReturnsNull(HalEntityResolver testEntityResolver) throws Exception { - testHandler = new RelByArrayIndexDiscoverer(testEntityResolver); + @Test + void findHref_GivenNonNumber_ReturnsNull() throws Exception { assertThat(this.testHandler.findHref(testJson(), "array[first]")).isNull(); } - @ParameterizedTest - @MethodSource("arrayIndexHandlers") - void findHref_GivenNegativeNumber_ReturnsNull(HalEntityResolver testEntityResolver) throws Exception { - testHandler = new RelByArrayIndexDiscoverer(testEntityResolver); + @Test + void findHref_GivenNegativeNumber_ReturnsNull() throws Exception { assertThat(this.testHandler.findHref(testJson(), "array[-1]")).isNull(); } - @ParameterizedTest - @MethodSource("arrayIndexHandlers") - void findHref_GivenRelDoesntExist_throwsException(HalEntityResolver testEntityResolver) throws Exception { - try { - testHandler = new RelByArrayIndexDiscoverer(testEntityResolver); + @Test + void findHref_GivenLinksResolverAndRelDoesntExist_throwsException() { + RelByArrayIndexDiscoverer linksResolverHandler = new RelByArrayIndexDiscoverer(LINKS_RESOLVER); + + assertThatThrownBy(() -> { + linksResolverHandler.findHref(testJson(), "doesnt-exist[0]"); + }).isInstanceOf(UnknownRelException.class) + .hasMessage("Rel 'doesnt-exist' with an item at index '0' not found in {'_links'=[array, not-array, self]}") + .hasMessageNotContaining("_embedded"); + } + + @Test + void findHref_GivenEmbeddedResolverAndRelDoesntExist_throwsException() { + RelByArrayIndexDiscoverer embeddedResolverHandler = new RelByArrayIndexDiscoverer(EMBEDDED_RESOLVER); + + assertThatThrownBy(() -> { + embeddedResolverHandler.findHref(testJson(), "doesnt-exist[0]"); + }).isInstanceOf(UnknownRelException.class) + .hasMessage("Rel 'doesnt-exist' with an item at index '0' not found in {'_embedded'=[array, not-array]}") + .hasMessageNotContaining("_links"); + } + + @Test + void findHref_GivenBothResolversAndRelDoesntExist_throwsException() { + assertThatThrownBy(() -> { this.testHandler.findHref(testJson(), "doesnt-exist[0]"); - fail("Should throw exception"); - } catch (UnknownRelException e) { - assertThat(e) - .hasMessageContaining("Rel 'doesnt-exist' with an item at index '0' not found in") - .has(anyOf( - messageContaining("{'_links'=[array, not-array, self]}"), - messageContaining("{'_embedded'=[array, not-array]}"))); - } - } - - @ParameterizedTest - @MethodSource("arrayIndexHandlers") - void findHref_GivenNonArrayRel_throwsException(HalEntityResolver testEntityResolver) throws Exception { - try { - testHandler = new RelByArrayIndexDiscoverer(testEntityResolver); + }).isInstanceOf(UnknownRelException.class) + .hasMessageContaining("Rel 'doesnt-exist' with an item at index '0' not found in") + .hasMessageContaining("'_embedded'=[array, not-array]") + .hasMessageContaining("'_links'=[array, not-array, self]"); + } + + @Test + void findHref_GivenLinksResolverAndNonArrayRel_throwsException() { + RelByArrayIndexDiscoverer linksResolverHandler = new RelByArrayIndexDiscoverer(LINKS_RESOLVER); + + assertThatThrownBy(() -> { + linksResolverHandler.findHref(testJson(), "not-array[0]"); + }).isInstanceOf(UnknownRelException.class) + .hasMessage("Rel 'not-array' with an item at index '0' not found in {'_links'=[array, not-array, self]}"); + } + + @Test + void findHref_GivenEmbeddedResolverAndNonArrayRel_throwsException() { + RelByArrayIndexDiscoverer embeddedResolverHandler = new RelByArrayIndexDiscoverer(EMBEDDED_RESOLVER); + + assertThatThrownBy(() -> { + embeddedResolverHandler.findHref(testJson(), "not-array[0]"); + }).isInstanceOf(UnknownRelException.class) + .hasMessage("Rel 'not-array' with an item at index '0' not found in {'_embedded'=[array, not-array]}") + .hasMessageNotContaining("_links"); + } + + @Test + void findHref_GivenBothResolversAndNonArrayRel_throwsException() { + assertThatThrownBy(() -> { this.testHandler.findHref(testJson(), "not-array[0]"); - fail("Should throw exception"); - } catch (UnknownRelException e) { - assertThat(e) - .hasMessageContaining("Rel 'not-array' with an item at index '0' not found in") - .has(anyOf( - messageContaining("{'_links'=[array, not-array, self]}"), - messageContaining("{'_embedded'=[array, not-array]}"))); - } - } - - @ParameterizedTest - @MethodSource("arrayIndexHandlers") - void findHref_GivenResourceWithNoEmbeddedAndUnknownRel_throwsException(HalEntityResolver testEntityResolver) throws Exception { - try { - JSONObject resource = JSON.parseObject(Resources.toString(getResource("hal-simple.json"), Charset.defaultCharset())); - testHandler = new RelByArrayIndexDiscoverer(testEntityResolver); + }).isInstanceOf(UnknownRelException.class) + .hasMessageContaining("Rel 'not-array' with an item at index '0' not found in") + .hasMessageContaining("'_embedded'=[array, not-array]") + .hasMessageContaining("'_links'=[array, not-array, self]"); + } + + @Test + void findHref_GivenResourceWithNoEmbeddedAndUnknownRel_throwsException() throws Exception { + JSONObject resource = JSON.parseObject(Resources.toString(getResource("hal-simple.json"), Charset.defaultCharset())); + + assertThatThrownBy(() -> { this.testHandler.findHref(resource, "not-exists[0]"); - fail("Should throw exception"); - } catch (UnknownRelException e) { - assertThat(e).hasMessageContaining("Rel 'not-exists' with an item at index '0' not found in"); - assertThat(e.getMessage()).doesNotContain("_embedded"); - } + }).isInstanceOf(UnknownRelException.class) + .hasMessageContaining("Rel 'not-exists' with an item at index '0' not found in") + .hasMessageNotContaining("_embedded"); } - @ParameterizedTest - @MethodSource("arrayIndexHandlers") - void findHref_GivenArrayPosition_ReturnsHref(HalEntityResolver testEntityResolver) throws Exception { - testHandler = new RelByArrayIndexDiscoverer(testEntityResolver); + @Test + void findHref_GivenArrayPosition_ReturnsHref() throws Exception { assertThat(this.testHandler.findHref(testJson(), "array[0]")).isEqualTo("http://first"); } - @ParameterizedTest - @MethodSource("arrayIndexHandlers") - void findHref_GivenSecondArrayPosition_ReturnsHref(HalEntityResolver testEntityResolver) throws Exception { - testHandler = new RelByArrayIndexDiscoverer(testEntityResolver); + @Test + void findHref_GivenSecondArrayPosition_ReturnsHref() throws Exception { assertThat(this.testHandler.findHref(testJson(), "array[1]")).isEqualTo("http://second"); } - @ParameterizedTest - @MethodSource("arrayIndexHandlers") - void findHref_GivenNonExistentArrayPosition_throwsException(HalEntityResolver testEntityResolver) throws Exception { - try { - testHandler = new RelByArrayIndexDiscoverer(testEntityResolver); + @Test + void findHref_GivenLinksResolverAndNonExistentArrayPosition_throwsException() { + RelByArrayIndexDiscoverer linksResolverHandler = new RelByArrayIndexDiscoverer(LINKS_RESOLVER); + + assertThatThrownBy(() -> { + linksResolverHandler.findHref(testJson(), "array[2]"); + }).isInstanceOf(UnknownRelException.class) + .hasMessage("Rel 'array' with an item at index '2' not found in {'_links'=[array, not-array, self]}") + .hasMessageNotContaining("_embedded"); + } + + @Test + void findHref_GivenEmbeddedResolverAndNonExistentArrayPosition_throwsException() { + RelByArrayIndexDiscoverer embeddedResolverHandler = new RelByArrayIndexDiscoverer(EMBEDDED_RESOLVER); + + assertThatThrownBy(() -> { + embeddedResolverHandler.findHref(testJson(), "array[2]"); + }).isInstanceOf(UnknownRelException.class) + .hasMessage("Rel 'array' with an item at index '2' not found in {'_embedded'=[array, not-array]}") + .hasMessageNotContaining("_links"); + } + + @Test + void findHref_GivenBothResolverAndNonExistentArrayPosition_throwsException() { + assertThatThrownBy(() -> { this.testHandler.findHref(testJson(), "array[2]"); - fail("Should throw exception"); - } catch (UnknownRelException e) { - assertThat(e) - .hasMessageContaining("Rel 'array' with an item at index '2' not found in") - .has(anyOf( - messageContaining("{'_links'=[array, not-array, self]}"), - messageContaining("{'_embedded'=[array, not-array]}"))); - } + }).isInstanceOf(UnknownRelException.class) + .hasMessageContaining("Rel 'array' with an item at index '2' not found in") + .hasMessageContaining("'_embedded'=[array, not-array]") + .hasMessageContaining("'_links'=[array, not-array, self]"); } private JSONObject testJson() throws IOException { return JSON.parseObject(Resources.toString(getResource("hal-array-rels-test-data.json"), Charset.defaultCharset())); } - - private Condition messageContaining(final String expected) { - return new Condition() { - @Override - public boolean matches(Throwable thrown) { - return thrown.getMessage().contains(expected); - } - }.as("message contains %s", expected); - } } diff --git a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/link/hal/RelByArrayPropertyDiscovererTest.java b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/link/hal/RelByArrayPropertyDiscovererTest.java index 8ab7e27..49e9d47 100644 --- a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/link/hal/RelByArrayPropertyDiscovererTest.java +++ b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/link/hal/RelByArrayPropertyDiscovererTest.java @@ -4,106 +4,121 @@ import com.alibaba.fastjson2.JSONObject; import com.google.common.base.Charsets; import com.google.common.io.Resources; -import org.assertj.core.api.Condition; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.api.Test; import uk.co.autotrader.traverson.exception.UnknownRelException; -import java.util.stream.Stream; - import static com.google.common.io.Resources.getResource; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; -import static org.assertj.core.condition.AnyOf.anyOf; +import static org.assertj.core.api.Assertions.*; class RelByArrayPropertyDiscovererTest { - private static Stream handlers() { - return Stream.of( - Arguments.of(new LinksResolver()), - Arguments.of(new EmbeddedResolver()) - ); - } + private static final LinksResolver LINKS_RESOLVER = new LinksResolver(); + private static final EmbeddedResolver EMBEDDED_RESOLVER = new EmbeddedResolver(); - private RelByArrayPropertyDiscoverer testSubject; + private final RelByArrayPropertyDiscoverer testSubject = new RelByArrayPropertyDiscoverer(LINKS_RESOLVER, EMBEDDED_RESOLVER); - @ParameterizedTest - @MethodSource("handlers") - void findHref_GivenRelWithoutProperty_ReturnsNull(HalEntityResolver halEntityResolver) throws Exception { - testSubject = new RelByArrayPropertyDiscoverer(halEntityResolver); + @Test + void findHref_GivenRelWithoutProperty_ReturnsNull() throws Exception { assertThat(this.testSubject.findHref(testJson(), "self")).isNull(); } - @ParameterizedTest - @MethodSource("handlers") - void findHref_GivenNonExistentRel_throwsException(HalEntityResolver halEntityResolver) throws Exception { - try { - testSubject = new RelByArrayPropertyDiscoverer(halEntityResolver); - this.testSubject.findHref(testJson(), "non-existent[key:value]"); - fail("Should throw exception"); - } catch (UnknownRelException e) { - assertThat(e).hasMessageContaining("Rel 'non-existent' with an item with property 'key: value' not found in") - .has(anyOf( - messageContaining("{'_links'=[duplicates, not-array, section, self]"), - messageContaining("{'_embedded'=[duplicates, not-array, section]"))); - } + @Test + void findHref_GivenLinksResolverAndNonExistentRel_throwsException() { + RelByArrayPropertyDiscoverer discoverer = new RelByArrayPropertyDiscoverer(LINKS_RESOLVER); + + assertThatThrownBy(() -> { + discoverer.findHref(testJson(), "non-existent[key:value]"); + }).isInstanceOf(UnknownRelException.class) + .hasMessageContaining("Rel 'non-existent' with an item with property 'key: value' not found in {'_links'=[duplicates, not-array, section, self]") + .hasMessageNotContaining("_embedded"); + } + + @Test + void findHref_GivenEmbeddedResolverAndNonExistentRel_throwsException() { + RelByArrayPropertyDiscoverer discoverer = new RelByArrayPropertyDiscoverer(EMBEDDED_RESOLVER); + + assertThatThrownBy(() -> { + discoverer.findHref(testJson(), "non-existent[key:value]"); + }).isInstanceOf(UnknownRelException.class) + .hasMessageContaining("Rel 'non-existent' with an item with property 'key: value' not found in {'_embedded'=[duplicates, not-array, section]") + .hasMessageNotContaining("_links"); } - @ParameterizedTest - @MethodSource("handlers") - void findHref_GivenRelWithPropertyThatExists_ReturnsRelatedHref(HalEntityResolver halEntityResolver) throws Exception { - testSubject = new RelByArrayPropertyDiscoverer(halEntityResolver); + @Test + void findHref_GivenRelWithPropertyThatExists_ReturnsRelatedHref() throws Exception { assertThat(this.testSubject.findHref(testJson(), "section[name:turnip]")).isEqualTo("http://turnip-link"); } - @ParameterizedTest - @MethodSource("handlers") - void findHref_GivenRelWithPropertyNotExisting_throwsException(HalEntityResolver halEntityResolver) throws Exception { - try { - testSubject = new RelByArrayPropertyDiscoverer(halEntityResolver); + @Test + void findHref_GivenLinksResolverAndRelWithPropertyNotExisting_throwsException() { + RelByArrayPropertyDiscoverer discoverer = new RelByArrayPropertyDiscoverer(LINKS_RESOLVER); + + assertThatThrownBy(() -> { + discoverer.findHref(testJson(), "section[name:notexist]"); + }).isInstanceOf(UnknownRelException.class) + .hasMessageContaining("Rel 'section' with an item with property 'name: notexist' not found in {'_links'=[duplicates, not-array, section, self]") + .hasMessageNotContaining("_embedded"); + } + + @Test + void findHref_GivenEmbeddedResolverAndRelWithPropertyNotExisting_throwsException() { + RelByArrayPropertyDiscoverer discoverer = new RelByArrayPropertyDiscoverer(EMBEDDED_RESOLVER); + + assertThatThrownBy(() -> { + discoverer.findHref(testJson(), "section[name:notexist]"); + }).isInstanceOf(UnknownRelException.class) + .hasMessageContaining("Rel 'section' with an item with property 'name: notexist' not found in {'_embedded'=[duplicates, not-array, section]") + .hasMessageNotContaining("_links"); + } + + @Test + void findHref_GivenBothResolversAndRelWithPropertyNotExisting_throwsException() { + assertThatThrownBy(() -> { this.testSubject.findHref(testJson(), "section[name:notexist]"); - fail("Should throw exception"); - } catch (UnknownRelException e) { - assertThat(e).hasMessageContaining("Rel 'section' with an item with property 'name: notexist' not found in") - .has(anyOf( - messageContaining("{'_links'=[duplicates, not-array, section, self]"), - messageContaining("{'_embedded'=[duplicates, not-array, section]"))); - } + }).isInstanceOf(UnknownRelException.class) + .hasMessageContaining("Rel 'section' with an item with property 'name: notexist' not found in") + .hasMessageContaining("'_embedded'=[duplicates, not-array, section]") + .hasMessageContaining("'_links'=[duplicates, not-array, section, self]"); + } + + @Test + void findHref_GivenLinksResolverAndRelThatIsntArray_throwsException() { + RelByArrayPropertyDiscoverer discoverer = new RelByArrayPropertyDiscoverer(LINKS_RESOLVER); + + assertThatThrownBy(() -> { + discoverer.findHref(testJson(), "self[prop:value]"); + }).isInstanceOf(UnknownRelException.class) + .hasMessageContaining("Rel 'self' with an item with property 'prop: value' not found in {'_links'=[duplicates, not-array, section, self]") + .hasMessageNotContaining("_embedded"); } - @ParameterizedTest - @MethodSource("handlers") - void findHref_GivenRelThatIsntArray_throwsException(HalEntityResolver halEntityResolver) throws Exception { - try { - testSubject = new RelByArrayPropertyDiscoverer(halEntityResolver); + @Test + void findHref_GivenEmbeddedResolverAndRelThatIsntArray_throwsException() { + RelByArrayPropertyDiscoverer discoverer = new RelByArrayPropertyDiscoverer(EMBEDDED_RESOLVER); + + assertThatThrownBy(() -> { + discoverer.findHref(testJson(), "self[prop:value]"); + }).isInstanceOf(UnknownRelException.class) + .hasMessageContaining("Rel 'self' with an item with property 'prop: value' not found in {'_embedded'=[duplicates, not-array, section]") + .hasMessageNotContaining("_links"); + } + + @Test + void findHref_GivenBothResolversAndRelThatIsntArray_throwsException() { + assertThatThrownBy(() -> { this.testSubject.findHref(testJson(), "self[prop:value]"); - fail("Should throw exception"); - } catch (UnknownRelException e) { - assertThat(e).hasMessageContaining("Rel 'self' with an item with property 'prop: value' not found in") - .has(anyOf( - messageContaining("{'_links'=[duplicates, not-array, section, self]"), - messageContaining("{'_embedded'=[duplicates, not-array, section]"))); - } + }).isInstanceOf(UnknownRelException.class) + .hasMessageContaining("Rel 'self' with an item with property 'prop: value' not found in") + .hasMessageContaining("'_embedded'=[duplicates, not-array, section]") + .hasMessageContaining("'_links'=[duplicates, not-array, section, self]"); } - @ParameterizedTest - @MethodSource("handlers") - void findHref_GivenRelWithDuplicateMatchingProperties_ReturnsFirstMatch(HalEntityResolver halEntityResolver) throws Exception { - testSubject = new RelByArrayPropertyDiscoverer(halEntityResolver); + @Test + void findHref_GivenRelWithDuplicateMatchingProperties_ReturnsFirstMatch() throws Exception { assertThat(this.testSubject.findHref(testJson(), "duplicates[name:dupe]")).isEqualTo("http://duplicate-link-1"); } private JSONObject testJson() throws Exception { return JSON.parseObject(Resources.toString(getResource("hal-keyed-link-rels.json"), Charsets.UTF_8)); } - - private Condition messageContaining(final String expected) { - return new Condition() { - @Override - public boolean matches(Throwable thrown) { - return thrown.getMessage().contains(expected); - } - }.as("message contains %s", expected); - } } From dc10ddd05b3253a9f148706038b9244286b59d2f Mon Sep 17 00:00:00 2001 From: "ibrahim.atcha" Date: Tue, 7 Mar 2023 16:27:33 +0000 Subject: [PATCH 4/4] refactors tests that assert on exceptions --- .../TraversonBuilderFollowsTest.java | 26 +++++----- .../link/BasicLinkDiscovererTest.java | 11 ++--- .../traverson/link/HalLinkDiscovererTest.java | 39 ++++++--------- .../link/hal/LinksRelHandlerTest.java | 11 ++--- .../hal/RelByArrayIndexDiscovererTest.java | 49 +++++++------------ .../hal/RelByArrayPropertyDiscovererTest.java | 40 ++++++--------- 6 files changed, 68 insertions(+), 108 deletions(-) diff --git a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/TraversonBuilderFollowsTest.java b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/TraversonBuilderFollowsTest.java index b25e497..2f651e7 100644 --- a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/TraversonBuilderFollowsTest.java +++ b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/TraversonBuilderFollowsTest.java @@ -19,7 +19,7 @@ import static com.google.common.io.Resources.getResource; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; @@ -91,17 +91,15 @@ void follows_GivenRelByProperty_FollowsLinkInEmbeddedBlock() { @Test void follows_GivenRelByPropertyThatIsNotAnArray_throwsException() { - try { + assertThatThrownBy(() -> { this.testSubject.jsonHal() .from("hal-traverson-builder-data.json") .follow("makes[invalid:property]") .get(); - fail("Test should throw an exception for an unknown rel"); - } catch (UnknownRelException e) { - assertThat(e).hasMessageContaining("Rel 'makes' with an item with property 'invalid: property' not found in {") - .hasMessageContaining("'_links'=[makes, self, vegetables]") - .hasMessageContaining("'_embedded'=[ships, vegetables]"); - } + }).isInstanceOf(UnknownRelException.class) + .hasMessageContaining("Rel 'makes' with an item with property 'invalid: property' not found in {") + .hasMessageContaining("'_links'=[makes, self, vegetables]") + .hasMessageContaining("'_embedded'=[ships, vegetables]"); } @Test @@ -117,17 +115,15 @@ void follows_GivenRelByArrayMatchingBothLinksAndEmbedded_FollowsLinkInEmbeddedBl @Test void follows_GivenRelByArrayThatIsNotAnArray_throwsException() { - try { + assertThatThrownBy(() -> { this.testSubject.jsonHal() .from("hal-traverson-builder-data.json") .follow("makes[0]") .get(); - fail("Test should throw an exception for an unknown rel"); - } catch (UnknownRelException e) { - assertThat(e).hasMessageContaining("Rel 'makes' with an item at index '0' not found in {") - .hasMessageContaining("'_links'=[makes, self, vegetables]") - .hasMessageContaining("'_embedded'=[ships, vegetables]"); - } + }).isInstanceOf(UnknownRelException.class) + .hasMessageContaining("Rel 'makes' with an item at index '0' not found in {") + .hasMessageContaining("'_links'=[makes, self, vegetables]") + .hasMessageContaining("'_embedded'=[ships, vegetables]"); } @Test diff --git a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/link/BasicLinkDiscovererTest.java b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/link/BasicLinkDiscovererTest.java index 95a16aa..618dd93 100644 --- a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/link/BasicLinkDiscovererTest.java +++ b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/link/BasicLinkDiscovererTest.java @@ -12,7 +12,7 @@ import java.nio.charset.Charset; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatThrownBy; @ExtendWith(MockitoExtension.class) class BasicLinkDiscovererTest { @@ -38,11 +38,8 @@ void findHref_GivenBasicHypermediaResourceAndRelNotExisting_ThrowsException() th String fileContents = Resources.toString(Resources.getResource("basic-hypermedia-simple.json"), Charset.defaultCharset()); JSONObject json = JSON.parseObject(fileContents); - try { - linkDiscoverer.findHref(json, "NotExistingRel"); - fail("Test should throw exception for missing link"); - } catch (UnknownRelException e) { - assertThat(e).hasMessage("Rel NotExistingRel not found"); - } + assertThatThrownBy(() -> linkDiscoverer.findHref(json, "NotExistingRel")) + .isInstanceOf(UnknownRelException.class) + .hasMessage("Rel NotExistingRel not found"); } } diff --git a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/link/HalLinkDiscovererTest.java b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/link/HalLinkDiscovererTest.java index 1d9b53f..4b14751 100644 --- a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/link/HalLinkDiscovererTest.java +++ b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/link/HalLinkDiscovererTest.java @@ -15,8 +15,7 @@ import java.nio.charset.Charset; import static com.google.common.io.Resources.getResource; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.fail; +import static org.assertj.core.api.Assertions.*; @ExtendWith(MockitoExtension.class) class HalLinkDiscovererTest { @@ -40,13 +39,9 @@ void findHref_GivenHalResource_ReturnsSelfHref() throws Exception { void findHref_GivenRelDoesntExist_ThrowsUnknownRelException() throws Exception { JSONObject json = getJsonResource("hal-simple.json"); - try { - this.linkDiscoverer.findHref(json, "doesNotExist"); - fail("Test should throw exception for missing link"); - } catch (UnknownRelException e) { - assertThat(e).hasMessage("Rel doesNotExist not in the following [domains, self]"); - } - + assertThatThrownBy(() -> this.linkDiscoverer.findHref(json, "doesNotExist")) + .isInstanceOf(UnknownRelException.class) + .hasMessage("Rel doesNotExist not in the following [domains, self]"); } @Test @@ -98,14 +93,11 @@ void findHref_GivenHalResourceWithLinkArray_ReturnsMatchingHrefFromArray() throw void findHref_GivenPropertyBasedRelDoesntExist_throwsException() throws Exception { JSONObject json = getJsonResource("hal-traverson-builder-data.json"); - try { - this.linkDiscoverer.findHref(json, "non-existent[key:value]"); - fail("Should throw exception when rel not found"); - } catch (UnknownRelException e) { - assertThat(e).hasMessageContaining("Rel 'non-existent' with an item with property 'key: value' not found in {") - .hasMessageContaining("'_links'=[makes, self, vegetables]") - .hasMessageContaining("'_embedded'=[ships, vegetables]"); - } + assertThatThrownBy(() -> this.linkDiscoverer.findHref(json, "non-existent[key:value]")) + .isInstanceOf(UnknownRelException.class) + .hasMessageContaining("Rel 'non-existent' with an item with property 'key: value' not found in {") + .hasMessageContaining("'_links'=[makes, self, vegetables]") + .hasMessageContaining("'_embedded'=[ships, vegetables]"); } @Test @@ -121,14 +113,11 @@ void findHref_GivenHalResourceWithLinkArrayIndex_ReturnsMatchingHrefFromArray() void findHref_GivenNonExistentArrayIndex_throwsException() throws Exception { JSONObject json = getJsonResource("hal-traverson-builder-data.json"); - try { - this.linkDiscoverer.findHref(json, "non-existent[0]"); - fail("Should throw exception when rel not found"); - } catch (UnknownRelException e) { - assertThat(e).hasMessageContaining("Rel 'non-existent' with an item at index '0' not found in {") - .hasMessageContaining("'_links'=[makes, self, vegetables]") - .hasMessageContaining("'_embedded'=[ships, vegetables]"); - } + assertThatThrownBy(() -> this.linkDiscoverer.findHref(json, "non-existent[0]")) + .isInstanceOf(UnknownRelException.class) + .hasMessageContaining("Rel 'non-existent' with an item at index '0' not found in {") + .hasMessageContaining("'_links'=[makes, self, vegetables]") + .hasMessageContaining("'_embedded'=[ships, vegetables]"); } private JSONObject getJsonResource(String resourceName) throws IOException { diff --git a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/link/hal/LinksRelHandlerTest.java b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/link/hal/LinksRelHandlerTest.java index c4d2f5f..f7d1cef 100644 --- a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/link/hal/LinksRelHandlerTest.java +++ b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/link/hal/LinksRelHandlerTest.java @@ -12,7 +12,7 @@ import java.nio.charset.Charset; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatThrownBy; @ExtendWith(MockitoExtension.class) class LinksRelHandlerTest { @@ -39,11 +39,8 @@ void findHref_GivenJsonDoesNotContainExpectedRel_ThrowsException() throws Except String fileContents = Resources.toString(Resources.getResource("hal-simple.json"), Charset.defaultCharset()); JSONObject json = JSON.parseObject(fileContents); - try { - this.handler.findHref(json, "doesNotExist"); - fail("Test should throw exception for missing link"); - } catch (UnknownRelException e) { - assertThat(e).hasMessage("Rel doesNotExist not in the following [domains, self]"); - } + assertThatThrownBy(() -> this.handler.findHref(json, "doesNotExist")) + .isInstanceOf(UnknownRelException.class) + .hasMessage("Rel doesNotExist not in the following [domains, self]"); } } diff --git a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/link/hal/RelByArrayIndexDiscovererTest.java b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/link/hal/RelByArrayIndexDiscovererTest.java index 77ed471..e75b1a6 100644 --- a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/link/hal/RelByArrayIndexDiscovererTest.java +++ b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/link/hal/RelByArrayIndexDiscovererTest.java @@ -37,9 +37,8 @@ void findHref_GivenNegativeNumber_ReturnsNull() throws Exception { void findHref_GivenLinksResolverAndRelDoesntExist_throwsException() { RelByArrayIndexDiscoverer linksResolverHandler = new RelByArrayIndexDiscoverer(LINKS_RESOLVER); - assertThatThrownBy(() -> { - linksResolverHandler.findHref(testJson(), "doesnt-exist[0]"); - }).isInstanceOf(UnknownRelException.class) + assertThatThrownBy(() -> linksResolverHandler.findHref(testJson(), "doesnt-exist[0]")) + .isInstanceOf(UnknownRelException.class) .hasMessage("Rel 'doesnt-exist' with an item at index '0' not found in {'_links'=[array, not-array, self]}") .hasMessageNotContaining("_embedded"); } @@ -48,18 +47,16 @@ void findHref_GivenLinksResolverAndRelDoesntExist_throwsException() { void findHref_GivenEmbeddedResolverAndRelDoesntExist_throwsException() { RelByArrayIndexDiscoverer embeddedResolverHandler = new RelByArrayIndexDiscoverer(EMBEDDED_RESOLVER); - assertThatThrownBy(() -> { - embeddedResolverHandler.findHref(testJson(), "doesnt-exist[0]"); - }).isInstanceOf(UnknownRelException.class) + assertThatThrownBy(() -> embeddedResolverHandler.findHref(testJson(), "doesnt-exist[0]")) + .isInstanceOf(UnknownRelException.class) .hasMessage("Rel 'doesnt-exist' with an item at index '0' not found in {'_embedded'=[array, not-array]}") .hasMessageNotContaining("_links"); } @Test void findHref_GivenBothResolversAndRelDoesntExist_throwsException() { - assertThatThrownBy(() -> { - this.testHandler.findHref(testJson(), "doesnt-exist[0]"); - }).isInstanceOf(UnknownRelException.class) + assertThatThrownBy(() -> this.testHandler.findHref(testJson(), "doesnt-exist[0]")) + .isInstanceOf(UnknownRelException.class) .hasMessageContaining("Rel 'doesnt-exist' with an item at index '0' not found in") .hasMessageContaining("'_embedded'=[array, not-array]") .hasMessageContaining("'_links'=[array, not-array, self]"); @@ -69,9 +66,8 @@ void findHref_GivenBothResolversAndRelDoesntExist_throwsException() { void findHref_GivenLinksResolverAndNonArrayRel_throwsException() { RelByArrayIndexDiscoverer linksResolverHandler = new RelByArrayIndexDiscoverer(LINKS_RESOLVER); - assertThatThrownBy(() -> { - linksResolverHandler.findHref(testJson(), "not-array[0]"); - }).isInstanceOf(UnknownRelException.class) + assertThatThrownBy(() -> linksResolverHandler.findHref(testJson(), "not-array[0]")) + .isInstanceOf(UnknownRelException.class) .hasMessage("Rel 'not-array' with an item at index '0' not found in {'_links'=[array, not-array, self]}"); } @@ -79,18 +75,15 @@ void findHref_GivenLinksResolverAndNonArrayRel_throwsException() { void findHref_GivenEmbeddedResolverAndNonArrayRel_throwsException() { RelByArrayIndexDiscoverer embeddedResolverHandler = new RelByArrayIndexDiscoverer(EMBEDDED_RESOLVER); - assertThatThrownBy(() -> { - embeddedResolverHandler.findHref(testJson(), "not-array[0]"); - }).isInstanceOf(UnknownRelException.class) + assertThatThrownBy(() -> embeddedResolverHandler.findHref(testJson(), "not-array[0]")).isInstanceOf(UnknownRelException.class) .hasMessage("Rel 'not-array' with an item at index '0' not found in {'_embedded'=[array, not-array]}") .hasMessageNotContaining("_links"); } @Test void findHref_GivenBothResolversAndNonArrayRel_throwsException() { - assertThatThrownBy(() -> { - this.testHandler.findHref(testJson(), "not-array[0]"); - }).isInstanceOf(UnknownRelException.class) + assertThatThrownBy(() -> this.testHandler.findHref(testJson(), "not-array[0]")) + .isInstanceOf(UnknownRelException.class) .hasMessageContaining("Rel 'not-array' with an item at index '0' not found in") .hasMessageContaining("'_embedded'=[array, not-array]") .hasMessageContaining("'_links'=[array, not-array, self]"); @@ -100,9 +93,8 @@ void findHref_GivenBothResolversAndNonArrayRel_throwsException() { void findHref_GivenResourceWithNoEmbeddedAndUnknownRel_throwsException() throws Exception { JSONObject resource = JSON.parseObject(Resources.toString(getResource("hal-simple.json"), Charset.defaultCharset())); - assertThatThrownBy(() -> { - this.testHandler.findHref(resource, "not-exists[0]"); - }).isInstanceOf(UnknownRelException.class) + assertThatThrownBy(() -> this.testHandler.findHref(resource, "not-exists[0]")) + .isInstanceOf(UnknownRelException.class) .hasMessageContaining("Rel 'not-exists' with an item at index '0' not found in") .hasMessageNotContaining("_embedded"); } @@ -121,9 +113,8 @@ void findHref_GivenSecondArrayPosition_ReturnsHref() throws Exception { void findHref_GivenLinksResolverAndNonExistentArrayPosition_throwsException() { RelByArrayIndexDiscoverer linksResolverHandler = new RelByArrayIndexDiscoverer(LINKS_RESOLVER); - assertThatThrownBy(() -> { - linksResolverHandler.findHref(testJson(), "array[2]"); - }).isInstanceOf(UnknownRelException.class) + assertThatThrownBy(() -> linksResolverHandler.findHref(testJson(), "array[2]")) + .isInstanceOf(UnknownRelException.class) .hasMessage("Rel 'array' with an item at index '2' not found in {'_links'=[array, not-array, self]}") .hasMessageNotContaining("_embedded"); } @@ -132,18 +123,16 @@ void findHref_GivenLinksResolverAndNonExistentArrayPosition_throwsException() { void findHref_GivenEmbeddedResolverAndNonExistentArrayPosition_throwsException() { RelByArrayIndexDiscoverer embeddedResolverHandler = new RelByArrayIndexDiscoverer(EMBEDDED_RESOLVER); - assertThatThrownBy(() -> { - embeddedResolverHandler.findHref(testJson(), "array[2]"); - }).isInstanceOf(UnknownRelException.class) + assertThatThrownBy(() -> embeddedResolverHandler.findHref(testJson(), "array[2]")) + .isInstanceOf(UnknownRelException.class) .hasMessage("Rel 'array' with an item at index '2' not found in {'_embedded'=[array, not-array]}") .hasMessageNotContaining("_links"); } @Test void findHref_GivenBothResolverAndNonExistentArrayPosition_throwsException() { - assertThatThrownBy(() -> { - this.testHandler.findHref(testJson(), "array[2]"); - }).isInstanceOf(UnknownRelException.class) + assertThatThrownBy(() -> this.testHandler.findHref(testJson(), "array[2]")) + .isInstanceOf(UnknownRelException.class) .hasMessageContaining("Rel 'array' with an item at index '2' not found in") .hasMessageContaining("'_embedded'=[array, not-array]") .hasMessageContaining("'_links'=[array, not-array, self]"); diff --git a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/link/hal/RelByArrayPropertyDiscovererTest.java b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/link/hal/RelByArrayPropertyDiscovererTest.java index 49e9d47..00515bd 100644 --- a/traverson4j-core/src/test/java/uk/co/autotrader/traverson/link/hal/RelByArrayPropertyDiscovererTest.java +++ b/traverson4j-core/src/test/java/uk/co/autotrader/traverson/link/hal/RelByArrayPropertyDiscovererTest.java @@ -26,9 +26,8 @@ void findHref_GivenRelWithoutProperty_ReturnsNull() throws Exception { void findHref_GivenLinksResolverAndNonExistentRel_throwsException() { RelByArrayPropertyDiscoverer discoverer = new RelByArrayPropertyDiscoverer(LINKS_RESOLVER); - assertThatThrownBy(() -> { - discoverer.findHref(testJson(), "non-existent[key:value]"); - }).isInstanceOf(UnknownRelException.class) + assertThatThrownBy(() -> discoverer.findHref(testJson(), "non-existent[key:value]")) + .isInstanceOf(UnknownRelException.class) .hasMessageContaining("Rel 'non-existent' with an item with property 'key: value' not found in {'_links'=[duplicates, not-array, section, self]") .hasMessageNotContaining("_embedded"); } @@ -37,9 +36,8 @@ void findHref_GivenLinksResolverAndNonExistentRel_throwsException() { void findHref_GivenEmbeddedResolverAndNonExistentRel_throwsException() { RelByArrayPropertyDiscoverer discoverer = new RelByArrayPropertyDiscoverer(EMBEDDED_RESOLVER); - assertThatThrownBy(() -> { - discoverer.findHref(testJson(), "non-existent[key:value]"); - }).isInstanceOf(UnknownRelException.class) + assertThatThrownBy(() -> discoverer.findHref(testJson(), "non-existent[key:value]")) + .isInstanceOf(UnknownRelException.class) .hasMessageContaining("Rel 'non-existent' with an item with property 'key: value' not found in {'_embedded'=[duplicates, not-array, section]") .hasMessageNotContaining("_links"); } @@ -53,9 +51,8 @@ void findHref_GivenRelWithPropertyThatExists_ReturnsRelatedHref() throws Excepti void findHref_GivenLinksResolverAndRelWithPropertyNotExisting_throwsException() { RelByArrayPropertyDiscoverer discoverer = new RelByArrayPropertyDiscoverer(LINKS_RESOLVER); - assertThatThrownBy(() -> { - discoverer.findHref(testJson(), "section[name:notexist]"); - }).isInstanceOf(UnknownRelException.class) + assertThatThrownBy(() -> discoverer.findHref(testJson(), "section[name:notexist]")) + .isInstanceOf(UnknownRelException.class) .hasMessageContaining("Rel 'section' with an item with property 'name: notexist' not found in {'_links'=[duplicates, not-array, section, self]") .hasMessageNotContaining("_embedded"); } @@ -64,18 +61,16 @@ void findHref_GivenLinksResolverAndRelWithPropertyNotExisting_throwsException() void findHref_GivenEmbeddedResolverAndRelWithPropertyNotExisting_throwsException() { RelByArrayPropertyDiscoverer discoverer = new RelByArrayPropertyDiscoverer(EMBEDDED_RESOLVER); - assertThatThrownBy(() -> { - discoverer.findHref(testJson(), "section[name:notexist]"); - }).isInstanceOf(UnknownRelException.class) + assertThatThrownBy(() -> discoverer.findHref(testJson(), "section[name:notexist]")) + .isInstanceOf(UnknownRelException.class) .hasMessageContaining("Rel 'section' with an item with property 'name: notexist' not found in {'_embedded'=[duplicates, not-array, section]") .hasMessageNotContaining("_links"); } @Test void findHref_GivenBothResolversAndRelWithPropertyNotExisting_throwsException() { - assertThatThrownBy(() -> { - this.testSubject.findHref(testJson(), "section[name:notexist]"); - }).isInstanceOf(UnknownRelException.class) + assertThatThrownBy(() -> this.testSubject.findHref(testJson(), "section[name:notexist]")) + .isInstanceOf(UnknownRelException.class) .hasMessageContaining("Rel 'section' with an item with property 'name: notexist' not found in") .hasMessageContaining("'_embedded'=[duplicates, not-array, section]") .hasMessageContaining("'_links'=[duplicates, not-array, section, self]"); @@ -85,9 +80,8 @@ void findHref_GivenBothResolversAndRelWithPropertyNotExisting_throwsException() void findHref_GivenLinksResolverAndRelThatIsntArray_throwsException() { RelByArrayPropertyDiscoverer discoverer = new RelByArrayPropertyDiscoverer(LINKS_RESOLVER); - assertThatThrownBy(() -> { - discoverer.findHref(testJson(), "self[prop:value]"); - }).isInstanceOf(UnknownRelException.class) + assertThatThrownBy(() -> discoverer.findHref(testJson(), "self[prop:value]")) + .isInstanceOf(UnknownRelException.class) .hasMessageContaining("Rel 'self' with an item with property 'prop: value' not found in {'_links'=[duplicates, not-array, section, self]") .hasMessageNotContaining("_embedded"); } @@ -96,18 +90,16 @@ void findHref_GivenLinksResolverAndRelThatIsntArray_throwsException() { void findHref_GivenEmbeddedResolverAndRelThatIsntArray_throwsException() { RelByArrayPropertyDiscoverer discoverer = new RelByArrayPropertyDiscoverer(EMBEDDED_RESOLVER); - assertThatThrownBy(() -> { - discoverer.findHref(testJson(), "self[prop:value]"); - }).isInstanceOf(UnknownRelException.class) + assertThatThrownBy(() -> discoverer.findHref(testJson(), "self[prop:value]")) + .isInstanceOf(UnknownRelException.class) .hasMessageContaining("Rel 'self' with an item with property 'prop: value' not found in {'_embedded'=[duplicates, not-array, section]") .hasMessageNotContaining("_links"); } @Test void findHref_GivenBothResolversAndRelThatIsntArray_throwsException() { - assertThatThrownBy(() -> { - this.testSubject.findHref(testJson(), "self[prop:value]"); - }).isInstanceOf(UnknownRelException.class) + assertThatThrownBy(() -> this.testSubject.findHref(testJson(), "self[prop:value]")) + .isInstanceOf(UnknownRelException.class) .hasMessageContaining("Rel 'self' with an item with property 'prop: value' not found in") .hasMessageContaining("'_embedded'=[duplicates, not-array, section]") .hasMessageContaining("'_links'=[duplicates, not-array, section, self]");