diff --git a/.mvn/jvm.config b/.mvn/jvm.config index 0e7dabeff..c79df8879 100644 --- a/.mvn/jvm.config +++ b/.mvn/jvm.config @@ -1 +1 @@ --Xmx1024m -XX:CICompilerCount=1 -XX:TieredStopAtLevel=1 -Djava.security.egd=file:/dev/./urandom \ No newline at end of file +-XX:CICompilerCount=1 -XX:TieredStopAtLevel=1 -Djava.security.egd=file:/dev/./urandom diff --git a/annotation-error-decoder/pom.xml b/annotation-error-decoder/pom.xml index 76f96f625..ed064f8e6 100644 --- a/annotation-error-decoder/pom.xml +++ b/annotation-error-decoder/pom.xml @@ -46,7 +46,12 @@ com.squareup.okhttp3 - mockwebserver + mockwebserver3-junit5 + test + + + org.junit.jupiter + junit-jupiter test diff --git a/annotation-error-decoder/src/test/java/feign/error/AbstractAnnotationErrorDecoderTest.java b/annotation-error-decoder/src/test/java/feign/error/AbstractAnnotationErrorDecoderTest.java index f7abdd15a..fcf501e9d 100644 --- a/annotation-error-decoder/src/test/java/feign/error/AbstractAnnotationErrorDecoderTest.java +++ b/annotation-error-decoder/src/test/java/feign/error/AbstractAnnotationErrorDecoderTest.java @@ -35,7 +35,7 @@ Response testResponse(int status) { } Response testResponse(int status, String body) { - return testResponse(status, body, new HashMap>()); + return testResponse(status, body, new HashMap<>()); } Response testResponse(int status, String body, Map> headers) { diff --git a/annotation-error-decoder/src/test/java/feign/error/AnnotationErrorDecoderAnnotationInheritanceTest.java b/annotation-error-decoder/src/test/java/feign/error/AnnotationErrorDecoderAnnotationInheritanceTest.java index f56b6ce89..ffdfd12b5 100644 --- a/annotation-error-decoder/src/test/java/feign/error/AnnotationErrorDecoderAnnotationInheritanceTest.java +++ b/annotation-error-decoder/src/test/java/feign/error/AnnotationErrorDecoderAnnotationInheritanceTest.java @@ -18,13 +18,9 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.Arrays; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; -@RunWith(Parameterized.class) public class AnnotationErrorDecoderAnnotationInheritanceTest extends AbstractAnnotationErrorDecoderTest< AnnotationErrorDecoderAnnotationInheritanceTest.TestClientInterfaceWithWithMetaAnnotation> { @@ -33,8 +29,6 @@ public Class interfaceAtTest() { return TestClientInterfaceWithWithMetaAnnotation.class; } - @Parameters( - name = "{0}: When error code ({1}) on method ({2}) should return exception type ({3})") public static Iterable data() { return Arrays.asList( new Object[][] { @@ -45,22 +39,24 @@ public static Iterable data() { {"Test Code Specific At Method", 403, "method2Test", MethodLevelNotFoundException.class}, {"Test Code Specific At Method", 404, "method2Test", ClassLevelNotFoundException.class}, }); - } + } // first data value (0) is default - @Parameter // first data value (0) is default public String testType; - - @Parameter(1) public int errorCode; - - @Parameter(2) public String method; - - @Parameter(3) public Class expectedExceptionClass; - @Test - public void test() throws Exception { + @MethodSource("data") + @ParameterizedTest( + name = "{0}: When error code ({1}) on method ({2}) should return exception type ({3})") + void test( + String testType, + int errorCode, + String method, + Class expectedExceptionClass) + throws Exception { + initAnnotationErrorDecoderAnnotationInheritanceTest( + testType, errorCode, method, expectedExceptionClass); AnnotationErrorDecoder decoder = AnnotationErrorDecoder.builderFor(TestClientInterfaceWithWithMetaAnnotation.class).build(); @@ -69,7 +65,7 @@ public void test() throws Exception { } @ClassError - interface TestClientInterfaceWithWithMetaAnnotation { + public static interface TestClientInterfaceWithWithMetaAnnotation { @MethodError void method1Test(); @@ -117,4 +113,15 @@ public MethodLevelDefaultException() {} static class MethodLevelNotFoundException extends Exception { public MethodLevelNotFoundException() {} } + + public void initAnnotationErrorDecoderAnnotationInheritanceTest( + String testType, + int errorCode, + String method, + Class expectedExceptionClass) { + this.testType = testType; + this.errorCode = errorCode; + this.method = method; + this.expectedExceptionClass = expectedExceptionClass; + } } diff --git a/annotation-error-decoder/src/test/java/feign/error/AnnotationErrorDecoderClassInheritanceTest.java b/annotation-error-decoder/src/test/java/feign/error/AnnotationErrorDecoderClassInheritanceTest.java index 175e887b2..61a69f2c3 100644 --- a/annotation-error-decoder/src/test/java/feign/error/AnnotationErrorDecoderClassInheritanceTest.java +++ b/annotation-error-decoder/src/test/java/feign/error/AnnotationErrorDecoderClassInheritanceTest.java @@ -24,13 +24,9 @@ import feign.error.AnnotationErrorDecoderClassInheritanceTest.ParentInterfaceWithErrorHandling.ServeErrorException; import feign.error.AnnotationErrorDecoderClassInheritanceTest.ParentInterfaceWithErrorHandling.UnauthenticatedOrUnauthorizedException; import java.util.Arrays; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; -@RunWith(Parameterized.class) public class AnnotationErrorDecoderClassInheritanceTest extends AbstractAnnotationErrorDecoderTest< AnnotationErrorDecoderClassInheritanceTest.GrandChild> { @@ -40,8 +36,6 @@ public Class interfaceAtTest() { return GrandChild.class; } - @Parameters( - name = "{0}: When error code ({1}) on method ({2}) should return exception type ({3})") public static Iterable data() { return Arrays.asList( new Object[][] { @@ -78,22 +72,24 @@ public static Iterable data() { {"Test Default At Method", 504, "method3Test", Method3DefaultException.class}, {"Test Default At Class", 504, "method2Test", ClassLevelDefaultException.class}, }); - } + } // first data value (0) is default - @Parameter // first data value (0) is default public String testType; - - @Parameter(1) public int errorCode; - - @Parameter(2) public String method; - - @Parameter(3) public Class expectedExceptionClass; - @Test - public void test() throws Exception { + @MethodSource("data") + @ParameterizedTest( + name = "{0}: When error code ({1}) on method ({2}) should return exception type ({3})") + void test( + String testType, + int errorCode, + String method, + Class expectedExceptionClass) + throws Exception { + initAnnotationErrorDecoderClassInheritanceTest( + testType, errorCode, method, expectedExceptionClass); AnnotationErrorDecoder decoder = AnnotationErrorDecoder.builderFor(GrandChild.class).build(); assertThat(decoder.decode(feignConfigKey(method), testResponse(errorCode)).getClass()) @@ -157,4 +153,15 @@ class ServeErrorException extends Exception {} abstract class Child implements ParentInterfaceWithErrorHandling {} abstract class GrandChild extends Child {} + + public void initAnnotationErrorDecoderClassInheritanceTest( + String testType, + int errorCode, + String method, + Class expectedExceptionClass) { + this.testType = testType; + this.errorCode = errorCode; + this.method = method; + this.expectedExceptionClass = expectedExceptionClass; + } } diff --git a/annotation-error-decoder/src/test/java/feign/error/AnnotationErrorDecoderExceptionConstructorsTest.java b/annotation-error-decoder/src/test/java/feign/error/AnnotationErrorDecoderExceptionConstructorsTest.java index f0bde7bff..b5e921ed1 100644 --- a/annotation-error-decoder/src/test/java/feign/error/AnnotationErrorDecoderExceptionConstructorsTest.java +++ b/annotation-error-decoder/src/test/java/feign/error/AnnotationErrorDecoderExceptionConstructorsTest.java @@ -13,21 +13,38 @@ */ package feign.error; -import static feign.error.AnnotationErrorDecoderExceptionConstructorsTest.TestClientInterfaceWithDifferentExceptionConstructors; -import static feign.error.AnnotationErrorDecoderExceptionConstructorsTest.TestClientInterfaceWithDifferentExceptionConstructors.*; import static org.assertj.core.api.Assertions.assertThat; import feign.Request; import feign.codec.Decoder; +import feign.error.AnnotationErrorDecoderExceptionConstructorsTest.TestClientInterfaceWithDifferentExceptionConstructors; +import feign.error.AnnotationErrorDecoderExceptionConstructorsTest.TestClientInterfaceWithDifferentExceptionConstructors.DeclaredDefaultConstructorException; +import feign.error.AnnotationErrorDecoderExceptionConstructorsTest.TestClientInterfaceWithDifferentExceptionConstructors.DeclaredDefaultConstructorWithOtherConstructorsException; +import feign.error.AnnotationErrorDecoderExceptionConstructorsTest.TestClientInterfaceWithDifferentExceptionConstructors.DefaultConstructorException; +import feign.error.AnnotationErrorDecoderExceptionConstructorsTest.TestClientInterfaceWithDifferentExceptionConstructors.DefinedConstructorWithAnnotationForBody; +import feign.error.AnnotationErrorDecoderExceptionConstructorsTest.TestClientInterfaceWithDifferentExceptionConstructors.DefinedConstructorWithAnnotationForBodyAndHeaders; +import feign.error.AnnotationErrorDecoderExceptionConstructorsTest.TestClientInterfaceWithDifferentExceptionConstructors.DefinedConstructorWithAnnotationForBodyAndHeadersSecondOrder; +import feign.error.AnnotationErrorDecoderExceptionConstructorsTest.TestClientInterfaceWithDifferentExceptionConstructors.DefinedConstructorWithAnnotationForHeaders; +import feign.error.AnnotationErrorDecoderExceptionConstructorsTest.TestClientInterfaceWithDifferentExceptionConstructors.DefinedConstructorWithAnnotationForHeadersButNotForBody; +import feign.error.AnnotationErrorDecoderExceptionConstructorsTest.TestClientInterfaceWithDifferentExceptionConstructors.DefinedConstructorWithAnnotationForNonSupportedBody; +import feign.error.AnnotationErrorDecoderExceptionConstructorsTest.TestClientInterfaceWithDifferentExceptionConstructors.DefinedConstructorWithAnnotationForOptionalBody; +import feign.error.AnnotationErrorDecoderExceptionConstructorsTest.TestClientInterfaceWithDifferentExceptionConstructors.DefinedConstructorWithNoAnnotationForBody; +import feign.error.AnnotationErrorDecoderExceptionConstructorsTest.TestClientInterfaceWithDifferentExceptionConstructors.DefinedConstructorWithRequest; +import feign.error.AnnotationErrorDecoderExceptionConstructorsTest.TestClientInterfaceWithDifferentExceptionConstructors.DefinedConstructorWithRequestAndAnnotationForResponseBody; +import feign.error.AnnotationErrorDecoderExceptionConstructorsTest.TestClientInterfaceWithDifferentExceptionConstructors.DefinedConstructorWithRequestAndResponseBody; +import feign.error.AnnotationErrorDecoderExceptionConstructorsTest.TestClientInterfaceWithDifferentExceptionConstructors.DefinedConstructorWithRequestAndResponseHeadersAndOptionalResponseBody; +import feign.error.AnnotationErrorDecoderExceptionConstructorsTest.TestClientInterfaceWithDifferentExceptionConstructors.DefinedConstructorWithRequestAndResponseHeadersAndResponseBody; +import feign.error.AnnotationErrorDecoderExceptionConstructorsTest.TestClientInterfaceWithDifferentExceptionConstructors.ParametersException; import feign.optionals.OptionalDecoder; -import java.util.*; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; - -@RunWith(Parameterized.class) +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + public class AnnotationErrorDecoderExceptionConstructorsTest extends AbstractAnnotationErrorDecoderTest< TestClientInterfaceWithDifferentExceptionConstructors> { @@ -43,8 +60,7 @@ public class AnnotationErrorDecoderExceptionConstructorsTest Request.Body.empty(), null); private static final feign.Request NO_REQUEST = null; - private static final Map> NON_NULL_HEADERS = - new HashMap>(); + private static final Map> NON_NULL_HEADERS = new HashMap<>(); private static final Map> NO_HEADERS = null; @Override @@ -52,8 +68,6 @@ public Class interfaceAtT return TestClientInterfaceWithDifferentExceptionConstructors.class; } - @Parameters( - name = "{0}: When error code ({1}) on method ({2}) should return exception type ({3})") public static Iterable data() { return Arrays.asList( new Object[][] { @@ -186,28 +200,33 @@ public static Iterable data() { NON_NULL_HEADERS } }); - } + } // first data value (0) is default - @Parameter // first data value (0) is default public String testName; - - @Parameter(1) public int errorCode; - - @Parameter(2) public Class expectedExceptionClass; - - @Parameter(3) public Object expectedRequest; - - @Parameter(4) public Object expectedBody; - - @Parameter(5) public Map> expectedHeaders; - @Test - public void test() throws Exception { + @MethodSource("data") + @ParameterizedTest( + name = "{0}: When error code ({1}) on method ({2}) should return exception type ({3})") + void test( + String testName, + int errorCode, + Class expectedExceptionClass, + Object expectedRequest, + Object expectedBody, + Map> expectedHeaders) + throws Exception { + initAnnotationErrorDecoderExceptionConstructorsTest( + testName, + errorCode, + expectedExceptionClass, + expectedRequest, + expectedBody, + expectedHeaders); AnnotationErrorDecoder decoder = AnnotationErrorDecoder.builderFor( TestClientInterfaceWithDifferentExceptionConstructors.class) @@ -226,8 +245,24 @@ public void test() throws Exception { assertThat(exception.headers()).isEqualTo(expectedHeaders); } - @Test - public void testIfExceptionIsNotInTheList() throws Exception { + @MethodSource("data") + @ParameterizedTest( + name = "{0}: When error code ({1}) on method ({2}) should return exception type ({3})") + void ifExceptionIsNotInTheList( + String testName, + int errorCode, + Class expectedExceptionClass, + Object expectedRequest, + Object expectedBody, + Map> expectedHeaders) + throws Exception { + initAnnotationErrorDecoderExceptionConstructorsTest( + testName, + errorCode, + expectedExceptionClass, + expectedRequest, + expectedBody, + expectedHeaders); AnnotationErrorDecoder decoder = AnnotationErrorDecoder.builderFor( TestClientInterfaceWithDifferentExceptionConstructors.class) @@ -649,4 +684,19 @@ public Map> headers() { } } } + + public void initAnnotationErrorDecoderExceptionConstructorsTest( + String testName, + int errorCode, + Class expectedExceptionClass, + Object expectedRequest, + Object expectedBody, + Map> expectedHeaders) { + this.testName = testName; + this.errorCode = errorCode; + this.expectedExceptionClass = expectedExceptionClass; + this.expectedRequest = expectedRequest; + this.expectedBody = expectedBody; + this.expectedHeaders = expectedHeaders; + } } diff --git a/annotation-error-decoder/src/test/java/feign/error/AnnotationErrorDecoderIllegalInterfacesTest.java b/annotation-error-decoder/src/test/java/feign/error/AnnotationErrorDecoderIllegalInterfacesTest.java index 562400e94..b79887fef 100644 --- a/annotation-error-decoder/src/test/java/feign/error/AnnotationErrorDecoderIllegalInterfacesTest.java +++ b/annotation-error-decoder/src/test/java/feign/error/AnnotationErrorDecoderIllegalInterfacesTest.java @@ -16,23 +16,15 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; +import feign.Request; import java.util.Arrays; import java.util.Collection; import java.util.Map; -import org.junit.Test; -import org.junit.runner.Request; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; - -@RunWith(Parameterized.class) +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + public class AnnotationErrorDecoderIllegalInterfacesTest { - @Parameters( - name = - "{index}: When building interface ({0}) should return exception type ({1}) with message" - + " ({2})") public static Iterable data() { return Arrays.asList( new Object[][] { @@ -72,19 +64,22 @@ public static Iterable data() { "Cannot have two parameters either without" } }); - } + } // first data value (0) is default - @Parameter // first data value (0) is default public Class testInterface; - - @Parameter(1) public Class expectedExceptionClass; - - @Parameter(2) public String messageStart; - @Test - public void test() throws Exception { + @MethodSource("data") + @ParameterizedTest( + name = + "{index}: When building interface ({0}) should return exception type ({1}) with message" + + " ({2})") + void test( + Class testInterface, Class expectedExceptionClass, String messageStart) + throws Exception { + initAnnotationErrorDecoderIllegalInterfacesTest( + testInterface, expectedExceptionClass, messageStart); try { AnnotationErrorDecoder.builderFor(testInterface).build(); fail("Should have thrown exception"); @@ -212,4 +207,11 @@ class BadException extends Exception { public BadException(@ResponseHeaders TestPojo headers1) {} } } + + public void initAnnotationErrorDecoderIllegalInterfacesTest( + Class testInterface, Class expectedExceptionClass, String messageStart) { + this.testInterface = testInterface; + this.expectedExceptionClass = expectedExceptionClass; + this.messageStart = messageStart; + } } diff --git a/annotation-error-decoder/src/test/java/feign/error/AnnotationErrorDecoderInheritanceClassLevelAnnotationTest.java b/annotation-error-decoder/src/test/java/feign/error/AnnotationErrorDecoderInheritanceClassLevelAnnotationTest.java index 860a43757..81bc31794 100644 --- a/annotation-error-decoder/src/test/java/feign/error/AnnotationErrorDecoderInheritanceClassLevelAnnotationTest.java +++ b/annotation-error-decoder/src/test/java/feign/error/AnnotationErrorDecoderInheritanceClassLevelAnnotationTest.java @@ -18,13 +18,9 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.Arrays; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; -@RunWith(Parameterized.class) public class AnnotationErrorDecoderInheritanceClassLevelAnnotationTest extends AbstractAnnotationErrorDecoderTest< AnnotationErrorDecoderInheritanceClassLevelAnnotationTest.SecondLevelInterface> { @@ -33,8 +29,6 @@ public Class interfaceAtTest() { return SecondLevelInterface.class; } - @Parameters( - name = "{0}: When error code ({1}) on method ({2}) should return exception type ({3})") public static Iterable data() { return Arrays.asList( new Object[][] { @@ -63,22 +57,24 @@ public static Iterable data() { SecondLevelMethodErrorHandlingException.class }, }); - } + } // first data value (0) is default - @Parameter // first data value (0) is default public String testType; - - @Parameter(1) public int errorCode; - - @Parameter(2) public String method; - - @Parameter(3) public Class expectedExceptionClass; - @Test - public void test() throws Exception { + @MethodSource("data") + @ParameterizedTest( + name = "{0}: When error code ({1}) on method ({2}) should return exception type ({3})") + void test( + String testType, + int errorCode, + String method, + Class expectedExceptionClass) + throws Exception { + initAnnotationErrorDecoderInheritanceClassLevelAnnotationTest( + testType, errorCode, method, expectedExceptionClass); AnnotationErrorDecoder decoder = AnnotationErrorDecoder.builderFor(SecondLevelInterface.class).build(); @@ -147,4 +143,15 @@ public SecondLevelClassAnnotationException() {} static class SecondLevelMethodErrorHandlingException extends Exception { public SecondLevelMethodErrorHandlingException() {} } + + public void initAnnotationErrorDecoderInheritanceClassLevelAnnotationTest( + String testType, + int errorCode, + String method, + Class expectedExceptionClass) { + this.testType = testType; + this.errorCode = errorCode; + this.method = method; + this.expectedExceptionClass = expectedExceptionClass; + } } diff --git a/annotation-error-decoder/src/test/java/feign/error/AnnotationErrorDecoderInheritanceMethodLevelAnnotationTest.java b/annotation-error-decoder/src/test/java/feign/error/AnnotationErrorDecoderInheritanceMethodLevelAnnotationTest.java index 6fe46d727..bb9ac837e 100644 --- a/annotation-error-decoder/src/test/java/feign/error/AnnotationErrorDecoderInheritanceMethodLevelAnnotationTest.java +++ b/annotation-error-decoder/src/test/java/feign/error/AnnotationErrorDecoderInheritanceMethodLevelAnnotationTest.java @@ -18,13 +18,9 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.Arrays; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; -@RunWith(Parameterized.class) public class AnnotationErrorDecoderInheritanceMethodLevelAnnotationTest extends AbstractAnnotationErrorDecoderTest< AnnotationErrorDecoderInheritanceMethodLevelAnnotationTest.SecondLevelInterface> { @@ -33,8 +29,6 @@ public Class interfaceAtTest() { return SecondLevelInterface.class; } - @Parameters( - name = "{0}: When error code ({1}) on method ({2}) should return exception type ({3})") public static Iterable data() { return Arrays.asList( new Object[][] { @@ -87,22 +81,24 @@ public static Iterable data() { MethodSecondLevelAnnotationException.class }, }); - } + } // first data value (0) is default - @Parameter // first data value (0) is default public String testType; - - @Parameter(1) public int errorCode; - - @Parameter(2) public String method; - - @Parameter(3) public Class expectedExceptionClass; - @Test - public void test() throws Exception { + @MethodSource("data") + @ParameterizedTest( + name = "{0}: When error code ({1}) on method ({2}) should return exception type ({3})") + void test( + String testType, + int errorCode, + String method, + Class expectedExceptionClass) + throws Exception { + initAnnotationErrorDecoderInheritanceMethodLevelAnnotationTest( + testType, errorCode, method, expectedExceptionClass); AnnotationErrorDecoder decoder = AnnotationErrorDecoder.builderFor(SecondLevelInterface.class).build(); @@ -129,9 +125,11 @@ interface TopLevelInterface { } interface SecondLevelInterface extends TopLevelInterface { + @Override @SecondLevelMethodErrorHandling void topLevelMethod2(); + @Override @ErrorHandling( codeSpecific = { @ErrorCodes( @@ -141,6 +139,7 @@ interface SecondLevelInterface extends TopLevelInterface { defaultException = MethodSecondLevelDefaultException.class) void topLevelMethod3(); + @Override @SecondLevelMethodErrorHandling void topLevelMethod4(); } @@ -188,4 +187,15 @@ public MethodSecondLevelErrorHandlingException() {} static class MethodSecondLevelAnnotationException extends Exception { public MethodSecondLevelAnnotationException() {} } + + public void initAnnotationErrorDecoderInheritanceMethodLevelAnnotationTest( + String testType, + int errorCode, + String method, + Class expectedExceptionClass) { + this.testType = testType; + this.errorCode = errorCode; + this.method = method; + this.expectedExceptionClass = expectedExceptionClass; + } } diff --git a/annotation-error-decoder/src/test/java/feign/error/AnnotationErrorDecoderInheritanceTest.java b/annotation-error-decoder/src/test/java/feign/error/AnnotationErrorDecoderInheritanceTest.java index c82c1daf2..5fb186e94 100644 --- a/annotation-error-decoder/src/test/java/feign/error/AnnotationErrorDecoderInheritanceTest.java +++ b/annotation-error-decoder/src/test/java/feign/error/AnnotationErrorDecoderInheritanceTest.java @@ -13,24 +13,20 @@ */ package feign.error; -import static feign.error.AnnotationErrorDecoderInheritanceTest.TestClientInterfaceWithExceptionPriority.ClassLevelDefaultException; -import static feign.error.AnnotationErrorDecoderInheritanceTest.TestClientInterfaceWithExceptionPriority.ClassLevelNotFoundException; -import static feign.error.AnnotationErrorDecoderInheritanceTest.TestClientInterfaceWithExceptionPriority.Method1DefaultException; -import static feign.error.AnnotationErrorDecoderInheritanceTest.TestClientInterfaceWithExceptionPriority.Method1NotFoundException; -import static feign.error.AnnotationErrorDecoderInheritanceTest.TestClientInterfaceWithExceptionPriority.Method2NotFoundException; -import static feign.error.AnnotationErrorDecoderInheritanceTest.TestClientInterfaceWithExceptionPriority.Method3DefaultException; -import static feign.error.AnnotationErrorDecoderInheritanceTest.TestClientInterfaceWithExceptionPriority.ServeErrorException; -import static feign.error.AnnotationErrorDecoderInheritanceTest.TestClientInterfaceWithExceptionPriority.UnauthenticatedOrUnauthorizedException; import static org.assertj.core.api.Assertions.assertThat; +import feign.error.AnnotationErrorDecoderInheritanceTest.TopLevelInterface.ClassLevelDefaultException; +import feign.error.AnnotationErrorDecoderInheritanceTest.TopLevelInterface.ClassLevelNotFoundException; +import feign.error.AnnotationErrorDecoderInheritanceTest.TopLevelInterface.Method1DefaultException; +import feign.error.AnnotationErrorDecoderInheritanceTest.TopLevelInterface.Method1NotFoundException; +import feign.error.AnnotationErrorDecoderInheritanceTest.TopLevelInterface.Method2NotFoundException; +import feign.error.AnnotationErrorDecoderInheritanceTest.TopLevelInterface.Method3DefaultException; +import feign.error.AnnotationErrorDecoderInheritanceTest.TopLevelInterface.ServeErrorException; +import feign.error.AnnotationErrorDecoderInheritanceTest.TopLevelInterface.UnauthenticatedOrUnauthorizedException; import java.util.Arrays; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; -@RunWith(Parameterized.class) public class AnnotationErrorDecoderInheritanceTest extends AbstractAnnotationErrorDecoderTest< AnnotationErrorDecoderInheritanceTest.TestClientInterfaceWithExceptionPriority> { @@ -40,8 +36,6 @@ public Class interfaceAtTest() { return TestClientInterfaceWithExceptionPriority.class; } - @Parameters( - name = "{0}: When error code ({1}) on method ({2}) should return exception type ({3})") public static Iterable data() { return Arrays.asList( new Object[][] { @@ -78,22 +72,23 @@ public static Iterable data() { {"Test Default At Method", 504, "method3Test", Method3DefaultException.class}, {"Test Default At Class", 504, "method2Test", ClassLevelDefaultException.class}, }); - } + } // first data value (0) is default - @Parameter // first data value (0) is default public String testType; - - @Parameter(1) public int errorCode; - - @Parameter(2) public String method; - - @Parameter(3) public Class expectedExceptionClass; - @Test - public void test() throws Exception { + @MethodSource("data") + @ParameterizedTest( + name = "{0}: When error code ({1}) on method ({2}) should return exception type ({3})") + void test( + String testType, + int errorCode, + String method, + Class expectedExceptionClass) + throws Exception { + initAnnotationErrorDecoderInheritanceTest(testType, errorCode, method, expectedExceptionClass); AnnotationErrorDecoder decoder = AnnotationErrorDecoder.builderFor(TestClientInterfaceWithExceptionPriority.class).build(); @@ -161,4 +156,15 @@ interface TestClientInterfaceWithExceptionPriority extends SecondLevelInterface @ErrorHandling(defaultException = Method3DefaultException.class) void method3Test(); } + + public void initAnnotationErrorDecoderInheritanceTest( + String testType, + int errorCode, + String method, + Class expectedExceptionClass) { + this.testType = testType; + this.errorCode = errorCode; + this.method = method; + this.expectedExceptionClass = expectedExceptionClass; + } } diff --git a/annotation-error-decoder/src/test/java/feign/error/AnnotationErrorDecoderNoAnnotationTest.java b/annotation-error-decoder/src/test/java/feign/error/AnnotationErrorDecoderNoAnnotationTest.java index dc734ca73..5304fca9e 100644 --- a/annotation-error-decoder/src/test/java/feign/error/AnnotationErrorDecoderNoAnnotationTest.java +++ b/annotation-error-decoder/src/test/java/feign/error/AnnotationErrorDecoderNoAnnotationTest.java @@ -13,12 +13,11 @@ */ package feign.error; -import static feign.error.AnnotationErrorDecoderNoAnnotationTest.*; import static org.assertj.core.api.Assertions.assertThat; -import feign.Response; import feign.codec.ErrorDecoder; -import org.junit.Test; +import feign.error.AnnotationErrorDecoderNoAnnotationTest.TestClientInterfaceWithNoAnnotations; +import org.junit.jupiter.api.Test; public class AnnotationErrorDecoderNoAnnotationTest extends AbstractAnnotationErrorDecoderTest { @@ -29,15 +28,9 @@ public Class interfaceAtTest() { } @Test - public void delegatesToDefaultErrorDecoder() throws Exception { - - ErrorDecoder defaultErrorDecoder = - new ErrorDecoder() { - @Override - public Exception decode(String methodKey, Response response) { - return new DefaultErrorDecoderException(); - } - }; + void delegatesToDefaultErrorDecoder() throws Exception { + + ErrorDecoder defaultErrorDecoder = (methodKey, response) -> new DefaultErrorDecoderException(); AnnotationErrorDecoder decoder = AnnotationErrorDecoder.builderFor(TestClientInterfaceWithNoAnnotations.class) diff --git a/annotation-error-decoder/src/test/java/feign/error/AnnotationErrorDecoderPriorityTest.java b/annotation-error-decoder/src/test/java/feign/error/AnnotationErrorDecoderPriorityTest.java index 884a75867..eab2b50d7 100644 --- a/annotation-error-decoder/src/test/java/feign/error/AnnotationErrorDecoderPriorityTest.java +++ b/annotation-error-decoder/src/test/java/feign/error/AnnotationErrorDecoderPriorityTest.java @@ -13,17 +13,20 @@ */ package feign.error; -import static feign.error.AnnotationErrorDecoderPriorityTest.TestClientInterfaceWithExceptionPriority.*; import static org.assertj.core.api.Assertions.assertThat; +import feign.error.AnnotationErrorDecoderPriorityTest.TestClientInterfaceWithExceptionPriority.ClassLevelDefaultException; +import feign.error.AnnotationErrorDecoderPriorityTest.TestClientInterfaceWithExceptionPriority.ClassLevelNotFoundException; +import feign.error.AnnotationErrorDecoderPriorityTest.TestClientInterfaceWithExceptionPriority.Method1DefaultException; +import feign.error.AnnotationErrorDecoderPriorityTest.TestClientInterfaceWithExceptionPriority.Method1NotFoundException; +import feign.error.AnnotationErrorDecoderPriorityTest.TestClientInterfaceWithExceptionPriority.Method2NotFoundException; +import feign.error.AnnotationErrorDecoderPriorityTest.TestClientInterfaceWithExceptionPriority.Method3DefaultException; +import feign.error.AnnotationErrorDecoderPriorityTest.TestClientInterfaceWithExceptionPriority.ServeErrorException; +import feign.error.AnnotationErrorDecoderPriorityTest.TestClientInterfaceWithExceptionPriority.UnauthenticatedOrUnauthorizedException; import java.util.Arrays; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; -@RunWith(Parameterized.class) public class AnnotationErrorDecoderPriorityTest extends AbstractAnnotationErrorDecoderTest< AnnotationErrorDecoderPriorityTest.TestClientInterfaceWithExceptionPriority> { @@ -33,8 +36,6 @@ public Class interfaceAtTest() { return TestClientInterfaceWithExceptionPriority.class; } - @Parameters( - name = "{0}: When error code ({1}) on method ({2}) should return exception type ({3})") public static Iterable data() { return Arrays.asList( new Object[][] { @@ -71,22 +72,23 @@ public static Iterable data() { {"Test Default At Method", 504, "method3Test", Method3DefaultException.class}, {"Test Default At Class", 504, "method2Test", ClassLevelDefaultException.class}, }); - } + } // first data value (0) is default - @Parameter // first data value (0) is default public String testType; - - @Parameter(1) public int errorCode; - - @Parameter(2) public String method; - - @Parameter(3) public Class expectedExceptionClass; - @Test - public void test() throws Exception { + @MethodSource("data") + @ParameterizedTest( + name = "{0}: When error code ({1}) on method ({2}) should return exception type ({3})") + void test( + String testType, + int errorCode, + String method, + Class expectedExceptionClass) + throws Exception { + initAnnotationErrorDecoderPriorityTest(testType, errorCode, method, expectedExceptionClass); AnnotationErrorDecoder decoder = AnnotationErrorDecoder.builderFor(TestClientInterfaceWithExceptionPriority.class).build(); @@ -147,4 +149,15 @@ class UnauthenticatedOrUnauthorizedException extends Exception {} class ServeErrorException extends Exception {} } + + public void initAnnotationErrorDecoderPriorityTest( + String testType, + int errorCode, + String method, + Class expectedExceptionClass) { + this.testType = testType; + this.errorCode = errorCode; + this.method = method; + this.expectedExceptionClass = expectedExceptionClass; + } } diff --git a/apt-test-generator/pom.xml b/apt-test-generator/pom.xml index e04395048..c58bbedc5 100644 --- a/apt-test-generator/pom.xml +++ b/apt-test-generator/pom.xml @@ -52,6 +52,12 @@ compile-testing 0.21.0 test + + + junit + junit + + org.slf4j diff --git a/apt-test-generator/src/test/java/feign/apttestgenerator/GenerateTestStubAPTTest.java b/apt-test-generator/src/test/java/feign/apttestgenerator/GenerateTestStubAPTTest.java index 210a620fe..bdada881a 100644 --- a/apt-test-generator/src/test/java/feign/apttestgenerator/GenerateTestStubAPTTest.java +++ b/apt-test-generator/src/test/java/feign/apttestgenerator/GenerateTestStubAPTTest.java @@ -19,15 +19,15 @@ import com.google.testing.compile.Compilation; import com.google.testing.compile.JavaFileObjects; import java.io.File; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Test for {@link GenerateTestStubAPT} */ -public class GenerateTestStubAPTTest { +class GenerateTestStubAPTTest { private final File main = new File("../example-github/src/main/java/").getAbsoluteFile(); @Test - public void test() throws Exception { + void test() throws Exception { final Compilation compilation = javac() .withProcessors(new GenerateTestStubAPT()) diff --git a/benchmark/pom.xml b/benchmark/pom.xml index d7c0163da..728d7017f 100644 --- a/benchmark/pom.xml +++ b/benchmark/pom.xml @@ -66,7 +66,7 @@ com.squareup.okhttp3 - mockwebserver + mockwebserver3-junit5 io.netty diff --git a/benchmark/src/main/java/feign/benchmark/WhatShouldWeCacheBenchmarks.java b/benchmark/src/main/java/feign/benchmark/WhatShouldWeCacheBenchmarks.java index c3dd1a0a4..f0dea47a4 100644 --- a/benchmark/src/main/java/feign/benchmark/WhatShouldWeCacheBenchmarks.java +++ b/benchmark/src/main/java/feign/benchmark/WhatShouldWeCacheBenchmarks.java @@ -17,10 +17,8 @@ import feign.Contract; import feign.Feign; import feign.MethodMetadata; -import feign.Request; import feign.Response; import feign.Target.HardCodedTarget; -import java.io.IOException; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; @@ -64,18 +62,15 @@ public List parseAndValidateMetadata(Class declaring) { } }; fakeClient = - new Client() { - public Response execute(Request request, Request.Options options) throws IOException { - Map> headers = - new LinkedHashMap>(); - return Response.builder() - .body((byte[]) null) - .status(200) - .headers(headers) - .reason("ok") - .request(request) - .build(); - } + (request, options) -> { + Map> headers = new LinkedHashMap>(); + return Response.builder() + .body((byte[]) null) + .status(200) + .headers(headers) + .reason("ok") + .request(request) + .build(); }; cachedFakeFeign = Feign.builder().client(fakeClient).build(); cachedFakeApi = diff --git a/core/pom.xml b/core/pom.xml index ffb3a535f..fd71e0569 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -34,7 +34,12 @@ com.squareup.okhttp3 - mockwebserver + mockwebserver3-junit5 + test + + + org.junit.jupiter + junit-jupiter test @@ -57,12 +62,6 @@ test - - org.hamcrest - hamcrest - test - - org.mockito mockito-core diff --git a/core/src/main/java/feign/AsynchronousMethodHandler.java b/core/src/main/java/feign/AsynchronousMethodHandler.java index 6dc327433..266d5594c 100644 --- a/core/src/main/java/feign/AsynchronousMethodHandler.java +++ b/core/src/main/java/feign/AsynchronousMethodHandler.java @@ -186,10 +186,9 @@ private CompletableFuture executeAndDecode(RequestTemplate template, Opt return client .execute(request, options, Optional.ofNullable(requestContext)) .thenApply( - response -> { - // TODO: remove in Feign 12 - return ensureRequestIsSet(response, template, request); - }) + response -> + // TODO: remove in Feign 12 + ensureRequestIsSet(response, template, request)) .exceptionally( throwable -> { CompletionException completionException = diff --git a/core/src/test/java/feign/AlwaysEncodeBodyContractTest.java b/core/src/test/java/feign/AlwaysEncodeBodyContractTest.java index 8b7ea6c15..a6857fd4e 100644 --- a/core/src/test/java/feign/AlwaysEncodeBodyContractTest.java +++ b/core/src/test/java/feign/AlwaysEncodeBodyContractTest.java @@ -14,6 +14,7 @@ package feign; import static java.lang.annotation.RetentionPolicy.RUNTIME; +import static org.assertj.core.api.Assertions.assertThat; import feign.codec.EncodeException; import feign.codec.Encoder; @@ -24,10 +25,9 @@ import java.lang.reflect.Type; import java.util.Arrays; import java.util.stream.Collectors; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class AlwaysEncodeBodyContractTest { +class AlwaysEncodeBodyContractTest { @Retention(RUNTIME) @Target(ElementType.METHOD) @@ -87,14 +87,14 @@ public Response execute(Request request, Request.Options options) throws IOExcep * non-annotated parameters the client method has, as alwaysEncodeBody is set to true. */ @Test - public void alwaysEncodeBodyTrueTest() { + void alwaysEncodeBodyTrueTest() { SampleTargetMultipleNonAnnotatedParameters sampleClient1 = Feign.builder() .contract(new SampleContract()) .encoder(new AllParametersSampleEncoder()) .client(new SampleClient()) .target(SampleTargetMultipleNonAnnotatedParameters.class, "http://localhost"); - Assert.assertEquals("foobarchar", sampleClient1.concatenate("foo", "bar", "char")); + assertThat(sampleClient1.concatenate("foo", "bar", "char")).isEqualTo("foobarchar"); SampleTargetNoParameters sampleClient2 = Feign.builder() @@ -102,7 +102,7 @@ public void alwaysEncodeBodyTrueTest() { .encoder(new AllParametersSampleEncoder()) .client(new SampleClient()) .target(SampleTargetNoParameters.class, "http://localhost"); - Assert.assertEquals("", sampleClient2.concatenate()); + assertThat(sampleClient2.concatenate()).isEqualTo(""); SampleTargetOneParameter sampleClient3 = Feign.builder() @@ -110,6 +110,6 @@ public void alwaysEncodeBodyTrueTest() { .encoder(new AllParametersSampleEncoder()) .client(new SampleClient()) .target(SampleTargetOneParameter.class, "http://localhost"); - Assert.assertEquals("moo", sampleClient3.concatenate("moo")); + assertThat(sampleClient3.concatenate("moo")).isEqualTo("moo"); } } diff --git a/core/src/test/java/feign/AsyncFeignTest.java b/core/src/test/java/feign/AsyncFeignTest.java index e3991451a..cb7be7a04 100644 --- a/core/src/test/java/feign/AsyncFeignTest.java +++ b/core/src/test/java/feign/AsyncFeignTest.java @@ -16,10 +16,12 @@ import static feign.ExceptionPropagationPolicy.UNWRAP; import static feign.Util.UTF_8; import static feign.assertj.MockWebServerAssertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; import static org.assertj.core.data.MapEntry.entry; -import static org.hamcrest.CoreMatchers.isA; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; @@ -58,23 +60,20 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.MockWebServer; +import mockwebserver3.MockResponse; +import mockwebserver3.MockWebServer; import okio.Buffer; -import org.junit.Ignore; -import org.junit.Rule; -import org.junit.Test; -import org.junit.jupiter.params.provider.ValueSource; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; public class AsyncFeignTest { private static final Long NON_RETRYABLE = null; - @Rule public final ExpectedException thrown = ExpectedException.none(); - @Rule public final MockWebServer server = new MockWebServer(); + public final MockWebServer server = new MockWebServer(); @Test - public void iterableQueryParams() throws Exception { + void iterableQueryParams() throws Exception { server.enqueue(new MockResponse().setBody("foo")); TestInterfaceAsync api = @@ -86,7 +85,7 @@ public void iterableQueryParams() throws Exception { } @Test - public void postTemplateParamsResolve() throws Exception { + void postTemplateParamsResolve() throws Exception { server.enqueue(new MockResponse().setBody("foo")); TestInterfaceAsync api = @@ -101,7 +100,7 @@ public void postTemplateParamsResolve() throws Exception { } @Test - public void postFormParams() throws Exception { + void postFormParams() throws Exception { server.enqueue(new MockResponse().setBody("foo")); TestInterfaceAsync api = @@ -117,7 +116,7 @@ public void postFormParams() throws Exception { } @Test - public void postBodyParam() throws Exception { + void postBodyParam() throws Exception { server.enqueue(new MockResponse().setBody("foo")); TestInterfaceAsync api = @@ -137,7 +136,7 @@ public void postBodyParam() throws Exception { * type. */ @Test - public void bodyTypeCorrespondsWithParameterType() throws Exception { + void bodyTypeCorrespondsWithParameterType() throws Exception { server.enqueue(new MockResponse().setBody("foo")); final AtomicReference encodedType = new AtomicReference<>(); @@ -162,7 +161,7 @@ public void encode(Object object, Type bodyType, RequestTemplate template) { } @Test - public void postGZIPEncodedBodyParam() throws Exception { + void postGZIPEncodedBodyParam() throws Exception { server.enqueue(new MockResponse().setBody("foo")); TestInterfaceAsync api = @@ -178,7 +177,7 @@ public void postGZIPEncodedBodyParam() throws Exception { } @Test - public void postDeflateEncodedBodyParam() throws Exception { + void postDeflateEncodedBodyParam() throws Exception { server.enqueue(new MockResponse().setBody("foo")); TestInterfaceAsync api = @@ -194,7 +193,7 @@ public void postDeflateEncodedBodyParam() throws Exception { } @Test - public void singleInterceptor() throws Exception { + void singleInterceptor() throws Exception { server.enqueue(new MockResponse().setBody("foo")); TestInterfaceAsync api = @@ -211,7 +210,7 @@ public void singleInterceptor() throws Exception { } @Test - public void multipleInterceptor() throws Exception { + void multipleInterceptor() throws Exception { server.enqueue(new MockResponse().setBody("foo")); TestInterfaceAsync api = @@ -231,7 +230,7 @@ public void multipleInterceptor() throws Exception { } @Test - public void customExpander() throws Exception { + void customExpander() throws Exception { server.enqueue(new MockResponse()); TestInterfaceAsync api = @@ -245,7 +244,7 @@ public void customExpander() throws Exception { } @Test - public void customExpanderListParam() throws Exception { + void customExpanderListParam() throws Exception { server.enqueue(new MockResponse()); TestInterfaceAsync api = @@ -260,7 +259,7 @@ public void customExpanderListParam() throws Exception { } @Test - public void customExpanderNullParam() throws Exception { + void customExpanderNullParam() throws Exception { server.enqueue(new MockResponse()); TestInterfaceAsync api = @@ -274,7 +273,7 @@ public void customExpanderNullParam() throws Exception { } @Test - public void headerMap() throws Exception { + void headerMap() throws Exception { server.enqueue(new MockResponse()); TestInterfaceAsync api = @@ -294,7 +293,7 @@ public void headerMap() throws Exception { } @Test - public void headerMapWithHeaderAnnotations() throws Exception { + void headerMapWithHeaderAnnotations() throws Exception { server.enqueue(new MockResponse()); TestInterfaceAsync api = @@ -328,7 +327,7 @@ public void headerMapWithHeaderAnnotations() throws Exception { } @Test - public void queryMap() throws Exception { + void queryMap() throws Exception { server.enqueue(new MockResponse()); TestInterfaceAsync api = @@ -345,7 +344,7 @@ public void queryMap() throws Exception { } @Test - public void queryMapIterableValuesExpanded() throws Exception { + void queryMapIterableValuesExpanded() throws Exception { server.enqueue(new MockResponse()); TestInterfaceAsync api = @@ -354,7 +353,7 @@ public void queryMapIterableValuesExpanded() throws Exception { Map queryMap = new LinkedHashMap<>(); queryMap.put("name", Arrays.asList("Alice", "Bob")); queryMap.put("fooKey", "fooValue"); - queryMap.put("emptyListKey", new ArrayList()); + queryMap.put("emptyListKey", new ArrayList<>()); queryMap.put("emptyStringKey", ""); // empty values are ignored. CompletableFuture cf = api.queryMap(queryMap); @@ -365,7 +364,7 @@ public void queryMapIterableValuesExpanded() throws Exception { } @Test - public void queryMapWithQueryParams() throws Exception { + void queryMapWithQueryParams() throws Exception { TestInterfaceAsync api = new TestInterfaceAsyncBuilder().target("http://localhost:" + server.getPort()); @@ -392,7 +391,7 @@ public void queryMapWithQueryParams() throws Exception { } @Test - public void queryMapValueStartingWithBrace() throws Exception { + void queryMapValueStartingWithBrace() throws Exception { TestInterfaceAsync api = new TestInterfaceAsyncBuilder().target("http://localhost:" + server.getPort()); @@ -422,7 +421,7 @@ public void queryMapValueStartingWithBrace() throws Exception { } @Test - public void queryMapPojoWithFullParams() throws Exception { + void queryMapPojoWithFullParams() throws Exception { TestInterfaceAsync api = new TestInterfaceAsyncBuilder().target("http://localhost:" + server.getPort()); @@ -435,7 +434,7 @@ public void queryMapPojoWithFullParams() throws Exception { } @Test - public void queryMapPojoWithPartialParams() throws Exception { + void queryMapPojoWithPartialParams() throws Exception { TestInterfaceAsync api = new TestInterfaceAsyncBuilder().target("http://localhost:" + server.getPort()); @@ -449,7 +448,7 @@ public void queryMapPojoWithPartialParams() throws Exception { } @Test - public void queryMapPojoWithEmptyParams() throws Exception { + void queryMapPojoWithEmptyParams() throws Exception { TestInterfaceAsync api = new TestInterfaceAsyncBuilder().target("http://localhost:" + server.getPort()); @@ -461,24 +460,23 @@ public void queryMapPojoWithEmptyParams() throws Exception { } @Test - public void configKeyFormatsAsExpected() throws Exception { - assertEquals( - "TestInterfaceAsync#post()", - Feign.configKey( - TestInterfaceAsync.class, TestInterfaceAsync.class.getDeclaredMethod("post"))); - assertEquals( - "TestInterfaceAsync#uriParam(String,URI,String)", - Feign.configKey( - TestInterfaceAsync.class, - TestInterfaceAsync.class.getDeclaredMethod( - "uriParam", String.class, URI.class, String.class))); + void configKeyFormatsAsExpected() throws Exception { + assertThat( + Feign.configKey( + TestInterfaceAsync.class, TestInterfaceAsync.class.getDeclaredMethod("post"))) + .isEqualTo("TestInterfaceAsync#post()"); + assertThat( + Feign.configKey( + TestInterfaceAsync.class, + TestInterfaceAsync.class.getDeclaredMethod( + "uriParam", String.class, URI.class, String.class))) + .isEqualTo("TestInterfaceAsync#uriParam(String,URI,String)"); } @Test - public void configKeyUsesChildType() throws Exception { - assertEquals( - "List#iterator()", - Feign.configKey(List.class, Iterable.class.getDeclaredMethod("iterator"))); + void configKeyUsesChildType() throws Exception { + assertThat(Feign.configKey(List.class, Iterable.class.getDeclaredMethod("iterator"))) + .isEqualTo("List#iterator()"); } private T unwrap(CompletableFuture cf) throws Throwable { @@ -490,21 +488,20 @@ private T unwrap(CompletableFuture cf) throws Throwable { } @Test - public void canOverrideErrorDecoder() throws Throwable { + void canOverrideErrorDecoder() throws Throwable { server.enqueue(new MockResponse().setResponseCode(400).setBody("foo")); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("bad zone name"); TestInterfaceAsync api = new TestInterfaceAsyncBuilder() .errorDecoder(new IllegalArgumentExceptionOn400()) .target("http://localhost:" + server.getPort()); - unwrap(api.post()); + Throwable exception = assertThrows(IllegalArgumentException.class, () -> unwrap(api.post())); + assertThat(exception.getMessage()).contains("bad zone name"); } @Test - public void overrideTypeSpecificDecoder() throws Throwable { + void overrideTypeSpecificDecoder() throws Throwable { server.enqueue(new MockResponse().setBody("success!")); TestInterfaceAsync api = @@ -512,12 +509,12 @@ public void overrideTypeSpecificDecoder() throws Throwable { .decoder((response, type) -> "fail") .target("http://localhost:" + server.getPort()); - assertEquals("fail", unwrap(api.post())); + assertThat(unwrap(api.post())).isEqualTo("fail"); } /** when you must parse a 2xx status to determine if the operation succeeded or not. */ @Test - public void retryableExceptionInDecoder() throws Exception { + void retryableExceptionInDecoder() throws Exception { server.enqueue(new MockResponse().setBody("retry!")); server.enqueue(new MockResponse().setBody("success!")); @@ -546,10 +543,8 @@ public Object decode(Response response, Type type) throws IOException { } @Test - public void doesntRetryAfterResponseIsSent() throws Throwable { + void doesntRetryAfterResponseIsSent() throws Throwable { server.enqueue(new MockResponse().setBody("success!")); - thrown.expect(FeignException.class); - thrown.expectMessage("timeout reading POST http://"); TestInterfaceAsync api = new TestInterfaceAsyncBuilder() @@ -561,11 +556,12 @@ public void doesntRetryAfterResponseIsSent() throws Throwable { CompletableFuture cf = api.post(); server.takeRequest(); - unwrap(cf); + Throwable exception = assertThrows(FeignException.class, () -> unwrap(cf)); + assertThat(exception.getMessage()).contains("timeout reading POST http://"); } @Test - public void throwsFeignExceptionIncludingBody() throws Throwable { + void throwsFeignExceptionIncludingBody() throws Throwable { server.enqueue(new MockResponse().setBody("success!")); TestInterfaceAsync api = @@ -586,11 +582,11 @@ public void throwsFeignExceptionIncludingBody() throws Throwable { assertThat(e.contentUTF8()).isEqualTo("Request body"); return; } - fail(); + fail(""); } @Test - public void throwsFeignExceptionWithoutBody() { + void throwsFeignExceptionWithoutBody() { server.enqueue(new MockResponse().setBody("success!")); TestInterfaceAsync api = @@ -611,7 +607,7 @@ public void throwsFeignExceptionWithoutBody() { } @Test - public void ensureRetryerClonesItself() throws Throwable { + void ensureRetryerClonesItself() throws Throwable { server.enqueue(new MockResponse().setResponseCode(503).setBody("foo 1")); server.enqueue(new MockResponse().setResponseCode(200).setBody("foo 2")); server.enqueue(new MockResponse().setResponseCode(503).setBody("foo 3")); @@ -623,88 +619,74 @@ public void ensureRetryerClonesItself() throws Throwable { AsyncFeign.builder() .retryer(retryer) .errorDecoder( - new ErrorDecoder() { - @Override - public Exception decode(String methodKey, Response response) { - return new RetryableException( + (methodKey, response) -> + new RetryableException( response.status(), "play it again sam!", HttpMethod.POST, NON_RETRYABLE, - response.request()); - } - }) + response.request())) .target(TestInterfaceAsync.class, "http://localhost:" + server.getPort()); unwrap(api.post()); unwrap(api.post()); // if retryer instance was reused, this statement will throw an exception - assertEquals(4, server.getRequestCount()); + assertThat(server.getRequestCount()).isEqualTo(4); } @Test - public void throwsOriginalExceptionAfterFailedRetries() throws Throwable { + void throwsOriginalExceptionAfterFailedRetries() throws Throwable { server.enqueue(new MockResponse().setResponseCode(503).setBody("foo 1")); server.enqueue(new MockResponse().setResponseCode(503).setBody("foo 2")); final String message = "the innerest"; - thrown.expect(TestInterfaceException.class); - thrown.expectMessage(message); TestInterfaceAsync api = AsyncFeign.builder() .exceptionPropagationPolicy(UNWRAP) .retryer(new Retryer.Default(1, 1, 2)) .errorDecoder( - new ErrorDecoder() { - @Override - public Exception decode(String methodKey, Response response) { - return new RetryableException( + (methodKey, response) -> + new RetryableException( response.status(), "play it again sam!", HttpMethod.POST, new TestInterfaceException(message), NON_RETRYABLE, - response.request()); - } - }) + response.request())) .target(TestInterfaceAsync.class, "http://localhost:" + server.getPort()); - unwrap(api.post()); + Throwable exception = assertThrows(TestInterfaceException.class, () -> unwrap(api.post())); + assertThat(exception.getMessage()).contains(message); } @Test - public void throwsRetryableExceptionIfNoUnderlyingCause() throws Throwable { + void throwsRetryableExceptionIfNoUnderlyingCause() throws Throwable { server.enqueue(new MockResponse().setResponseCode(503).setBody("foo 1")); server.enqueue(new MockResponse().setResponseCode(503).setBody("foo 2")); String message = "play it again sam!"; - thrown.expect(RetryableException.class); - thrown.expectMessage(message); TestInterfaceAsync api = AsyncFeign.builder() .exceptionPropagationPolicy(UNWRAP) .retryer(new Retryer.Default(1, 1, 2)) .errorDecoder( - new ErrorDecoder() { - @Override - public Exception decode(String methodKey, Response response) { - return new RetryableException( + (methodKey, response) -> + new RetryableException( response.status(), message, HttpMethod.POST, NON_RETRYABLE, - response.request()); - } - }) + response.request())) .target(TestInterfaceAsync.class, "http://localhost:" + server.getPort()); - unwrap(api.post()); + Throwable exception = assertThrows(RetryableException.class, () -> unwrap(api.post())); + assertThat(exception.getMessage()).contains(message); } @SuppressWarnings("deprecation") @Test - public void whenReturnTypeIsResponseNoErrorHandling() throws Throwable { + void whenReturnTypeIsResponseNoErrorHandling() throws Throwable { Map> headers = new LinkedHashMap<>(); headers.put("Location", Arrays.asList("http://bar.com")); final Response response = @@ -734,9 +716,9 @@ public void whenReturnTypeIsResponseNoErrorHandling() throws Throwable { execs.shutdown(); } - @Ignore("FIXME random test failures when building on ubuntu, need to investigate further") + @Disabled("FIXME random test failures when building on ubuntu, need to investigate further") // @ParameterizedTest - @ValueSource(ints = {1, 5, 10, 100, 1000}) + // @ValueSource(ints = {1, 5, 10, 100, 1000}) public void cancelRetry(final int expectedTryCount) throws Throwable { // Arrange final CompletableFuture maximumTryCompleted = new CompletableFuture<>(); @@ -806,9 +788,8 @@ public Retryer clone() { } @Test - public void okIfDecodeRootCauseHasNoMessage() throws Throwable { + void okIfDecodeRootCauseHasNoMessage() throws Throwable { server.enqueue(new MockResponse().setBody("success!")); - thrown.expect(DecodeException.class); TestInterfaceAsync api = new TestInterfaceAsyncBuilder() @@ -818,15 +799,12 @@ public void okIfDecodeRootCauseHasNoMessage() throws Throwable { }) .target("http://localhost:" + server.getPort()); - unwrap(api.post()); + assertThrows(DecodeException.class, () -> unwrap(api.post())); } @Test - public void decodingExceptionGetWrappedInDismiss404Mode() throws Throwable { + void decodingExceptionGetWrappedInDismiss404Mode() throws Throwable { server.enqueue(new MockResponse().setResponseCode(404)); - thrown.expect(DecodeException.class); - thrown.expectCause(isA(NoSuchElementException.class)); - ; TestInterfaceAsync api = new TestInterfaceAsyncBuilder() @@ -838,29 +816,32 @@ public void decodingExceptionGetWrappedInDismiss404Mode() throws Throwable { }) .target("http://localhost:" + server.getPort()); - unwrap(api.post()); + DecodeException exception = assertThrows(DecodeException.class, () -> unwrap(api.post())); + assertThat(exception).hasCauseInstanceOf(NoSuchElementException.class); } @Test - public void decodingDoesNotSwallow404ErrorsInDismiss404Mode() throws Throwable { - server.enqueue(new MockResponse().setResponseCode(404)); - thrown.expect(IllegalArgumentException.class); - - TestInterfaceAsync api = - new TestInterfaceAsyncBuilder() - .dismiss404() - .errorDecoder(new IllegalArgumentExceptionOn404()) - .target("http://localhost:" + server.getPort()); - - CompletableFuture cf = api.queryMap(Collections.emptyMap()); - server.takeRequest(); - unwrap(cf); + void decodingDoesNotSwallow404ErrorsInDismiss404Mode() throws Throwable { + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy( + () -> { + server.enqueue(new MockResponse().setResponseCode(404)); + + TestInterfaceAsync api = + new TestInterfaceAsyncBuilder() + .dismiss404() + .errorDecoder(new IllegalArgumentExceptionOn404()) + .target("http://localhost:" + server.getPort()); + + CompletableFuture cf = api.queryMap(Collections.emptyMap()); + server.takeRequest(); + unwrap(cf); + }); } @Test - public void okIfEncodeRootCauseHasNoMessage() throws Throwable { + void okIfEncodeRootCauseHasNoMessage() throws Throwable { server.enqueue(new MockResponse().setBody("success!")); - thrown.expect(EncodeException.class); TestInterfaceAsync api = new TestInterfaceAsyncBuilder() @@ -870,11 +851,11 @@ public void okIfEncodeRootCauseHasNoMessage() throws Throwable { }) .target("http://localhost:" + server.getPort()); - unwrap(api.body(Arrays.asList("foo"))); + assertThrows(EncodeException.class, () -> unwrap(api.body(Arrays.asList("foo")))); } @Test - public void equalsHashCodeAndToStringWork() { + void equalsHashCodeAndToStringWork() { Target t1 = new HardCodedTarget<>(TestInterfaceAsync.class, "http://localhost:8080"); Target t2 = @@ -907,7 +888,7 @@ public void equalsHashCodeAndToStringWork() { @SuppressWarnings("resource") @Test - public void decodeLogicSupportsByteArray() throws Throwable { + void decodeLogicSupportsByteArray() throws Throwable { byte[] expectedResponse = {12, 34, 56}; server.enqueue(new MockResponse().setBody(new Buffer().write(expectedResponse))); @@ -919,7 +900,7 @@ public void decodeLogicSupportsByteArray() throws Throwable { } @Test - public void encodeLogicSupportsByteArray() throws Exception { + void encodeLogicSupportsByteArray() throws Exception { byte[] expectedRequest = {12, 34, 56}; server.enqueue(new MockResponse()); @@ -935,7 +916,7 @@ public void encodeLogicSupportsByteArray() throws Exception { } @Test - public void encodedQueryParam() throws Exception { + void encodedQueryParam() throws Exception { server.enqueue(new MockResponse()); TestInterfaceAsync api = @@ -959,7 +940,7 @@ private void checkCFCompletedSoon(CompletableFuture cf) { } @Test - public void responseMapperIsAppliedBeforeDelegate() throws IOException { + void responseMapperIsAppliedBeforeDelegate() throws IOException { ResponseMappingDecoder decoder = new ResponseMappingDecoder(upperCaseResponseMapper(), new StringDecoder()); String output = (String) decoder.decode(responseWithText("response"), String.class); @@ -968,17 +949,13 @@ public void responseMapperIsAppliedBeforeDelegate() throws IOException { } private ResponseMapper upperCaseResponseMapper() { - return new ResponseMapper() { - @SuppressWarnings("deprecation") - @Override - public Response map(Response response, Type type) { - try { - return response.toBuilder() - .body(Util.toString(response.body().asReader()).toUpperCase().getBytes()) - .build(); - } catch (IOException e) { - throw new RuntimeException(e); - } + return (response, type) -> { + try { + return response.toBuilder() + .body(Util.toString(response.body().asReader()).toUpperCase().getBytes()) + .build(); + } catch (IOException e) { + throw new RuntimeException(e); } }; } @@ -994,7 +971,7 @@ private Response responseWithText(String text) { } @Test - public void mapAndDecodeExecutesMapFunction() throws Throwable { + void mapAndDecodeExecutesMapFunction() throws Throwable { server.enqueue(new MockResponse().setBody("response!")); TestInterfaceAsync api = @@ -1002,11 +979,11 @@ public void mapAndDecodeExecutesMapFunction() throws Throwable { .mapAndDecode(upperCaseResponseMapper(), new StringDecoder()) .target(TestInterfaceAsync.class, "http://localhost:" + server.getPort()); - assertEquals("RESPONSE!", unwrap(api.post())); + assertThat(unwrap(api.post())).isEqualTo("RESPONSE!"); } @Test - public void beanQueryMapEncoderWithPrivateGetterIgnored() throws Exception { + void beanQueryMapEncoderWithPrivateGetterIgnored() throws Exception { TestInterfaceAsync api = new TestInterfaceAsyncBuilder() .queryMapEndcoder(new BeanQueryMapEncoder()) @@ -1024,7 +1001,7 @@ public void beanQueryMapEncoderWithPrivateGetterIgnored() throws Exception { } @Test - public void queryMap_with_child_pojo() throws Exception { + void queryMap_with_child_pojo() throws Exception { TestInterfaceAsync api = new TestInterfaceAsyncBuilder() .queryMapEndcoder(new FieldQueryMapEncoder()) @@ -1046,7 +1023,7 @@ public void queryMap_with_child_pojo() throws Exception { } @Test - public void beanQueryMapEncoderWithNullValueIgnored() throws Exception { + void beanQueryMapEncoderWithNullValueIgnored() throws Exception { TestInterfaceAsync api = new TestInterfaceAsyncBuilder() .queryMapEndcoder(new BeanQueryMapEncoder()) @@ -1065,7 +1042,7 @@ public void beanQueryMapEncoderWithNullValueIgnored() throws Exception { } @Test - public void beanQueryMapEncoderWithEmptyParams() throws Exception { + void beanQueryMapEncoderWithEmptyParams() throws Exception { TestInterfaceAsync api = new TestInterfaceAsyncBuilder() .queryMapEndcoder(new BeanQueryMapEncoder()) @@ -1243,16 +1220,11 @@ static final class TestInterfaceAsyncBuilder { AsyncFeign.builder() .decoder(new Decoder.Default()) .encoder( - new Encoder() { - - @SuppressWarnings("deprecation") - @Override - public void encode(Object object, Type bodyType, RequestTemplate template) { - if (object instanceof Map) { - template.body(new Gson().toJson(object)); - } else { - template.body(object.toString()); - } + (object, bodyType, template) -> { + if (object instanceof Map) { + template.body(new Gson().toJson(object)); + } else { + template.body(object.toString()); } }); @@ -1296,33 +1268,48 @@ TestInterfaceAsync target(String url) { */ @Test - public void testNonInterface() { - thrown.expect(IllegalArgumentException.class); - AsyncFeign.builder().target(NonInterface.class, "http://localhost"); + void nonInterface() { + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy( + () -> { + AsyncFeign.builder().target(NonInterface.class, "http://localhost"); + }); } @Test - public void testExtendedCFReturnType() { - thrown.expect(IllegalArgumentException.class); - AsyncFeign.builder().target(ExtendedCFApi.class, "http://localhost"); + void extendedCFReturnType() { + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy( + () -> { + AsyncFeign.builder().target(ExtendedCFApi.class, "http://localhost"); + }); } @Test - public void testLowerWildReturnType() { - thrown.expect(IllegalArgumentException.class); - AsyncFeign.builder().target(LowerWildApi.class, "http://localhost"); + void lowerWildReturnType() { + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy( + () -> { + AsyncFeign.builder().target(LowerWildApi.class, "http://localhost"); + }); } @Test - public void testUpperWildReturnType() { - thrown.expect(IllegalArgumentException.class); - AsyncFeign.builder().target(UpperWildApi.class, "http://localhost"); + void upperWildReturnType() { + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy( + () -> { + AsyncFeign.builder().target(UpperWildApi.class, "http://localhost"); + }); } @Test - public void testrWildReturnType() { - thrown.expect(IllegalArgumentException.class); - AsyncFeign.builder().target(WildApi.class, "http://localhost"); + void rWildReturnType() { + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy( + () -> { + AsyncFeign.builder().target(WildApi.class, "http://localhost"); + }); } static final class ExtendedCF extends CompletableFuture {} @@ -1380,4 +1367,9 @@ public Instant instant() { return Instant.ofEpochMilli(millis); } } + + @AfterEach + void afterEachTest() throws IOException { + server.close(); + } } diff --git a/core/src/test/java/feign/BaseApiTest.java b/core/src/test/java/feign/BaseApiTest.java index d463daab7..8197f1570 100644 --- a/core/src/test/java/feign/BaseApiTest.java +++ b/core/src/test/java/feign/BaseApiTest.java @@ -14,20 +14,19 @@ package feign; import static feign.assertj.MockWebServerAssertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import com.google.gson.reflect.TypeToken; -import feign.codec.Decoder; -import feign.codec.Encoder; -import java.lang.reflect.Type; +import java.io.IOException; import java.util.List; -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.MockWebServer; -import org.junit.Rule; -import org.junit.Test; +import mockwebserver3.MockResponse; +import mockwebserver3.MockWebServer; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; public class BaseApiTest { - @Rule public final MockWebServer server = new MockWebServer(); + public final MockWebServer server = new MockWebServer(); interface BaseApi { @@ -57,19 +56,16 @@ static class Entities { interface MyApi extends BaseApi {} @Test - public void resolvesParameterizedResult() throws InterruptedException { + void resolvesParameterizedResult() throws InterruptedException { server.enqueue(new MockResponse().setBody("foo")); String baseUrl = server.url("/default").toString(); Feign.builder() .decoder( - new Decoder() { - @Override - public Object decode(Response response, Type type) { - assertThat(type).isEqualTo(new TypeToken>() {}.getType()); - return null; - } + (response, type) -> { + assertThat(type).isEqualTo(new TypeToken>() {}.getType()); + return null; }) .target(MyApi.class, baseUrl) .get("foo"); @@ -78,28 +74,26 @@ public Object decode(Response response, Type type) { } @Test - public void resolvesBodyParameter() throws InterruptedException { + void resolvesBodyParameter() throws InterruptedException { server.enqueue(new MockResponse().setBody("foo")); String baseUrl = server.url("/default").toString(); Feign.builder() .encoder( - new Encoder() { - @Override - public void encode(Object object, Type bodyType, RequestTemplate template) { - assertThat(bodyType).isEqualTo(new TypeToken>() {}.getType()); - } - }) + (object, bodyType, template) -> + assertThat(bodyType).isEqualTo(new TypeToken>() {}.getType())) .decoder( - new Decoder() { - @Override - public Object decode(Response response, Type type) { - assertThat(type).isEqualTo(new TypeToken>() {}.getType()); - return null; - } + (response, type) -> { + assertThat(type).isEqualTo(new TypeToken>() {}.getType()); + return null; }) .target(MyApi.class, baseUrl) - .getAll(new Keys()); + .getAll(new Keys<>()); + } + + @AfterEach + void afterEachTest() throws IOException { + server.close(); } } diff --git a/core/src/test/java/feign/BaseBuilderTest.java b/core/src/test/java/feign/BaseBuilderTest.java index 991bd56d8..32cf7100c 100644 --- a/core/src/test/java/feign/BaseBuilderTest.java +++ b/core/src/test/java/feign/BaseBuilderTest.java @@ -14,19 +14,18 @@ package feign; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNotSame; import static org.mockito.Mockito.RETURNS_MOCKS; import java.lang.reflect.Field; import java.util.List; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; -public class BaseBuilderTest { +class BaseBuilderTest { @Test - public void checkEnrichTouchesAllAsyncBuilderFields() + void checkEnrichTouchesAllAsyncBuilderFields() throws IllegalArgumentException, IllegalAccessException { test( AsyncFeign.builder() @@ -52,13 +51,15 @@ private void test(BaseBuilder builder, int expectedFieldsCount) .isNotEmpty(); mockedValue = ((List) mockedValue).get(0); } - assertTrue("Field was not enriched " + field, Mockito.mockingDetails(mockedValue).isMock()); + assertThat(Mockito.mockingDetails(mockedValue).isMock()) + .as("Field was not enriched " + field) + .isTrue(); assertNotSame(builder, enriched); } } @Test - public void checkEnrichTouchesAllBuilderFields() + void checkEnrichTouchesAllBuilderFields() throws IllegalArgumentException, IllegalAccessException { test( Feign.builder() diff --git a/core/src/test/java/feign/CapabilityTest.java b/core/src/test/java/feign/CapabilityTest.java index 10580a1a5..808f9c4d2 100644 --- a/core/src/test/java/feign/CapabilityTest.java +++ b/core/src/test/java/feign/CapabilityTest.java @@ -13,15 +13,14 @@ */ package feign; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import feign.Request.Options; import java.io.IOException; import java.util.Arrays; -import org.hamcrest.CoreMatchers; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class CapabilityTest { +class CapabilityTest { private class AClient implements Client { @@ -53,7 +52,7 @@ public Response execute(Request request, Options options) throws IOException { } @Test - public void enrichClient() { + void enrichClient() { Client enriched = (Client) Capability.enrich( @@ -73,6 +72,6 @@ public Client enrich(Client client) { } })); - assertThat(enriched, CoreMatchers.instanceOf(BClient.class)); + assertThat(enriched).isInstanceOf(BClient.class); } } diff --git a/core/src/test/java/feign/ContractWithRuntimeInjectionTest.java b/core/src/test/java/feign/ContractWithRuntimeInjectionTest.java index 03d197aa1..8b54e5d71 100644 --- a/core/src/test/java/feign/ContractWithRuntimeInjectionTest.java +++ b/core/src/test/java/feign/ContractWithRuntimeInjectionTest.java @@ -15,13 +15,14 @@ import static feign.assertj.MockWebServerAssertions.assertThat; +import java.io.IOException; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.MockWebServer; -import org.junit.Rule; -import org.junit.Test; +import mockwebserver3.MockResponse; +import mockwebserver3.MockWebServer; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.BeanFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; @@ -48,7 +49,7 @@ public String expand(Object value) { } } - @Rule public final MockWebServer server = new MockWebServer(); + public final MockWebServer server = new MockWebServer(); interface TestExpander { @@ -57,7 +58,7 @@ interface TestExpander { } @Test - public void baseCaseExpanderNewInstance() throws InterruptedException { + void baseCaseExpanderNewInstance() throws InterruptedException { server.enqueue(new MockResponse()); String baseUrl = server.url("/default").toString(); @@ -95,7 +96,7 @@ static class ContractWithRuntimeInjection implements Contract { public List parseAndValidateMetadata(Class targetType) { List result = new Contract.Default().parseAndValidateMetadata(targetType); for (MethodMetadata md : result) { - Map indexToExpander = new LinkedHashMap(); + Map indexToExpander = new LinkedHashMap<>(); for (Map.Entry> entry : md.indexToExpanderClass().entrySet()) { indexToExpander.put(entry.getKey(), beanFactory.getBean(entry.getValue())); @@ -107,7 +108,7 @@ public List parseAndValidateMetadata(Class targetType) { } @Test - public void contractWithRuntimeInjection() throws InterruptedException { + void contractWithRuntimeInjection() throws InterruptedException { server.enqueue(new MockResponse()); String baseUrl = server.url("/default").toString(); @@ -120,4 +121,9 @@ public void contractWithRuntimeInjection() throws InterruptedException { assertThat(server.takeRequest()).hasPath("/default/path?query=foo"); } + + @AfterEach + void afterEachTest() throws IOException { + server.close(); + } } diff --git a/core/src/test/java/feign/DefaultContractInheritanceTest.java b/core/src/test/java/feign/DefaultContractInheritanceTest.java index d29505b26..2d3bd685d 100644 --- a/core/src/test/java/feign/DefaultContractInheritanceTest.java +++ b/core/src/test/java/feign/DefaultContractInheritanceTest.java @@ -15,20 +15,18 @@ import static feign.assertj.FeignAssertions.assertThat; import static java.util.Arrays.asList; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.data.MapEntry.entry; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.List; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; /** * Tests interface inheritance defined per {@link Contract.Default} are interpreted into expected * {@link feign .RequestTemplate template} instances. */ -public class DefaultContractInheritanceTest { - - @Rule public final ExpectedException thrown = ExpectedException.none(); +class DefaultContractInheritanceTest { Contract.Default contract = new Contract.Default(); @@ -42,7 +40,7 @@ interface SimpleParameterizedBaseApi { interface SimpleParameterizedApi extends SimpleParameterizedBaseApi {} @Test - public void simpleParameterizedBaseApi() throws Exception { + void simpleParameterizedBaseApi() throws Exception { final List md = contract.parseAndValidateMetadata(SimpleParameterizedApi.class); assertThat(md).hasSize(1); @@ -53,10 +51,13 @@ public void simpleParameterizedBaseApi() throws Exception { } @Test - public void parameterizedApiUnsupported() throws Exception { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Parameterized types unsupported: SimpleParameterizedBaseApi"); - contract.parseAndValidateMetadata(SimpleParameterizedBaseApi.class); + void parameterizedApiUnsupported() throws Exception { + Throwable exception = + assertThrows( + IllegalStateException.class, + () -> contract.parseAndValidateMetadata(SimpleParameterizedBaseApi.class)); + assertThat(exception.getMessage()) + .contains("Parameterized types unsupported: SimpleParameterizedBaseApi"); } interface OverrideParameterizedApi extends SimpleParameterizedBaseApi { @@ -75,17 +76,18 @@ interface SimpleBaseApi { interface OverrideSimpleApi extends SimpleBaseApi { + @Override @RequestLine("GET /api/v2/{zoneId}") String get(@Param("key") String key); } @Test - public void overrideParameterizedApiSupported() { + void overrideParameterizedApiSupported() { contract.parseAndValidateMetadata(OverrideParameterizedApi.class); } @Test - public void overrideSimpleApiSupported() { + void overrideSimpleApiSupported() { contract.parseAndValidateMetadata(OverrideSimpleApi.class); } @@ -141,29 +143,32 @@ interface MultipleInheritanceApi extends ServiceApi { } @Test - public void singleInheritance() { + void singleInheritance() { contract.parseAndValidateMetadata(SingleInheritanceChild.class); } @Test - public void multipleInheritanceDoneWrong() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Only single inheritance supported: MultipleInheritanceDoneWrong"); - contract.parseAndValidateMetadata(MultipleInheritanceDoneWrong.class); + void multipleInheritanceDoneWrong() { + Throwable exception = + assertThrows( + IllegalStateException.class, + () -> contract.parseAndValidateMetadata(MultipleInheritanceDoneWrong.class)); + assertThat(exception.getMessage()) + .contains("Only single inheritance supported: MultipleInheritanceDoneWrong"); } @Test - public void multipleInheritanceDoneCorrectly() { + void multipleInheritanceDoneCorrectly() { contract.parseAndValidateMetadata(MultipleInheritanceDoneCorrectly.class); } @Test - public void multipleInheritanceDoneCorrectly2() { + void multipleInheritanceDoneCorrectly2() { contract.parseAndValidateMetadata(MultipleInheritanceApi.class); } @Test - public void multipleInheritanceSupported() { + void multipleInheritanceSupported() { contract.parseAndValidateMetadata(GrandChild.class); } } diff --git a/core/src/test/java/feign/DefaultContractTest.java b/core/src/test/java/feign/DefaultContractTest.java index ee5c32db9..535441f45 100644 --- a/core/src/test/java/feign/DefaultContractTest.java +++ b/core/src/test/java/feign/DefaultContractTest.java @@ -15,32 +15,38 @@ import static feign.assertj.FeignAssertions.assertThat; import static java.util.Arrays.asList; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.data.MapEntry.entry; +import static org.junit.jupiter.api.Assertions.assertThrows; import com.google.gson.reflect.TypeToken; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; import java.net.URI; import java.time.Clock; import java.time.Instant; import java.time.ZoneId; -import java.util.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.SortedMap; import org.assertj.core.api.Fail; -import org.junit.Rule; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; /** * Tests interfaces defined per {@link Contract.Default} are interpreted into expected {@link feign * .RequestTemplate template} instances. */ -public class DefaultContractTest { - - @Rule public final ExpectedException thrown = ExpectedException.none(); +class DefaultContractTest { Contract.Default contract = new Contract.Default(); @Test - public void httpMethods() throws Exception { + void httpMethods() throws Exception { assertThat(parseAndValidateMetadata(Methods.class, "post").template()).hasMethod("POST"); assertThat(parseAndValidateMetadata(Methods.class, "put").template()).hasMethod("PUT"); @@ -51,7 +57,7 @@ public void httpMethods() throws Exception { } @Test - public void bodyParamIsGeneric() throws Exception { + void bodyParamIsGeneric() throws Exception { final MethodMetadata md = parseAndValidateMetadata(BodyParams.class, "post", List.class); assertThat(md.bodyIndex()).isEqualTo(0); @@ -59,7 +65,7 @@ public void bodyParamIsGeneric() throws Exception { } @Test - public void bodyParamWithPathParam() throws Exception { + void bodyParamWithPathParam() throws Exception { final MethodMetadata md = parseAndValidateMetadata(BodyParams.class, "post", int.class, List.class); @@ -68,21 +74,23 @@ public void bodyParamWithPathParam() throws Exception { } @Test - public void tooManyBodies() throws Exception { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Method has too many Body"); - parseAndValidateMetadata(BodyParams.class, "tooMany", List.class, List.class); + void tooManyBodies() throws Exception { + Throwable exception = + assertThrows( + IllegalStateException.class, + () -> parseAndValidateMetadata(BodyParams.class, "tooMany", List.class, List.class)); + assertThat(exception.getMessage()).contains("Method has too many Body"); } @Test - public void customMethodWithoutPath() throws Exception { + void customMethodWithoutPath() throws Exception { assertThat(parseAndValidateMetadata(CustomMethod.class, "patch").template()) .hasMethod("PATCH") .hasUrl("/"); } @Test - public void queryParamsInPathExtract() throws Exception { + void queryParamsInPathExtract() throws Exception { assertThat(parseAndValidateMetadata(WithQueryParamsInPath.class, "none").template()) .hasUrl("/") .hasQueries(); @@ -119,14 +127,14 @@ public void queryParamsInPathExtract() throws Exception { } @Test - public void bodyWithoutParameters() throws Exception { + void bodyWithoutParameters() throws Exception { final MethodMetadata md = parseAndValidateMetadata(BodyWithoutParameters.class, "post"); assertThat(md.template()).hasBody(""); } @Test - public void headersOnMethodAddsContentTypeHeader() throws Exception { + void headersOnMethodAddsContentTypeHeader() throws Exception { final MethodMetadata md = parseAndValidateMetadata(BodyWithoutParameters.class, "post"); assertThat(md.template()) @@ -136,7 +144,7 @@ public void headersOnMethodAddsContentTypeHeader() throws Exception { } @Test - public void headersOnTypeAddsContentTypeHeader() throws Exception { + void headersOnTypeAddsContentTypeHeader() throws Exception { final MethodMetadata md = parseAndValidateMetadata(HeadersOnType.class, "post"); assertThat(md.template()) @@ -146,7 +154,7 @@ public void headersOnTypeAddsContentTypeHeader() throws Exception { } @Test - public void headersContainsWhitespaces() throws Exception { + void headersContainsWhitespaces() throws Exception { final MethodMetadata md = parseAndValidateMetadata(HeadersContainsWhitespaces.class, "post"); assertThat(md.template()) @@ -156,7 +164,7 @@ public void headersContainsWhitespaces() throws Exception { } @Test - public void withPathAndURIParam() throws Exception { + void withPathAndURIParam() throws Exception { final MethodMetadata md = parseAndValidateMetadata( WithURIParam.class, "uriParam", String.class, URI.class, String.class); @@ -171,7 +179,7 @@ public void withPathAndURIParam() throws Exception { } @Test - public void pathAndQueryParams() throws Exception { + void pathAndQueryParams() throws Exception { final MethodMetadata md = parseAndValidateMetadata( WithPathAndQueryParams.class, @@ -189,7 +197,7 @@ public void pathAndQueryParams() throws Exception { } @Test - public void autoDiscoverParamNames() throws Exception { + void autoDiscoverParamNames() throws Exception { final MethodMetadata md = parseAndValidateMetadata( AutoDiscoverParamNames.class, @@ -207,7 +215,7 @@ public void autoDiscoverParamNames() throws Exception { } @Test - public void bodyWithTemplate() throws Exception { + void bodyWithTemplate() throws Exception { final MethodMetadata md = parseAndValidateMetadata( FormParams.class, "login", String.class, String.class, String.class); @@ -219,7 +227,7 @@ public void bodyWithTemplate() throws Exception { } @Test - public void formParamsParseIntoIndexToName() throws Exception { + void formParamsParseIntoIndexToName() throws Exception { final MethodMetadata md = parseAndValidateMetadata( FormParams.class, "login", String.class, String.class, String.class); @@ -234,27 +242,31 @@ public void formParamsParseIntoIndexToName() throws Exception { } @Test - public void formParamAndBodyParams() throws Exception { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Body parameters cannot be used with form parameters."); - - parseAndValidateMetadata( - FormParams.class, "formParamAndBodyParams", String.class, String.class); - Fail.failBecauseExceptionWasNotThrown(IllegalStateException.class); + void formParamAndBodyParams() throws Exception { + Throwable exception = + assertThrows( + IllegalStateException.class, + () -> + parseAndValidateMetadata( + FormParams.class, "formParamAndBodyParams", String.class, String.class)); + assertThat(exception.getMessage()) + .contains("Body parameters cannot be used with form parameters."); } @Test - public void bodyParamsAndformParam() throws Exception { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Body parameters cannot be used with form parameters."); - - parseAndValidateMetadata( - FormParams.class, "bodyParamsAndformParam", String.class, String.class); - Fail.failBecauseExceptionWasNotThrown(IllegalStateException.class); + void bodyParamsAndformParam() throws Exception { + Throwable exception = + assertThrows( + IllegalStateException.class, + () -> + parseAndValidateMetadata( + FormParams.class, "bodyParamsAndformParam", String.class, String.class)); + assertThat(exception.getMessage()) + .contains("Body parameters cannot be used with form parameters."); } @Test - public void formParamParseIntoFormParams() throws Exception { + void formParamParseIntoFormParams() throws Exception { MethodMetadata md = parseAndValidateMetadata( @@ -271,7 +283,7 @@ public void formParamParseIntoFormParams() throws Exception { /** Body type is only for the body param. */ @Test - public void formParamsDoesNotSetBodyType() throws Exception { + void formParamsDoesNotSetBodyType() throws Exception { final MethodMetadata md = parseAndValidateMetadata( FormParams.class, "login", String.class, String.class, String.class); @@ -280,7 +292,7 @@ public void formParamsDoesNotSetBodyType() throws Exception { } @Test - public void headerParamsParseIntoIndexToName() throws Exception { + void headerParamsParseIntoIndexToName() throws Exception { final MethodMetadata md = parseAndValidateMetadata(HeaderParams.class, "logout", String.class); assertThat(md.template()).hasHeaders(entry("Auth-Token", asList("{authToken}", "Foo"))); @@ -290,7 +302,7 @@ public void headerParamsParseIntoIndexToName() throws Exception { } @Test - public void headerParamsParseIntoIndexToNameNotAtStart() throws Exception { + void headerParamsParseIntoIndexToNameNotAtStart() throws Exception { final MethodMetadata md = parseAndValidateMetadata(HeaderParamsNotAtStart.class, "logout", String.class); @@ -302,14 +314,14 @@ public void headerParamsParseIntoIndexToNameNotAtStart() throws Exception { } @Test - public void customExpander() throws Exception { + void customExpander() throws Exception { final MethodMetadata md = parseAndValidateMetadata(CustomExpander.class, "clock", Clock.class); assertThat(md.indexToExpanderClass()).containsExactly(entry(0, ClockToMillis.class)); } @Test - public void queryMap() throws Exception { + void queryMap() throws Exception { final MethodMetadata md = parseAndValidateMetadata(QueryMapTestInterface.class, "queryMap", Map.class); @@ -317,7 +329,7 @@ public void queryMap() throws Exception { } @Test - public void queryMapMapSubclass() throws Exception { + void queryMapMapSubclass() throws Exception { final MethodMetadata md = parseAndValidateMetadata( QueryMapTestInterface.class, "queryMapMapSubclass", SortedMap.class); @@ -326,7 +338,7 @@ public void queryMapMapSubclass() throws Exception { } @Test - public void onlyOneQueryMapAnnotationPermitted() throws Exception { + void onlyOneQueryMapAnnotationPermitted() throws Exception { try { parseAndValidateMetadata( QueryMapTestInterface.class, "multipleQueryMap", Map.class, Map.class); @@ -337,7 +349,7 @@ public void onlyOneQueryMapAnnotationPermitted() throws Exception { } @Test - public void queryMapKeysMustBeStrings() throws Exception { + void queryMapKeysMustBeStrings() throws Exception { try { parseAndValidateMetadata(QueryMapTestInterface.class, "nonStringKeyQueryMap", Map.class); Fail.failBecauseExceptionWasNotThrown(IllegalStateException.class); @@ -347,7 +359,7 @@ public void queryMapKeysMustBeStrings() throws Exception { } @Test - public void queryMapPojoObject() throws Exception { + void queryMapPojoObject() throws Exception { final MethodMetadata md = parseAndValidateMetadata(QueryMapTestInterface.class, "pojoObject", Object.class); @@ -355,7 +367,7 @@ public void queryMapPojoObject() throws Exception { } @Test - public void slashAreEncodedWhenNeeded() throws Exception { + void slashAreEncodedWhenNeeded() throws Exception { MethodMetadata md = parseAndValidateMetadata(SlashNeedToBeEncoded.class, "getQueues", String.class); @@ -367,7 +379,7 @@ public void slashAreEncodedWhenNeeded() throws Exception { } @Test - public void onlyOneHeaderMapAnnotationPermitted() throws Exception { + void onlyOneHeaderMapAnnotationPermitted() throws Exception { try { parseAndValidateMetadata(HeaderMapInterface.class, "multipleHeaderMap", Map.class, Map.class); Fail.failBecauseExceptionWasNotThrown(IllegalStateException.class); @@ -377,7 +389,7 @@ public void onlyOneHeaderMapAnnotationPermitted() throws Exception { } @Test - public void headerMapSubclass() throws Exception { + void headerMapSubclass() throws Exception { final MethodMetadata md = parseAndValidateMetadata( HeaderMapInterface.class, "headerMapSubClass", SubClassHeaders.class); @@ -385,7 +397,7 @@ public void headerMapSubclass() throws Exception { } @Test - public void headerMapUserObject() throws Exception { + void headerMapUserObject() throws Exception { final MethodMetadata md = parseAndValidateMetadata( HeaderMapInterface.class, "headerMapUserObject", HeaderMapUserObject.class); @@ -645,10 +657,10 @@ interface SubClassHeaders extends Map {} interface ParameterizedApi extends ParameterizedBaseApi {} @Test - public void parameterizedBaseApi() throws Exception { + void parameterizedBaseApi() throws Exception { final List md = contract.parseAndValidateMetadata(ParameterizedApi.class); - final Map byConfigKey = new LinkedHashMap(); + final Map byConfigKey = new LinkedHashMap<>(); for (final MethodMetadata m : md) { byConfigKey.put(m.configKey(), m); } @@ -677,7 +689,7 @@ interface ParameterizedHeaderExpandApi { } @Test - public void parameterizedHeaderExpandApi() throws Exception { + void parameterizedHeaderExpandApi() throws Exception { final List md = contract.parseAndValidateMetadata(ParameterizedHeaderExpandApi.class); @@ -690,12 +702,13 @@ public void parameterizedHeaderExpandApi() throws Exception { .hasHeaders( entry("Authorization", asList("{authHdr}")), entry("Accept", asList("application/json"))); - // Ensure that the authHdr expansion was properly detected and did not create a formParam + // Ensure that the authHdr expansion was properly detected and did not create a + // formParam assertThat(md.get(0).formParams()).isEmpty(); } @Test - public void parameterizedHeaderNotStartingWithCurlyBraceExpandApi() throws Exception { + void parameterizedHeaderNotStartingWithCurlyBraceExpandApi() throws Exception { final List md = contract.parseAndValidateMetadata( ParameterizedHeaderNotStartingWithCurlyBraceExpandApi.class); @@ -709,7 +722,8 @@ public void parameterizedHeaderNotStartingWithCurlyBraceExpandApi() throws Excep .hasHeaders( entry("Authorization", asList("Bearer {authHdr}")), entry("Accept", asList("application/json"))); - // Ensure that the authHdr expansion was properly detected and did not create a formParam + // Ensure that the authHdr expansion was properly detected and did not create a + // formParam assertThat(md.get(0).formParams()).isEmpty(); } @@ -733,11 +747,11 @@ interface ParameterizedHeaderExpandInheritedApi extends ParameterizedHeaderBase } @Test - public void parameterizedHeaderExpandApiBaseClass() throws Exception { + void parameterizedHeaderExpandApiBaseClass() throws Exception { final List mds = contract.parseAndValidateMetadata(ParameterizedHeaderExpandInheritedApi.class); - final Map byConfigKey = new LinkedHashMap(); + final Map byConfigKey = new LinkedHashMap<>(); for (final MethodMetadata m : mds) { byConfigKey.put(m.configKey(), m); } @@ -754,7 +768,8 @@ public void parameterizedHeaderExpandApiBaseClass() throws Exception { .hasHeaders( entry("Authorization", asList("{authHdr}")), entry("Accept", asList("application/json"))); - // Ensure that the authHdr expansion was properly detected and did not create a formParam + // Ensure that the authHdr expansion was properly detected and did not create a + // formParam assertThat(md.formParams()).isEmpty(); md = byConfigKey.get("ParameterizedHeaderExpandInheritedApi#getZone(String,String)"); @@ -776,13 +791,15 @@ interface MissingMethod { /** Let's help folks not lose time when they mistake request line for a URI! */ @Test - public void missingMethod() throws Exception { - thrown.expect(IllegalStateException.class); - thrown.expectMessage( - "RequestLine annotation didn't start with an HTTP verb on method" - + " MissingMethod#updateSharing"); - - contract.parseAndValidateMetadata(MissingMethod.class); + void missingMethod() throws Exception { + Throwable exception = + assertThrows( + IllegalStateException.class, + () -> contract.parseAndValidateMetadata(MissingMethod.class)); + assertThat(exception.getMessage()) + .contains( + "RequestLine annotation didn't start with an HTTP verb on method" + + " MissingMethod#updateSharing"); } interface StaticMethodOnInterface { @@ -795,7 +812,7 @@ static String staticMethod() { } @Test - public void staticMethodsOnInterfaceIgnored() throws Exception { + void staticMethodsOnInterfaceIgnored() throws Exception { final List mds = contract.parseAndValidateMetadata(StaticMethodOnInterface.class); assertThat(mds).hasSize(1); @@ -813,7 +830,7 @@ default String defaultGet(String key) { } @Test - public void defaultMethodsOnInterfaceIgnored() throws Exception { + void defaultMethodsOnInterfaceIgnored() throws Exception { final List mds = contract.parseAndValidateMetadata(DefaultMethodOnInterface.class); assertThat(mds).hasSize(1); @@ -827,7 +844,7 @@ interface SubstringQuery { } @Test - public void paramIsASubstringOfAQuery() throws Exception { + void paramIsASubstringOfAQuery() throws Exception { final List mds = contract.parseAndValidateMetadata(SubstringQuery.class); assertThat(mds.get(0).template().queries()).containsExactly(entry("q", asList("body:{body}"))); @@ -835,22 +852,29 @@ public void paramIsASubstringOfAQuery() throws Exception { } @Test - public void errorMessageOnMixedContracts() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("are not used by contract Default"); - - contract.parseAndValidateMetadata(MixedAnnotations.class); + void errorMessageOnMixedContracts() { + Throwable exception = + assertThrows( + IllegalStateException.class, + () -> contract.parseAndValidateMetadata(MixedAnnotations.class)); + assertThat(exception.getMessage()).contains("are not used by contract Default"); } interface MixedAnnotations { @Headers("Content-Type: application/json") @RequestLine("GET api/v2/clients/{uid}") Response findAllClientsByUid2( - @Category(value = String.class) String uid, + @UselessAnnotation("only used to cause problems") String uid, Integer limit, @SuppressWarnings({"a"}) Integer offset); } + @Retention(RetentionPolicy.RUNTIME) + @Target(ElementType.PARAMETER) + public static @interface UselessAnnotation { + String value() default ""; + } + class TestClock extends Clock { private long millis; diff --git a/core/src/test/java/feign/DefaultQueryMapEncoderTest.java b/core/src/test/java/feign/DefaultQueryMapEncoderTest.java index e03a0f8cb..c803fd736 100644 --- a/core/src/test/java/feign/DefaultQueryMapEncoderTest.java +++ b/core/src/test/java/feign/DefaultQueryMapEncoderTest.java @@ -13,24 +13,19 @@ */ package feign; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import feign.querymap.FieldQueryMapEncoder; import java.util.HashMap; import java.util.Map; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; -public class DefaultQueryMapEncoderTest { - - @Rule public final ExpectedException thrown = ExpectedException.none(); +class DefaultQueryMapEncoderTest { private final QueryMapEncoder encoder = new FieldQueryMapEncoder(); @Test - public void testEncodesObject_visibleFields() { + void encodesObject_visibleFields() { Map expected = new HashMap<>(); expected.put("foo", "fooz"); expected.put("bar", "barz"); @@ -41,32 +36,34 @@ public void testEncodesObject_visibleFields() { object.baz = "bazz"; Map encodedMap = encoder.encode(object); - assertEquals("Unexpected encoded query map", expected, encodedMap); + assertThat(encodedMap).as("Unexpected encoded query map").isEqualTo(expected); } @Test - public void testEncodesObject_visibleFields_emptyObject() { + void encodesObject_visibleFields_emptyObject() { VisibleFieldsObject object = new VisibleFieldsObject(); Map encodedMap = encoder.encode(object); - assertTrue("Non-empty map generated from null fields: " + encodedMap, encodedMap.isEmpty()); + assertThat(encodedMap.isEmpty()) + .as("Non-empty map generated from null fields: " + encodedMap) + .isTrue(); } @Test - public void testEncodesObject_nonVisibleFields() { + void encodesObject_nonVisibleFields() { Map expected = new HashMap<>(); expected.put("foo", "fooz"); expected.put("bar", "barz"); QueryMapEncoderObject object = new QueryMapEncoderObject("fooz", "barz"); Map encodedMap = encoder.encode(object); - assertEquals("Unexpected encoded query map", expected, encodedMap); + assertThat(encodedMap).as("Unexpected encoded query map").isEqualTo(expected); } @Test - public void testEncodesObject_nonVisibleFields_emptyObject() { + void encodesObject_nonVisibleFields_emptyObject() { QueryMapEncoderObject object = new QueryMapEncoderObject(null, null); Map encodedMap = encoder.encode(object); - assertTrue("Non-empty map generated from null fields", encodedMap.isEmpty()); + assertThat(encodedMap.isEmpty()).as("Non-empty map generated from null fields").isTrue(); } static class VisibleFieldsObject { diff --git a/core/src/test/java/feign/EmptyTargetTest.java b/core/src/test/java/feign/EmptyTargetTest.java index 00f02664f..d013476f7 100644 --- a/core/src/test/java/feign/EmptyTargetTest.java +++ b/core/src/test/java/feign/EmptyTargetTest.java @@ -13,45 +13,44 @@ */ package feign; -import static feign.assertj.FeignAssertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThrows; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; import feign.Request.HttpMethod; import feign.Target.EmptyTarget; import java.net.URI; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class EmptyTargetTest { +class EmptyTargetTest { @Test - public void whenNameNotSupplied() { + void whenNameNotSupplied() { assertThat(EmptyTarget.create(UriInterface.class)) .isEqualTo(EmptyTarget.create(UriInterface.class, "empty:UriInterface")); } @Test - public void toString_withoutName() { + void toString_withoutName() { assertThat(EmptyTarget.create(UriInterface.class).toString()) .isEqualTo("EmptyTarget(type=UriInterface)"); } @Test - public void toString_withName() { + void toString_withName() { assertThat(EmptyTarget.create(UriInterface.class, "manager-access").toString()) .isEqualTo("EmptyTarget(type=UriInterface, name=manager-access)"); } @Test - public void mustApplyToAbsoluteUrl() { + void mustApplyToAbsoluteUrl() { UnsupportedOperationException exception = assertThrows( UnsupportedOperationException.class, () -> EmptyTarget.create(UriInterface.class) .apply(new RequestTemplate().method(HttpMethod.GET).uri("/relative"))); - assertEquals( - "Request with non-absolute URL not supported with empty target", exception.getMessage()); + assertThat(exception.getMessage()) + .isEqualTo("Request with non-absolute URL not supported with empty target"); } interface UriInterface { diff --git a/core/src/test/java/feign/EnumForNameTest.java b/core/src/test/java/feign/EnumForNameTest.java index 933156550..810572007 100644 --- a/core/src/test/java/feign/EnumForNameTest.java +++ b/core/src/test/java/feign/EnumForNameTest.java @@ -14,27 +14,21 @@ package feign; import static feign.Util.enumForName; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.assertThat; import feign.Request.ProtocolVersion; import java.util.Arrays; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; public class EnumForNameTest { - @RunWith(Parameterized.class) + @Nested public static class KnownEnumValues { - - @Parameter public Object name; - - @Parameter(1) + public Object name; public ProtocolVersion expectedProtocolVersion; - @Parameters public static Iterable data() { return Arrays.asList( new Object[][] { @@ -47,29 +41,42 @@ public static Iterable data() { }); } - @Test - public void getKnownEnumValue() { - assertEquals( - "known enum value: " + name, - expectedProtocolVersion, - enumForName(ProtocolVersion.class, name)); + @MethodSource("data") + @ParameterizedTest + void getKnownEnumValue(Object name, ProtocolVersion expectedProtocolVersion) { + initKnownEnumValues(name, expectedProtocolVersion); + assertThat(enumForName(ProtocolVersion.class, name)) + .as("known enum value: " + name) + .isEqualTo(expectedProtocolVersion); + } + + public void initKnownEnumValues(Object name, ProtocolVersion expectedProtocolVersion) { + this.name = name; + this.expectedProtocolVersion = expectedProtocolVersion; } } - @RunWith(Parameterized.class) + @Nested public static class UnknownEnumValues { - @Parameter public Object name; + public Object name; - @Parameters public static Iterable data() { return Arrays.asList( new Object[][] {{Request.HttpMethod.GET}, {"SPDY/3"}, {null}, {"HTTP/2"}}); } - @Test - public void getKnownEnumValue() { - assertNull("unknown enum value: " + name, enumForName(ProtocolVersion.class, name)); + @MethodSource("data") + @ParameterizedTest + void getKnownEnumValue(Object name) { + initUnknownEnumValues(name); + assertThat(enumForName(ProtocolVersion.class, name)) + .as("unknown enum value: " + name) + .isNull(); + } + + public void initUnknownEnumValues(Object name) { + this.name = name; } } } diff --git a/core/src/test/java/feign/FeignBuilderTest.java b/core/src/test/java/feign/FeignBuilderTest.java index 7b5dce793..02f54dd51 100644 --- a/core/src/test/java/feign/FeignBuilderTest.java +++ b/core/src/test/java/feign/FeignBuilderTest.java @@ -15,11 +15,8 @@ import static feign.assertj.MockWebServerAssertions.assertThat; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import feign.codec.Decoder; import feign.codec.Encoder; @@ -40,32 +37,32 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Stream; -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.MockWebServer; +import mockwebserver3.MockResponse; +import mockwebserver3.MockWebServer; import org.assertj.core.data.MapEntry; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; public class FeignBuilderTest { - @Rule public final MockWebServer server = new MockWebServer(); + public final MockWebServer server = new MockWebServer(); @Test - public void testDefaults() throws Exception { + void defaults() throws Exception { server.enqueue(new MockResponse().setBody("response data")); String url = "http://localhost:" + server.getPort(); TestInterface api = Feign.builder().target(TestInterface.class, url); Response response = api.codecPost("request data"); - assertEquals("response data", Util.toString(response.body().asReader(Util.UTF_8))); + assertThat(Util.toString(response.body().asReader(Util.UTF_8))).isEqualTo("response data"); assertThat(server.takeRequest()).hasBody("request data"); } /** Shows exception handling isn't required to coerce 404 to null or empty */ @Test - public void testDismiss404() { + void dismiss404() { server.enqueue(new MockResponse().setResponseCode(404)); server.enqueue(new MockResponse().setResponseCode(404)); server.enqueue(new MockResponse().setResponseCode(404)); @@ -92,7 +89,7 @@ public void testDismiss404() { /** Shows exception handling isn't required to coerce 204 to null or empty */ @Test - public void testDecode204() { + void decode204() { server.enqueue(new MockResponse().setResponseCode(204)); server.enqueue(new MockResponse().setResponseCode(204)); server.enqueue(new MockResponse().setResponseCode(204)); @@ -118,7 +115,7 @@ public void testDecode204() { } @Test - public void testNoFollowRedirect() { + void noFollowRedirect() { server.enqueue(new MockResponse().setResponseCode(302).addHeader("Location", "/")); String url = "http://localhost:" + server.getPort(); @@ -148,7 +145,7 @@ public void testNoFollowRedirect() { } @Test - public void testUrlPathConcatUrlTrailingSlash() throws Exception { + void urlPathConcatUrlTrailingSlash() throws Exception { server.enqueue(new MockResponse().setBody("response data")); String url = "http://localhost:" + server.getPort() + "/"; @@ -159,7 +156,7 @@ public void testUrlPathConcatUrlTrailingSlash() throws Exception { } @Test - public void testUrlPathConcatNoPathOnRequestLine() throws Exception { + void urlPathConcatNoPathOnRequestLine() throws Exception { server.enqueue(new MockResponse().setBody("response data")); String url = "http://localhost:" + server.getPort() + "/"; @@ -170,7 +167,7 @@ public void testUrlPathConcatNoPathOnRequestLine() throws Exception { } @Test - public void testHttpNotFoundError() { + void httpNotFoundError() { server.enqueue(new MockResponse().setResponseCode(404)); String url = "http://localhost:" + server.getPort() + "/"; @@ -185,7 +182,7 @@ public void testHttpNotFoundError() { } @Test - public void testUrlPathConcatNoInitialSlashOnPath() throws Exception { + void urlPathConcatNoInitialSlashOnPath() throws Exception { server.enqueue(new MockResponse().setBody("response data")); String url = "http://localhost:" + server.getPort() + "/"; @@ -196,7 +193,7 @@ public void testUrlPathConcatNoInitialSlashOnPath() throws Exception { } @Test - public void testUrlPathConcatNoInitialSlashOnPathNoTrailingSlashOnUrl() throws Exception { + void urlPathConcatNoInitialSlashOnPathNoTrailingSlashOnUrl() throws Exception { server.enqueue(new MockResponse().setBody("response data")); String url = "http://localhost:" + server.getPort(); @@ -207,7 +204,7 @@ public void testUrlPathConcatNoInitialSlashOnPathNoTrailingSlashOnUrl() throws E } @Test - public void testOverrideEncoder() throws Exception { + void overrideEncoder() throws Exception { server.enqueue(new MockResponse().setBody("response data")); String url = "http://localhost:" + server.getPort(); @@ -220,20 +217,20 @@ public void testOverrideEncoder() throws Exception { } @Test - public void testOverrideDecoder() { + void overrideDecoder() { server.enqueue(new MockResponse().setBody("success!")); String url = "http://localhost:" + server.getPort(); Decoder decoder = (response, type) -> "fail"; TestInterface api = Feign.builder().decoder(decoder).target(TestInterface.class, url); - assertEquals("fail", api.decodedPost()); + assertThat(api.decodedPost()).isEqualTo("fail"); - assertEquals(1, server.getRequestCount()); + assertThat(server.getRequestCount()).isEqualTo(1); } @Test - public void testOverrideQueryMapEncoder() throws Exception { + void overrideQueryMapEncoder() throws Exception { server.enqueue(new MockResponse()); String url = "http://localhost:" + server.getPort(); @@ -250,11 +247,11 @@ public void testOverrideQueryMapEncoder() throws Exception { api.queryMapEncoded("ignored"); assertThat(server.takeRequest()).hasQueryParams(Arrays.asList("key1=value1", "key2=value2")); - assertEquals(1, server.getRequestCount()); + assertThat(server.getRequestCount()).isEqualTo(1); } @Test - public void testProvideRequestInterceptors() throws Exception { + void provideRequestInterceptors() throws Exception { server.enqueue(new MockResponse().setBody("response data")); String url = "http://localhost:" + server.getPort(); @@ -264,7 +261,7 @@ public void testProvideRequestInterceptors() throws Exception { TestInterface api = Feign.builder().requestInterceptor(requestInterceptor).target(TestInterface.class, url); Response response = api.codecPost("request data"); - assertEquals(Util.toString(response.body().asReader(Util.UTF_8)), "response data"); + assertThat("response data").isEqualTo(Util.toString(response.body().asReader(Util.UTF_8))); assertThat(server.takeRequest()) .hasHeaders(MapEntry.entry("Content-Type", Collections.singletonList("text/plain"))) @@ -272,7 +269,7 @@ public void testProvideRequestInterceptors() throws Exception { } @Test - public void testProvideInvocationHandlerFactory() throws Exception { + void provideInvocationHandlerFactory() throws Exception { server.enqueue(new MockResponse().setBody("response data")); String url = "http://localhost:" + server.getPort(); @@ -293,14 +290,14 @@ public InvocationHandler create(Target target, Map dispat TestInterface api = Feign.builder().invocationHandlerFactory(factory).target(TestInterface.class, url); Response response = api.codecPost("request data"); - assertEquals("response data", Util.toString(response.body().asReader(Util.UTF_8))); - assertEquals(1, callCount.get()); + assertThat(Util.toString(response.body().asReader(Util.UTF_8))).isEqualTo("response data"); + assertThat(callCount.get()).isEqualTo(1); assertThat(server.takeRequest()).hasBody("request data"); } @Test - public void testSlashIsEncodedInPathParams() throws Exception { + void slashIsEncodedInPathParams() throws Exception { server.enqueue(new MockResponse().setBody("response data")); String url = "http://localhost:" + server.getPort(); @@ -312,7 +309,7 @@ public void testSlashIsEncodedInPathParams() throws Exception { } @Test - public void testBasicDefaultMethod() { + void basicDefaultMethod() { String url = "http://localhost:" + server.getPort(); TestInterface api = Feign.builder().target(TestInterface.class, url); @@ -322,14 +319,14 @@ public void testBasicDefaultMethod() { } @Test - public void testDefaultCallingProxiedMethod() throws Exception { + void defaultCallingProxiedMethod() throws Exception { server.enqueue(new MockResponse().setBody("response data")); String url = "http://localhost:" + server.getPort(); TestInterface api = Feign.builder().target(TestInterface.class, url); Response response = api.defaultMethodPassthrough(); - assertEquals("response data", Util.toString(response.body().asReader(Util.UTF_8))); + assertThat(Util.toString(response.body().asReader(Util.UTF_8))).isEqualTo("response data"); assertThat(server.takeRequest()).hasPath("/"); } @@ -343,13 +340,13 @@ public void testDefaultCallingProxiedMethod() throws Exception { * exception. */ @Test - public void testDoNotCloseAfterDecode() { + void doNotCloseAfterDecode() { server.enqueue(new MockResponse().setBody("success!")); String url = "http://localhost:" + server.getPort(); Decoder decoder = (response, type) -> - new Iterator() { + new Iterator<>() { private boolean called = false; @Override @@ -362,7 +359,7 @@ public Object next() { try { return Util.toString(response.body().asReader(Util.UTF_8)); } catch (IOException e) { - fail(e.getMessage()); + fail("", e.getMessage()); return null; } finally { Util.ensureClosed(response); @@ -375,11 +372,11 @@ public Object next() { Feign.builder().decoder(decoder).doNotCloseAfterDecode().target(TestInterface.class, url); Iterator iterator = api.decodedLazyPost(); - assertTrue(iterator.hasNext()); - assertEquals("success!", iterator.next()); - assertFalse(iterator.hasNext()); + assertThat(iterator.hasNext()).isTrue(); + assertThat(iterator.next()).isEqualTo("success!"); + assertThat(iterator.hasNext()).isFalse(); - assertEquals(1, server.getRequestCount()); + assertThat(server.getRequestCount()).isEqualTo(1); } /** @@ -387,7 +384,7 @@ public Object next() { * the {@link Decoder}, the response should be closed. */ @Test - public void testDoNotCloseAfterDecodeDecoderFailure() { + void doNotCloseAfterDecodeDecoderFailure() { server.enqueue(new MockResponse().setBody("success!")); String url = "http://localhost:" + server.getPort(); @@ -457,7 +454,7 @@ public void close() throws IOException { fail("Expected an exception"); } catch (FeignException expected) { } - assertTrue("Responses must be closed when the decoder fails", closed.get()); + assertThat(closed.get()).as("Responses must be closed when the decoder fails").isTrue(); } interface TestInterface { @@ -502,4 +499,9 @@ default Response defaultMethodPassthrough() { return getNoPath(); } } + + @AfterEach + void afterEachTest() throws IOException { + server.close(); + } } diff --git a/core/src/test/java/feign/FeignExceptionTest.java b/core/src/test/java/feign/FeignExceptionTest.java index 738359855..d5647687c 100644 --- a/core/src/test/java/feign/FeignExceptionTest.java +++ b/core/src/test/java/feign/FeignExceptionTest.java @@ -14,16 +14,22 @@ package feign; import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.io.IOException; import java.nio.charset.StandardCharsets; -import java.util.*; -import org.junit.Test; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import org.junit.jupiter.api.Test; -public class FeignExceptionTest { +class FeignExceptionTest { @Test - public void canCreateWithRequestAndResponse() { + void canCreateWithRequestAndResponse() { Request request = Request.create( Request.HttpMethod.GET, @@ -48,7 +54,7 @@ public void canCreateWithRequestAndResponse() { } @Test - public void canCreateWithRequestOnly() { + void canCreateWithRequestOnly() { Request request = Request.create( Request.HttpMethod.GET, @@ -67,7 +73,7 @@ public void canCreateWithRequestOnly() { } @Test - public void createFeignExceptionWithCorrectCharsetResponse() { + void createFeignExceptionWithCorrectCharsetResponse() { Map> map = new HashMap<>(); map.put("connection", new ArrayList<>(Collections.singletonList("keep-alive"))); map.put("content-length", new ArrayList<>(Collections.singletonList("100"))); @@ -98,7 +104,7 @@ public void createFeignExceptionWithCorrectCharsetResponse() { } @Test - public void createFeignExceptionWithErrorCharsetResponse() { + void createFeignExceptionWithErrorCharsetResponse() { Map> map = new HashMap<>(); map.put("connection", new ArrayList<>(Collections.singletonList("keep-alive"))); map.put("content-length", new ArrayList<>(Collections.singletonList("100"))); @@ -129,7 +135,7 @@ public void createFeignExceptionWithErrorCharsetResponse() { } @Test - public void canGetResponseHeadersFromException() { + void canGetResponseHeadersFromException() { Request request = Request.create( Request.HttpMethod.GET, @@ -165,7 +171,7 @@ public void canGetResponseHeadersFromException() { } @Test - public void lengthOfBodyExceptionTest() { + void lengthOfBodyExceptionTest() { String bigResponse = "I love a storm in early May\n" + "When springtime’s boisterous, firstborn thunder\n" @@ -212,24 +218,31 @@ public void lengthOfBodyExceptionTest() { .isGreaterThanOrEqualTo(bigResponse.length()); } - @Test(expected = NullPointerException.class) - public void nullRequestShouldThrowNPEwThrowable() { - new Derived(404, "message", null, new Throwable()); + @Test + void nullRequestShouldThrowNPEwThrowable() { + assertThrows( + NullPointerException.class, () -> new Derived(404, "message", null, new Throwable())); } - @Test(expected = NullPointerException.class) - public void nullRequestShouldThrowNPEwThrowableAndBytes() { - new Derived(404, "message", null, new Throwable(), new byte[1], Collections.emptyMap()); + @Test + void nullRequestShouldThrowNPEwThrowableAndBytes() { + assertThrows( + NullPointerException.class, + () -> + new Derived( + 404, "message", null, new Throwable(), new byte[1], Collections.emptyMap())); } - @Test(expected = NullPointerException.class) - public void nullRequestShouldThrowNPE() { - new Derived(404, "message", null); + @Test + void nullRequestShouldThrowNPE() { + assertThrows(NullPointerException.class, () -> new Derived(404, "message", null)); } - @Test(expected = NullPointerException.class) - public void nullRequestShouldThrowNPEwBytes() { - new Derived(404, "message", null, new byte[1], Collections.emptyMap()); + @Test + void nullRequestShouldThrowNPEwBytes() { + assertThrows( + NullPointerException.class, + () -> new Derived(404, "message", null, new byte[1], Collections.emptyMap())); } static class Derived extends FeignException { diff --git a/core/src/test/java/feign/FeignTest.java b/core/src/test/java/feign/FeignTest.java index fa8781d53..c9641320c 100755 --- a/core/src/test/java/feign/FeignTest.java +++ b/core/src/test/java/feign/FeignTest.java @@ -17,12 +17,17 @@ import static feign.Util.UTF_8; import static feign.assertj.MockWebServerAssertions.assertThat; import static java.util.Collections.emptyList; -import static junit.framework.TestCase.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; import static org.assertj.core.data.MapEntry.entry; -import static org.hamcrest.CoreMatchers.isA; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; @@ -44,29 +49,34 @@ import java.time.Clock; import java.time.Instant; import java.time.ZoneId; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; import java.util.concurrent.atomic.AtomicReference; -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.MockWebServer; -import okhttp3.mockwebserver.SocketPolicy; +import mockwebserver3.MockResponse; +import mockwebserver3.MockWebServer; +import mockwebserver3.SocketPolicy; import okio.Buffer; import org.assertj.core.data.MapEntry; import org.assertj.core.util.Maps; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentMatchers; @SuppressWarnings("deprecation") public class FeignTest { private static final Long NON_RETRYABLE = null; - @Rule public final ExpectedException thrown = ExpectedException.none(); - @Rule public final MockWebServer server = new MockWebServer(); + public final MockWebServer server = new MockWebServer(); @Test - public void iterableQueryParams() throws Exception { + void iterableQueryParams() throws Exception { server.enqueue(new MockResponse().setBody("foo")); TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort()); @@ -77,7 +87,7 @@ public void iterableQueryParams() throws Exception { } @Test - public void arrayQueryMapParams() throws Exception { + void arrayQueryMapParams() throws Exception { server.enqueue(new MockResponse().setBody("foo")); TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort()); @@ -88,22 +98,22 @@ public void arrayQueryMapParams() throws Exception { } @Test - public void typedResponse() throws Exception { + void typedResponse() throws Exception { server.enqueue(new MockResponse().setBody("foo")); TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort()); TypedResponse response = api.getWithTypedResponse(); - assertEquals(200, response.status()); - assertEquals("foo", response.body()); - assertEquals("HTTP/1.1", response.protocolVersion().toString()); + assertThat(response.status()).isEqualTo(200); + assertThat(response.body()).isEqualTo("foo"); + assertThat(response.protocolVersion().toString()).isEqualTo("HTTP/1.1"); assertNotNull(response.headers()); assertNotNull(response.request()); } @Test - public void postTemplateParamsResolve() throws Exception { + void postTemplateParamsResolve() throws Exception { server.enqueue(new MockResponse().setBody("foo")); TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort()); @@ -117,7 +127,7 @@ public void postTemplateParamsResolve() throws Exception { } @Test - public void postFormParams() throws Exception { + void postFormParams() throws Exception { server.enqueue(new MockResponse().setBody("foo")); TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort()); @@ -130,7 +140,7 @@ public void postFormParams() throws Exception { } @Test - public void postBodyParam() throws Exception { + void postBodyParam() throws Exception { server.enqueue(new MockResponse().setBody("foo")); TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort()); @@ -147,7 +157,7 @@ public void postBodyParam() throws Exception { * type. */ @Test - public void bodyTypeCorrespondsWithParameterType() throws Exception { + void bodyTypeCorrespondsWithParameterType() throws Exception { server.enqueue(new MockResponse().setBody("foo")); final AtomicReference encodedType = new AtomicReference<>(); @@ -170,7 +180,7 @@ public void encode(Object object, Type bodyType, RequestTemplate template) { } @Test - public void postGZIPEncodedBodyParam() throws Exception { + void postGZIPEncodedBodyParam() throws Exception { server.enqueue(new MockResponse().setBody("foo")); TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort()); @@ -183,7 +193,7 @@ public void postGZIPEncodedBodyParam() throws Exception { } @Test - public void postDeflateEncodedBodyParam() throws Exception { + void postDeflateEncodedBodyParam() throws Exception { server.enqueue(new MockResponse().setBody("foo")); TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort()); @@ -196,7 +206,7 @@ public void postDeflateEncodedBodyParam() throws Exception { } @Test - public void singleInterceptor() throws Exception { + void singleInterceptor() throws Exception { server.enqueue(new MockResponse().setBody("foo")); TestInterface api = @@ -211,7 +221,7 @@ public void singleInterceptor() throws Exception { } @Test - public void multipleInterceptor() throws Exception { + void multipleInterceptor() throws Exception { server.enqueue(new MockResponse().setBody("foo")); TestInterface api = @@ -229,7 +239,7 @@ public void multipleInterceptor() throws Exception { } @Test - public void customExpander() throws Exception { + void customExpander() throws Exception { server.enqueue(new MockResponse()); TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort()); @@ -240,7 +250,7 @@ public void customExpander() throws Exception { } @Test - public void customExpanderListParam() throws Exception { + void customExpanderListParam() throws Exception { server.enqueue(new MockResponse()); TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort()); @@ -251,7 +261,7 @@ public void customExpanderListParam() throws Exception { } @Test - public void customExpanderNullParam() throws Exception { + void customExpanderNullParam() throws Exception { server.enqueue(new MockResponse()); TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort()); @@ -262,12 +272,12 @@ public void customExpanderNullParam() throws Exception { } @Test - public void headerMap() throws Exception { + void headerMap() throws Exception { server.enqueue(new MockResponse()); TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort()); - Map headerMap = new LinkedHashMap(); + Map headerMap = new LinkedHashMap<>(); headerMap.put("Content-Type", "myContent"); headerMap.put("Custom-Header", "fooValue"); api.headerMap(headerMap); @@ -279,7 +289,7 @@ public void headerMap() throws Exception { } @Test - public void HeaderMapUserObject() throws Exception { + void HeaderMapUserObject() throws Exception { server.enqueue(new MockResponse()); TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort()); @@ -296,12 +306,12 @@ public void HeaderMapUserObject() throws Exception { } @Test - public void headerMapWithHeaderAnnotations() throws Exception { + void headerMapWithHeaderAnnotations() throws Exception { server.enqueue(new MockResponse()); TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort()); - Map headerMap = new LinkedHashMap(); + Map headerMap = new LinkedHashMap<>(); headerMap.put("Custom-Header", "fooValue"); api.headerMapWithHeaderAnnotations(headerMap); @@ -327,7 +337,7 @@ public void headerMapWithHeaderAnnotations() throws Exception { } @Test - public void queryMap() throws Exception { + void queryMap() throws Exception { server.enqueue(new MockResponse()); TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort()); @@ -341,7 +351,7 @@ public void queryMap() throws Exception { } @Test - public void queryMapWithNull() throws Exception { + void queryMapWithNull() throws Exception { server.enqueue(new MockResponse()); TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort()); @@ -355,7 +365,7 @@ public void queryMapWithNull() throws Exception { } @Test - public void queryMapWithEmpty() throws Exception { + void queryMapWithEmpty() throws Exception { server.enqueue(new MockResponse()); TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort()); @@ -369,7 +379,7 @@ public void queryMapWithEmpty() throws Exception { } @Test - public void queryMapIterableValuesExpanded() throws Exception { + void queryMapIterableValuesExpanded() throws Exception { server.enqueue(new MockResponse()); TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort()); @@ -377,7 +387,7 @@ public void queryMapIterableValuesExpanded() throws Exception { Map queryMap = new LinkedHashMap<>(); queryMap.put("name", Arrays.asList("Alice", "Bob")); queryMap.put("fooKey", "fooValue"); - queryMap.put("emptyListKey", new ArrayList()); + queryMap.put("emptyListKey", new ArrayList<>()); queryMap.put("emptyStringKey", ""); // empty values are ignored. api.queryMap(queryMap); @@ -386,25 +396,25 @@ public void queryMapIterableValuesExpanded() throws Exception { } @Test - public void queryMapWithQueryParams() throws Exception { + void queryMapWithQueryParams() throws Exception { TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort()); server.enqueue(new MockResponse()); - Map queryMap = new LinkedHashMap(); + Map queryMap = new LinkedHashMap<>(); queryMap.put("fooKey", "fooValue"); api.queryMapWithQueryParams("alice", queryMap); // query map should be expanded after built-in parameters assertThat(server.takeRequest()).hasPath("/?name=alice&fooKey=fooValue"); server.enqueue(new MockResponse()); - queryMap = new LinkedHashMap(); + queryMap = new LinkedHashMap<>(); queryMap.put("name", "bob"); api.queryMapWithQueryParams("alice", queryMap); // queries are additive assertThat(server.takeRequest()).hasPath("/?name=alice&name=bob"); server.enqueue(new MockResponse()); - queryMap = new LinkedHashMap(); + queryMap = new LinkedHashMap<>(); queryMap.put("name", null); api.queryMapWithQueryParams("alice", queryMap); // null value for a query map key removes query parameter @@ -412,36 +422,36 @@ public void queryMapWithQueryParams() throws Exception { } @Test - public void queryMapValueStartingWithBrace() throws Exception { + void queryMapValueStartingWithBrace() throws Exception { TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort()); server.enqueue(new MockResponse()); - Map queryMap = new LinkedHashMap(); + Map queryMap = new LinkedHashMap<>(); queryMap.put("name", "{alice"); api.queryMap(queryMap); assertThat(server.takeRequest()).hasPath("/?name=%7Balice"); server.enqueue(new MockResponse()); - queryMap = new LinkedHashMap(); + queryMap = new LinkedHashMap<>(); queryMap.put("{name", "alice"); api.queryMap(queryMap); assertThat(server.takeRequest()).hasPath("/?%7Bname=alice"); server.enqueue(new MockResponse()); - queryMap = new LinkedHashMap(); + queryMap = new LinkedHashMap<>(); queryMap.put("name", "%7Balice"); api.queryMap(queryMap); assertThat(server.takeRequest()).hasPath("/?name=%7Balice"); server.enqueue(new MockResponse()); - queryMap = new LinkedHashMap(); + queryMap = new LinkedHashMap<>(); queryMap.put("%7Bname", "%7Balice"); api.queryMap(queryMap); assertThat(server.takeRequest()).hasPath("/?%7Bname=%7Balice"); } @Test - public void queryMapPojoWithFullParams() throws Exception { + void queryMapPojoWithFullParams() throws Exception { TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort()); CustomPojo customPojo = new CustomPojo("Name", 3); @@ -452,7 +462,7 @@ public void queryMapPojoWithFullParams() throws Exception { } @Test - public void queryMapPojoWithPartialParams() throws Exception { + void queryMapPojoWithPartialParams() throws Exception { TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort()); CustomPojo customPojo = new CustomPojo("Name", null); @@ -463,7 +473,7 @@ public void queryMapPojoWithPartialParams() throws Exception { } @Test - public void queryMapPojoWithEmptyParams() throws Exception { + void queryMapPojoWithEmptyParams() throws Exception { TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort()); CustomPojo customPojo = new CustomPojo(null, null); @@ -474,41 +484,38 @@ public void queryMapPojoWithEmptyParams() throws Exception { } @Test - public void configKeyFormatsAsExpected() throws Exception { - assertEquals( - "TestInterface#post()", - Feign.configKey(TestInterface.class, TestInterface.class.getDeclaredMethod("post"))); - assertEquals( - "TestInterface#uriParam(String,URI,String)", - Feign.configKey( - TestInterface.class, - TestInterface.class.getDeclaredMethod( - "uriParam", String.class, URI.class, String.class))); + void configKeyFormatsAsExpected() throws Exception { + assertThat(Feign.configKey(TestInterface.class, TestInterface.class.getDeclaredMethod("post"))) + .isEqualTo("TestInterface#post()"); + assertThat( + Feign.configKey( + TestInterface.class, + TestInterface.class.getDeclaredMethod( + "uriParam", String.class, URI.class, String.class))) + .isEqualTo("TestInterface#uriParam(String,URI,String)"); } @Test - public void configKeyUsesChildType() throws Exception { - assertEquals( - "List#iterator()", - Feign.configKey(List.class, Iterable.class.getDeclaredMethod("iterator"))); + void configKeyUsesChildType() throws Exception { + assertThat(Feign.configKey(List.class, Iterable.class.getDeclaredMethod("iterator"))) + .isEqualTo("List#iterator()"); } @Test - public void canOverrideErrorDecoder() throws Exception { + void canOverrideErrorDecoder() throws Exception { server.enqueue(new MockResponse().setResponseCode(400).setBody("foo")); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("bad zone name"); TestInterface api = new TestInterfaceBuilder() .errorDecoder(new IllegalArgumentExceptionOn400()) .target("http://localhost:" + server.getPort()); - api.post(); + Throwable exception = assertThrows(IllegalArgumentException.class, () -> api.post()); + assertThat(exception.getMessage()).contains("bad zone name"); } @Test - public void retriesLostConnectionBeforeRead() throws Exception { + void retriesLostConnectionBeforeRead() throws Exception { server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_START)); server.enqueue(new MockResponse().setBody("success!")); @@ -516,30 +523,24 @@ public void retriesLostConnectionBeforeRead() throws Exception { api.post(); - assertEquals(2, server.getRequestCount()); + assertThat(server.getRequestCount()).isEqualTo(2); } @Test - public void overrideTypeSpecificDecoder() throws Exception { + void overrideTypeSpecificDecoder() throws Exception { server.enqueue(new MockResponse().setBody("success!")); TestInterface api = new TestInterfaceBuilder() - .decoder( - new Decoder() { - @Override - public Object decode(Response response, Type type) { - return "fail"; - } - }) + .decoder((response, type) -> "fail") .target("http://localhost:" + server.getPort()); - assertEquals(api.post(), "fail"); + assertThat("fail").isEqualTo(api.post()); } /** when you must parse a 2xx status to determine if the operation succeeded or not. */ @Test - public void retryableExceptionInDecoder() throws Exception { + void retryableExceptionInDecoder() throws Exception { server.enqueue(new MockResponse().setBody("retry!")); server.enqueue(new MockResponse().setBody("success!")); @@ -563,32 +564,28 @@ public Object decode(Response response, Type type) throws IOException { }) .target("http://localhost:" + server.getPort()); - assertEquals(api.post(), "success!"); - assertEquals(2, server.getRequestCount()); + assertThat("success!").isEqualTo(api.post()); + assertThat(server.getRequestCount()).isEqualTo(2); } @Test - public void doesntRetryAfterResponseIsSent() throws Exception { + void doesntRetryAfterResponseIsSent() throws Exception { server.enqueue(new MockResponse().setBody("success!")); - thrown.expect(FeignException.class); - thrown.expectMessage("timeout reading POST http://"); TestInterface api = new TestInterfaceBuilder() .decoder( - new Decoder() { - @Override - public Object decode(Response response, Type type) throws IOException { - throw new IOException("timeout"); - } + (response, type) -> { + throw new IOException("timeout"); }) .target("http://localhost:" + server.getPort()); - api.post(); + Throwable exception = assertThrows(FeignException.class, () -> api.post()); + assertThat(exception.getMessage()).contains("timeout reading POST http://"); } @Test - public void throwsFeignExceptionIncludingBody() { + void throwsFeignExceptionIncludingBody() { server.enqueue(new MockResponse().setBody("success!")); TestInterface api = @@ -609,7 +606,7 @@ public void throwsFeignExceptionIncludingBody() { } @Test - public void throwsFeignExceptionWithoutBody() { + void throwsFeignExceptionWithoutBody() { server.enqueue(new MockResponse().setBody("success!")); TestInterface api = @@ -630,7 +627,7 @@ public void throwsFeignExceptionWithoutBody() { } @Test - public void ensureRetryerClonesItself() throws Exception { + void ensureRetryerClonesItself() throws Exception { server.enqueue(new MockResponse().setResponseCode(503).setBody("foo 1")); server.enqueue(new MockResponse().setResponseCode(200).setBody("foo 2")); server.enqueue(new MockResponse().setResponseCode(503).setBody("foo 3")); @@ -642,87 +639,72 @@ public void ensureRetryerClonesItself() throws Exception { Feign.builder() .retryer(retryer) .errorDecoder( - new ErrorDecoder() { - @Override - public Exception decode(String methodKey, Response response) { - return new RetryableException( + (methodKey, response) -> + new RetryableException( response.status(), "play it again sam!", HttpMethod.POST, NON_RETRYABLE, - response.request()); - } - }) + response.request())) .target(TestInterface.class, "http://localhost:" + server.getPort()); api.post(); api.post(); // if retryer instance was reused, this statement will throw an exception - assertEquals(4, server.getRequestCount()); + assertThat(server.getRequestCount()).isEqualTo(4); } @Test - public void throwsOriginalExceptionAfterFailedRetries() throws Exception { + void throwsOriginalExceptionAfterFailedRetries() throws Exception { server.enqueue(new MockResponse().setResponseCode(503).setBody("foo 1")); server.enqueue(new MockResponse().setResponseCode(503).setBody("foo 2")); final String message = "the innerest"; - thrown.expect(TestInterfaceException.class); - thrown.expectMessage(message); TestInterface api = Feign.builder() .exceptionPropagationPolicy(UNWRAP) .retryer(new Retryer.Default(1, 1, 2)) .errorDecoder( - new ErrorDecoder() { - @Override - public Exception decode(String methodKey, Response response) { - return new RetryableException( + (methodKey, response) -> + new RetryableException( response.status(), "play it again sam!", HttpMethod.POST, new TestInterfaceException(message), NON_RETRYABLE, - response.request()); - } - }) + response.request())) .target(TestInterface.class, "http://localhost:" + server.getPort()); - - api.post(); + TestInterfaceException exception = assertThrows(TestInterfaceException.class, () -> api.post()); + assertThat(exception.getMessage()).contains(message); } @Test - public void throwsRetryableExceptionIfNoUnderlyingCause() throws Exception { + void throwsRetryableExceptionIfNoUnderlyingCause() throws Exception { server.enqueue(new MockResponse().setResponseCode(503).setBody("foo 1")); server.enqueue(new MockResponse().setResponseCode(503).setBody("foo 2")); String message = "play it again sam!"; - thrown.expect(RetryableException.class); - thrown.expectMessage(message); TestInterface api = Feign.builder() .exceptionPropagationPolicy(UNWRAP) .retryer(new Retryer.Default(1, 1, 2)) .errorDecoder( - new ErrorDecoder() { - @Override - public Exception decode(String methodKey, Response response) { - return new RetryableException( + (methodKey, response) -> + new RetryableException( response.status(), message, HttpMethod.POST, NON_RETRYABLE, - response.request()); - } - }) + response.request())) .target(TestInterface.class, "http://localhost:" + server.getPort()); - api.post(); + RetryableException exception = assertThrows(RetryableException.class, () -> api.post()); + assertThat(exception.getMessage()).contains(message); } @Test - public void whenReturnTypeIsResponseNoErrorHandling() { + void whenReturnTypeIsResponseNoErrorHandling() { Map> headers = new LinkedHashMap<>(); headers.put("Location", Collections.singletonList("http://bar.com")); final Response response = @@ -768,86 +750,74 @@ public Retryer clone() { } @Test - public void okIfDecodeRootCauseHasNoMessage() throws Exception { + void okIfDecodeRootCauseHasNoMessage() throws Exception { server.enqueue(new MockResponse().setBody("success!")); - thrown.expect(DecodeException.class); TestInterface api = new TestInterfaceBuilder() .decoder( - new Decoder() { - @Override - public Object decode(Response response, Type type) throws IOException { - throw new RuntimeException(); - } + (response, type) -> { + throw new RuntimeException(); }) .target("http://localhost:" + server.getPort()); - api.post(); + assertThrows(DecodeException.class, () -> api.post()); } @Test - public void decodingExceptionGetWrappedInDismiss404Mode() throws Exception { + void decodingExceptionGetWrappedInDismiss404Mode() throws Exception { server.enqueue(new MockResponse().setResponseCode(404)); - thrown.expect(DecodeException.class); - thrown.expectCause(isA(NoSuchElementException.class)); - ; TestInterface api = new TestInterfaceBuilder() .dismiss404() .decoder( - new Decoder() { - @Override - public Object decode(Response response, Type type) throws IOException { - assertEquals(404, response.status()); - throw new NoSuchElementException(); - } + (response, type) -> { + assertEquals(404, response.status()); + throw new NoSuchElementException(); }) .target("http://localhost:" + server.getPort()); - api.post(); + DecodeException exception = assertThrows(DecodeException.class, () -> api.post()); + assertThat(exception).hasCauseInstanceOf(NoSuchElementException.class); } @Test - public void decodingDoesNotSwallow404ErrorsInDismiss404Mode() throws Exception { - server.enqueue(new MockResponse().setResponseCode(404)); - thrown.expect(IllegalArgumentException.class); + void decodingDoesNotSwallow404ErrorsInDismiss404Mode() throws Exception { + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy( + () -> { + server.enqueue(new MockResponse().setResponseCode(404)); - TestInterface api = - new TestInterfaceBuilder() - .dismiss404() - .errorDecoder(new IllegalArgumentExceptionOn404()) - .target("http://localhost:" + server.getPort()); - api.queryMap(Collections.emptyMap()); + TestInterface api = + new TestInterfaceBuilder() + .dismiss404() + .errorDecoder(new IllegalArgumentExceptionOn404()) + .target("http://localhost:" + server.getPort()); + api.queryMap(Collections.emptyMap()); + }); } @Test - public void okIfEncodeRootCauseHasNoMessage() throws Exception { + void okIfEncodeRootCauseHasNoMessage() throws Exception { server.enqueue(new MockResponse().setBody("success!")); - thrown.expect(EncodeException.class); TestInterface api = new TestInterfaceBuilder() .encoder( - new Encoder() { - @Override - public void encode(Object object, Type bodyType, RequestTemplate template) { - throw new RuntimeException(); - } + (object, bodyType, template) -> { + throw new RuntimeException(); }) .target("http://localhost:" + server.getPort()); - api.body(Arrays.asList("foo")); + assertThrows(EncodeException.class, () -> api.body(Arrays.asList("foo"))); } @Test - public void equalsHashCodeAndToStringWork() { - Target t1 = - new HardCodedTarget(TestInterface.class, "http://localhost:8080"); - Target t2 = - new HardCodedTarget(TestInterface.class, "http://localhost:8888"); + void equalsHashCodeAndToStringWork() { + Target t1 = new HardCodedTarget<>(TestInterface.class, "http://localhost:8080"); + Target t2 = new HardCodedTarget<>(TestInterface.class, "http://localhost:8888"); Target t3 = - new HardCodedTarget(OtherTestInterface.class, "http://localhost:8080"); + new HardCodedTarget<>(OtherTestInterface.class, "http://localhost:8080"); TestInterface i1 = Feign.builder().target(t1); TestInterface i2 = Feign.builder().target(t1); TestInterface i3 = Feign.builder().target(t2); @@ -873,7 +843,7 @@ public void equalsHashCodeAndToStringWork() { } @Test - public void decodeLogicSupportsByteArray() throws Exception { + void decodeLogicSupportsByteArray() throws Exception { byte[] expectedResponse = {12, 34, 56}; server.enqueue(new MockResponse().setBody(new Buffer().write(expectedResponse))); @@ -884,7 +854,7 @@ public void decodeLogicSupportsByteArray() throws Exception { } @Test - public void encodeLogicSupportsByteArray() throws Exception { + void encodeLogicSupportsByteArray() throws Exception { byte[] expectedRequest = {12, 34, 56}; server.enqueue(new MockResponse()); @@ -897,7 +867,7 @@ public void encodeLogicSupportsByteArray() throws Exception { } @Test - public void encodedQueryParam() throws Exception { + void encodedQueryParam() throws Exception { server.enqueue(new MockResponse()); TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort()); @@ -908,7 +878,7 @@ public void encodedQueryParam() throws Exception { } @Test - public void responseMapperIsAppliedBeforeDelegate() throws IOException { + void responseMapperIsAppliedBeforeDelegate() throws IOException { ResponseMappingDecoder decoder = new ResponseMappingDecoder(upperCaseResponseMapper(), new StringDecoder()); String output = (String) decoder.decode(responseWithText("response"), String.class); @@ -917,16 +887,13 @@ public void responseMapperIsAppliedBeforeDelegate() throws IOException { } private ResponseMapper upperCaseResponseMapper() { - return new ResponseMapper() { - @Override - public Response map(Response response, Type type) { - try { - return response.toBuilder() - .body(Util.toString(response.body().asReader(UTF_8)).toUpperCase().getBytes()) - .build(); - } catch (IOException e) { - throw new RuntimeException(e); - } + return (response, type) -> { + try { + return response.toBuilder() + .body(Util.toString(response.body().asReader(UTF_8)).toUpperCase().getBytes()) + .build(); + } catch (IOException e) { + throw new RuntimeException(e); } }; } @@ -941,7 +908,7 @@ private Response responseWithText(String text) { } @Test - public void mapAndDecodeExecutesMapFunction() throws Exception { + void mapAndDecodeExecutesMapFunction() throws Exception { server.enqueue(new MockResponse().setBody("response!")); TestInterface api = @@ -949,11 +916,11 @@ public void mapAndDecodeExecutesMapFunction() throws Exception { .mapAndDecode(upperCaseResponseMapper(), new StringDecoder()) .target(TestInterface.class, "http://localhost:" + server.getPort()); - assertEquals(api.post(), "RESPONSE!"); + assertThat("RESPONSE!").isEqualTo(api.post()); } @Test - public void beanQueryMapEncoderWithPrivateGetterIgnored() throws Exception { + void beanQueryMapEncoderWithPrivateGetterIgnored() throws Exception { TestInterface api = new TestInterfaceBuilder() .queryMapEncoder(new BeanQueryMapEncoder()) @@ -970,7 +937,7 @@ public void beanQueryMapEncoderWithPrivateGetterIgnored() throws Exception { } @Test - public void queryMap_with_child_pojo() throws Exception { + void queryMap_with_child_pojo() throws Exception { TestInterface api = new TestInterfaceBuilder() .queryMapEncoder(new FieldQueryMapEncoder()) @@ -993,7 +960,7 @@ public void queryMap_with_child_pojo() throws Exception { } @Test - public void queryMap_with_child_pojo_altered_by_getter_while_using_overriding_encoder() + void queryMap_with_child_pojo_altered_by_getter_while_using_overriding_encoder() throws Exception { TestInterface api = new TestInterfaceBuilder() @@ -1017,7 +984,7 @@ public void queryMap_with_child_pojo_altered_by_getter_while_using_overriding_en } @Test - public void beanQueryMapEncoderWithNullValueIgnored() throws Exception { + void beanQueryMapEncoderWithNullValueIgnored() throws Exception { TestInterface api = new TestInterfaceBuilder() .queryMapEncoder(new BeanQueryMapEncoder()) @@ -1033,7 +1000,7 @@ public void beanQueryMapEncoderWithNullValueIgnored() throws Exception { } @Test - public void beanQueryMapEncoderWithEmptyParams() throws Exception { + void beanQueryMapEncoderWithEmptyParams() throws Exception { TestInterface api = new TestInterfaceBuilder() .queryMapEncoder(new BeanQueryMapEncoder()) @@ -1047,7 +1014,7 @@ public void beanQueryMapEncoderWithEmptyParams() throws Exception { } @Test - public void matrixParametersAreSupported() throws Exception { + void matrixParametersAreSupported() throws Exception { TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort()); server.enqueue(new MockResponse()); @@ -1061,7 +1028,7 @@ public void matrixParametersAreSupported() throws Exception { } @Test - public void matrixParametersAlsoSupportMaps() throws Exception { + void matrixParametersAlsoSupportMaps() throws Exception { TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort()); server.enqueue(new MockResponse()); @@ -1074,7 +1041,7 @@ public void matrixParametersAlsoSupportMaps() throws Exception { } @Test - public void supportComplexHeaders() throws Exception { + void supportComplexHeaders() throws Exception { TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort()); server.enqueue(new MockResponse()); @@ -1088,7 +1055,7 @@ public void supportComplexHeaders() throws Exception { } @Test - public void decodeVoid() throws Exception { + void decodeVoid() throws Exception { Decoder mockDecoder = mock(Decoder.class); server.enqueue(new MockResponse().setResponseCode(200).setBody("OK")); @@ -1103,7 +1070,7 @@ public void decodeVoid() throws Exception { } @Test - public void redirectionInterceptorString() throws Exception { + void redirectionInterceptorString() throws Exception { String location = "https://redirect.example.com"; server.enqueue(new MockResponse().setResponseCode(302).setHeader("Location", location)); @@ -1112,12 +1079,13 @@ public void redirectionInterceptorString() throws Exception { .responseInterceptor(new RedirectionInterceptor()) .target("http://localhost:" + server.getPort()); - assertEquals( - "RedirectionInterceptor did not extract the location header", location, api.post()); + assertThat(api.post()) + .as("RedirectionInterceptor did not extract the location header") + .isEqualTo(location); } @Test - public void redirectionInterceptorCollection() throws Exception { + void redirectionInterceptorCollection() throws Exception { String location = "https://redirect.example.com"; Collection locations = Collections.singleton("https://redirect.example.com"); @@ -1129,16 +1097,16 @@ public void redirectionInterceptorCollection() throws Exception { .target("http://localhost:" + server.getPort()); Collection response = api.collection(); - assertEquals( - "RedirectionInterceptor did not extract the location header", - locations.size(), - response.size()); - assertTrue( - "RedirectionInterceptor did not extract the location header", response.contains(location)); + assertThat(response.size()) + .as("RedirectionInterceptor did not extract the location header") + .isEqualTo(locations.size()); + assertThat(response.contains(location)) + .as("RedirectionInterceptor did not extract the location header") + .isTrue(); } @Test - public void responseInterceptor400Error() throws Exception { + void responseInterceptor400Error() throws Exception { String body = "BACK OFF!!"; server.enqueue(new MockResponse().setResponseCode(429).setBody(body)); @@ -1146,11 +1114,13 @@ public void responseInterceptor400Error() throws Exception { new TestInterfaceBuilder() .responseInterceptor(new ErrorInterceptor()) .target("http://localhost:" + server.getPort()); - assertEquals("ResponseInterceptor did not extract the response body", body, api.post()); + assertThat(api.post()) + .as("ResponseInterceptor did not extract the response body") + .isEqualTo(body); } @Test - public void responseInterceptor500Error() throws Exception { + void responseInterceptor500Error() throws Exception { String body = "One moment, please."; server.enqueue(new MockResponse().setResponseCode(503).setBody(body)); @@ -1158,11 +1128,13 @@ public void responseInterceptor500Error() throws Exception { new TestInterfaceBuilder() .responseInterceptor(new ErrorInterceptor()) .target("http://localhost:" + server.getPort()); - assertEquals("ResponseInterceptor did not extract the response body", body, api.post()); + assertThat(api.post()) + .as("ResponseInterceptor did not extract the response body") + .isEqualTo(body); } @Test - public void responseInterceptorChain() throws Exception { + void responseInterceptorChain() throws Exception { String location = "https://redirect.example.com"; server.enqueue(new MockResponse().setResponseCode(302).setHeader("Location", location)); @@ -1175,13 +1147,16 @@ public void responseInterceptorChain() throws Exception { .responseInterceptor(new ErrorInterceptor()) .target("http://localhost:" + server.getPort()); - assertEquals( - "RedirectionInterceptor did not extract the location header", location, api.post()); - assertEquals("ResponseInterceptor did not extract the response body", body, api.post()); + assertThat(api.post()) + .as("RedirectionInterceptor did not extract the location header") + .isEqualTo(location); + assertThat(api.post()) + .as("ResponseInterceptor did not extract the response body") + .isEqualTo(body); } @Test - public void responseInterceptorChainList() throws Exception { + void responseInterceptorChainList() throws Exception { String location = "https://redirect.example.com"; server.enqueue(new MockResponse().setResponseCode(302).setHeader("Location", location)); @@ -1193,13 +1168,16 @@ public void responseInterceptorChainList() throws Exception { .responseInterceptors(List.of(new RedirectionInterceptor(), new ErrorInterceptor())) .target("http://localhost:" + server.getPort()); - assertEquals( - "RedirectionInterceptor did not extract the location header", location, api.post()); - assertEquals("ResponseInterceptor did not extract the response body", body, api.post()); + assertThat(api.post()) + .as("RedirectionInterceptor did not extract the location header") + .isEqualTo(location); + assertThat(api.post()) + .as("ResponseInterceptor did not extract the response body") + .isEqualTo(body); } @Test - public void responseInterceptorChainOrder() throws Exception { + void responseInterceptorChainOrder() throws Exception { String location = "https://redirect.example.com"; String redirectBody = "Not the location"; server.enqueue( @@ -1211,27 +1189,29 @@ public void responseInterceptorChainOrder() throws Exception { String body = "One moment, please."; server.enqueue(new MockResponse().setResponseCode(503).setBody(body)); - // ErrorInterceptor WILL extract the body of redirects, so we re-order our interceptors to + // ErrorInterceptor WILL extract the body of redirects, so we re-order our + // interceptors to // verify that chain ordering is maintained TestInterface api = new TestInterfaceBuilder() .responseInterceptors(List.of(new ErrorInterceptor(), new RedirectionInterceptor())) .target("http://localhost:" + server.getPort()); - assertEquals( - "RedirectionInterceptor did not extract the redirect response body", - redirectBody, - api.post()); - assertEquals("ResponseInterceptor did not extract the response body", body, api.post()); + assertThat(api.post()) + .as("RedirectionInterceptor did not extract the redirect response body") + .isEqualTo(redirectBody); + assertThat(api.post()) + .as("ResponseInterceptor did not extract the response body") + .isEqualTo(body); } @Test - public void testCallIgnoredMethod() throws Exception { + void callIgnoredMethod() throws Exception { TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort()); try { api.ignore(); - Assert.fail("No exception thrown"); + fail("No exception thrown"); } catch (Exception e) { assertThat(e.getClass()).isEqualTo(UnsupportedOperationException.class); assertThat(e.getMessage()).isEqualTo("Method \"ignore\" should not be called"); @@ -1444,14 +1424,11 @@ static final class TestInterfaceBuilder { new Feign.Builder() .decoder(new Decoder.Default()) .encoder( - new Encoder() { - @Override - public void encode(Object object, Type bodyType, RequestTemplate template) { - if (object instanceof Map) { - template.body(new Gson().toJson(object)); - } else { - template.body(object.toString()); - } + (object, bodyType, template) -> { + if (object instanceof Map) { + template.body(new Gson().toJson(object)); + } else { + template.body(object.toString()); } }); @@ -1543,4 +1520,9 @@ public Instant instant() { return Instant.ofEpochMilli(millis); } } + + @AfterEach + void afterEachTest() throws IOException { + server.close(); + } } diff --git a/core/src/test/java/feign/FeignUnderAsyncTest.java b/core/src/test/java/feign/FeignUnderAsyncTest.java index 61a7a5897..751acda8e 100644 --- a/core/src/test/java/feign/FeignUnderAsyncTest.java +++ b/core/src/test/java/feign/FeignUnderAsyncTest.java @@ -13,11 +13,13 @@ */ package feign; -import static feign.Util.*; +import static feign.Util.UTF_8; import static feign.assertj.MockWebServerAssertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; import static org.assertj.core.data.MapEntry.entry; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; @@ -50,22 +52,19 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicReference; -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.MockWebServer; -import okhttp3.mockwebserver.SocketPolicy; +import mockwebserver3.MockResponse; +import mockwebserver3.MockWebServer; +import mockwebserver3.SocketPolicy; import okio.Buffer; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; @SuppressWarnings("deprecation") public class FeignUnderAsyncTest { - - @Rule public final ExpectedException thrown = ExpectedException.none(); - @Rule public final MockWebServer server = new MockWebServer(); + public final MockWebServer server = new MockWebServer(); @Test - public void iterableQueryParams() throws Exception { + void iterableQueryParams() throws Exception { server.enqueue(new MockResponse().setBody("foo")); TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort()); @@ -76,7 +75,7 @@ public void iterableQueryParams() throws Exception { } @Test - public void postTemplateParamsResolve() throws Exception { + void postTemplateParamsResolve() throws Exception { server.enqueue(new MockResponse().setBody("foo")); TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort()); @@ -90,7 +89,7 @@ public void postTemplateParamsResolve() throws Exception { } @Test - public void postFormParams() throws Exception { + void postFormParams() throws Exception { server.enqueue(new MockResponse().setBody("foo")); TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort()); @@ -103,7 +102,7 @@ public void postFormParams() throws Exception { } @Test - public void postBodyParam() throws Exception { + void postBodyParam() throws Exception { server.enqueue(new MockResponse().setBody("foo")); TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort()); @@ -120,7 +119,7 @@ public void postBodyParam() throws Exception { * type. */ @Test - public void bodyTypeCorrespondsWithParameterType() throws Exception { + void bodyTypeCorrespondsWithParameterType() throws Exception { server.enqueue(new MockResponse().setBody("foo")); final AtomicReference encodedType = new AtomicReference<>(); @@ -143,7 +142,7 @@ public void encode(Object object, Type bodyType, RequestTemplate template) { } @Test - public void postGZIPEncodedBodyParam() throws Exception { + void postGZIPEncodedBodyParam() throws Exception { server.enqueue(new MockResponse().setBody("foo")); TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort()); @@ -156,7 +155,7 @@ public void postGZIPEncodedBodyParam() throws Exception { } @Test - public void postDeflateEncodedBodyParam() throws Exception { + void postDeflateEncodedBodyParam() throws Exception { server.enqueue(new MockResponse().setBody("foo")); TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort()); @@ -169,7 +168,7 @@ public void postDeflateEncodedBodyParam() throws Exception { } @Test - public void singleInterceptor() throws Exception { + void singleInterceptor() throws Exception { server.enqueue(new MockResponse().setBody("foo")); TestInterface api = @@ -184,7 +183,7 @@ public void singleInterceptor() throws Exception { } @Test - public void multipleInterceptor() throws Exception { + void multipleInterceptor() throws Exception { server.enqueue(new MockResponse().setBody("foo")); TestInterface api = @@ -202,7 +201,7 @@ public void multipleInterceptor() throws Exception { } @Test - public void customExpander() throws Exception { + void customExpander() throws Exception { server.enqueue(new MockResponse()); TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort()); @@ -213,7 +212,7 @@ public void customExpander() throws Exception { } @Test - public void customExpanderListParam() throws Exception { + void customExpanderListParam() throws Exception { server.enqueue(new MockResponse()); TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort()); @@ -224,7 +223,7 @@ public void customExpanderListParam() throws Exception { } @Test - public void customExpanderNullParam() throws Exception { + void customExpanderNullParam() throws Exception { server.enqueue(new MockResponse()); TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort()); @@ -235,12 +234,12 @@ public void customExpanderNullParam() throws Exception { } @Test - public void headerMap() throws Exception { + void headerMap() throws Exception { server.enqueue(new MockResponse()); TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort()); - Map headerMap = new LinkedHashMap(); + Map headerMap = new LinkedHashMap<>(); headerMap.put("Content-Type", "myContent"); headerMap.put("Custom-Header", "fooValue"); api.headerMap(headerMap); @@ -252,12 +251,12 @@ public void headerMap() throws Exception { } @Test - public void headerMapWithHeaderAnnotations() throws Exception { + void headerMapWithHeaderAnnotations() throws Exception { server.enqueue(new MockResponse()); TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort()); - Map headerMap = new LinkedHashMap(); + Map headerMap = new LinkedHashMap<>(); headerMap.put("Custom-Header", "fooValue"); api.headerMapWithHeaderAnnotations(headerMap); @@ -283,7 +282,7 @@ public void headerMapWithHeaderAnnotations() throws Exception { } @Test - public void queryMap() throws Exception { + void queryMap() throws Exception { server.enqueue(new MockResponse()); TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort()); @@ -297,7 +296,7 @@ public void queryMap() throws Exception { } @Test - public void queryMapIterableValuesExpanded() throws Exception { + void queryMapIterableValuesExpanded() throws Exception { server.enqueue(new MockResponse()); TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort()); @@ -305,7 +304,7 @@ public void queryMapIterableValuesExpanded() throws Exception { Map queryMap = new LinkedHashMap<>(); queryMap.put("name", Arrays.asList("Alice", "Bob")); queryMap.put("fooKey", "fooValue"); - queryMap.put("emptyListKey", new ArrayList()); + queryMap.put("emptyListKey", new ArrayList<>()); queryMap.put("emptyStringKey", ""); // empty values are ignored. api.queryMap(queryMap); @@ -314,25 +313,25 @@ public void queryMapIterableValuesExpanded() throws Exception { } @Test - public void queryMapWithQueryParams() throws Exception { + void queryMapWithQueryParams() throws Exception { TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort()); server.enqueue(new MockResponse()); - Map queryMap = new LinkedHashMap(); + Map queryMap = new LinkedHashMap<>(); queryMap.put("fooKey", "fooValue"); api.queryMapWithQueryParams("alice", queryMap); // query map should be expanded after built-in parameters assertThat(server.takeRequest()).hasPath("/?name=alice&fooKey=fooValue"); server.enqueue(new MockResponse()); - queryMap = new LinkedHashMap(); + queryMap = new LinkedHashMap<>(); queryMap.put("name", "bob"); api.queryMapWithQueryParams("alice", queryMap); // queries are additive assertThat(server.takeRequest()).hasPath("/?name=alice&name=bob"); server.enqueue(new MockResponse()); - queryMap = new LinkedHashMap(); + queryMap = new LinkedHashMap<>(); queryMap.put("name", null); api.queryMapWithQueryParams("alice", queryMap); // null value for a query map key removes query parameter @@ -340,36 +339,36 @@ public void queryMapWithQueryParams() throws Exception { } @Test - public void queryMapValueStartingWithBrace() throws Exception { + void queryMapValueStartingWithBrace() throws Exception { TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort()); server.enqueue(new MockResponse()); - Map queryMap = new LinkedHashMap(); + Map queryMap = new LinkedHashMap<>(); queryMap.put("name", "{alice"); api.queryMap(queryMap); assertThat(server.takeRequest()).hasPath("/?name=%7Balice"); server.enqueue(new MockResponse()); - queryMap = new LinkedHashMap(); + queryMap = new LinkedHashMap<>(); queryMap.put("{name", "alice"); api.queryMap(queryMap); assertThat(server.takeRequest()).hasPath("/?%7Bname=alice"); server.enqueue(new MockResponse()); - queryMap = new LinkedHashMap(); + queryMap = new LinkedHashMap<>(); queryMap.put("name", "%7Balice"); api.queryMapEncoded(queryMap); assertThat(server.takeRequest()).hasPath("/?name=%7Balice"); server.enqueue(new MockResponse()); - queryMap = new LinkedHashMap(); + queryMap = new LinkedHashMap<>(); queryMap.put("%7Bname", "%7Balice"); api.queryMapEncoded(queryMap); assertThat(server.takeRequest()).hasPath("/?%7Bname=%7Balice"); } @Test - public void queryMapPojoWithFullParams() throws Exception { + void queryMapPojoWithFullParams() throws Exception { TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort()); CustomPojo customPojo = new CustomPojo("Name", 3); @@ -380,7 +379,7 @@ public void queryMapPojoWithFullParams() throws Exception { } @Test - public void queryMapPojoWithPartialParams() throws Exception { + void queryMapPojoWithPartialParams() throws Exception { TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort()); CustomPojo customPojo = new CustomPojo("Name", null); @@ -391,7 +390,7 @@ public void queryMapPojoWithPartialParams() throws Exception { } @Test - public void queryMapPojoWithEmptyParams() throws Exception { + void queryMapPojoWithEmptyParams() throws Exception { TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort()); CustomPojo customPojo = new CustomPojo(null, null); @@ -402,41 +401,38 @@ public void queryMapPojoWithEmptyParams() throws Exception { } @Test - public void configKeyFormatsAsExpected() throws Exception { - assertEquals( - "TestInterface#post()", - Feign.configKey(TestInterface.class, TestInterface.class.getDeclaredMethod("post"))); - assertEquals( - "TestInterface#uriParam(String,URI,String)", - Feign.configKey( - TestInterface.class, - TestInterface.class.getDeclaredMethod( - "uriParam", String.class, URI.class, String.class))); + void configKeyFormatsAsExpected() throws Exception { + assertThat(Feign.configKey(TestInterface.class, TestInterface.class.getDeclaredMethod("post"))) + .isEqualTo("TestInterface#post()"); + assertThat( + Feign.configKey( + TestInterface.class, + TestInterface.class.getDeclaredMethod( + "uriParam", String.class, URI.class, String.class))) + .isEqualTo("TestInterface#uriParam(String,URI,String)"); } @Test - public void configKeyUsesChildType() throws Exception { - assertEquals( - "List#iterator()", - Feign.configKey(List.class, Iterable.class.getDeclaredMethod("iterator"))); + void configKeyUsesChildType() throws Exception { + assertThat(Feign.configKey(List.class, Iterable.class.getDeclaredMethod("iterator"))) + .isEqualTo("List#iterator()"); } @Test - public void canOverrideErrorDecoder() throws Exception { + void canOverrideErrorDecoder() throws Exception { server.enqueue(new MockResponse().setResponseCode(400).setBody("foo")); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("bad zone name"); TestInterface api = new TestInterfaceBuilder() .errorDecoder(new IllegalArgumentExceptionOn400()) .target("http://localhost:" + server.getPort()); - api.post(); + Throwable exception = assertThrows(IllegalArgumentException.class, () -> api.post()); + assertThat(exception.getMessage()).contains("bad zone name"); } @Test - public void retriesLostConnectionBeforeRead() throws Exception { + void retriesLostConnectionBeforeRead() throws Exception { server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_START)); server.enqueue(new MockResponse().setBody("success!")); @@ -444,49 +440,39 @@ public void retriesLostConnectionBeforeRead() throws Exception { api.post(); - assertEquals(2, server.getRequestCount()); + assertThat(server.getRequestCount()).isEqualTo(2); } @Test - public void overrideTypeSpecificDecoder() throws Exception { + void overrideTypeSpecificDecoder() throws Exception { server.enqueue(new MockResponse().setBody("success!")); TestInterface api = new TestInterfaceBuilder() - .decoder( - new Decoder() { - @Override - public Object decode(Response response, Type type) { - return "fail"; - } - }) + .decoder((response, type) -> "fail") .target("http://localhost:" + server.getPort()); - assertEquals(api.post(), "fail"); + assertThat("fail").isEqualTo(api.post()); } @Test - public void doesntRetryAfterResponseIsSent() throws Exception { + void doesntRetryAfterResponseIsSent() throws Exception { server.enqueue(new MockResponse().setBody("success!")); - thrown.expect(FeignException.class); - thrown.expectMessage("timeout reading POST http://"); TestInterface api = new TestInterfaceBuilder() .decoder( - new Decoder() { - @Override - public Object decode(Response response, Type type) throws IOException { - throw new IOException("timeout"); - } + (response, type) -> { + throw new IOException("timeout"); }) .target("http://localhost:" + server.getPort()); - api.post(); + Throwable exception = assertThrows(FeignException.class, () -> api.post()); + assertThat(exception.getMessage()).contains("timeout reading POST http://"); } @Test - public void throwsFeignExceptionIncludingBody() { + void throwsFeignExceptionIncludingBody() { server.enqueue(new MockResponse().setBody("success!")); TestInterface api = @@ -507,7 +493,7 @@ public void throwsFeignExceptionIncludingBody() { } @Test - public void throwsFeignExceptionWithoutBody() { + void throwsFeignExceptionWithoutBody() { server.enqueue(new MockResponse().setBody("success!")); TestInterface api = @@ -528,7 +514,7 @@ public void throwsFeignExceptionWithoutBody() { } @Test - public void whenReturnTypeIsResponseNoErrorHandling() { + void whenReturnTypeIsResponseNoErrorHandling() { Map> headers = new LinkedHashMap<>(); headers.put("Location", Collections.singletonList("http://bar.com")); final Response response = @@ -577,86 +563,74 @@ public Retryer clone() { } @Test - public void okIfDecodeRootCauseHasNoMessage() throws Exception { + void okIfDecodeRootCauseHasNoMessage() throws Exception { server.enqueue(new MockResponse().setBody("success!")); - thrown.expect(DecodeException.class); TestInterface api = new TestInterfaceBuilder() .decoder( - new Decoder() { - @Override - public Object decode(Response response, Type type) throws IOException { - throw new RuntimeException(); - } + (response, type) -> { + throw new RuntimeException(); }) .target("http://localhost:" + server.getPort()); - api.post(); + assertThrows(DecodeException.class, () -> api.post()); } @Test - public void decodingExceptionGetWrappedInDismiss404Mode() throws Exception { + void decodingExceptionGetWrappedInDismiss404Mode() throws Exception { server.enqueue(new MockResponse().setResponseCode(404)); - thrown.expect(DecodeException.class); - thrown.expectCause(isA(NoSuchElementException.class)); - ; TestInterface api = new TestInterfaceBuilder() .dismiss404() .decoder( - new Decoder() { - @Override - public Object decode(Response response, Type type) throws IOException { - assertEquals(404, response.status()); - throw new NoSuchElementException(); - } + (response, type) -> { + assertEquals(404, response.status()); + throw new NoSuchElementException(); }) .target("http://localhost:" + server.getPort()); - api.post(); + DecodeException exception = assertThrows(DecodeException.class, () -> api.post()); + assertThat(exception).hasCauseInstanceOf(NoSuchElementException.class); } @Test - public void decodingDoesNotSwallow404ErrorsInDismiss404Mode() throws Exception { - server.enqueue(new MockResponse().setResponseCode(404)); - thrown.expect(IllegalArgumentException.class); - - TestInterface api = - new TestInterfaceBuilder() - .dismiss404() - .errorDecoder(new IllegalArgumentExceptionOn404()) - .target("http://localhost:" + server.getPort()); - api.queryMap(Collections.emptyMap()); + void decodingDoesNotSwallow404ErrorsInDismiss404Mode() throws Exception { + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy( + () -> { + server.enqueue(new MockResponse().setResponseCode(404)); + + TestInterface api = + new TestInterfaceBuilder() + .dismiss404() + .errorDecoder(new IllegalArgumentExceptionOn404()) + .target("http://localhost:" + server.getPort()); + api.queryMap(Collections.emptyMap()); + }); } @Test - public void okIfEncodeRootCauseHasNoMessage() throws Exception { + void okIfEncodeRootCauseHasNoMessage() throws Exception { server.enqueue(new MockResponse().setBody("success!")); - thrown.expect(EncodeException.class); TestInterface api = new TestInterfaceBuilder() .encoder( - new Encoder() { - @Override - public void encode(Object object, Type bodyType, RequestTemplate template) { - throw new RuntimeException(); - } + (object, bodyType, template) -> { + throw new RuntimeException(); }) .target("http://localhost:" + server.getPort()); - api.body(Arrays.asList("foo")); + assertThrows(EncodeException.class, () -> api.body(Arrays.asList("foo"))); } @Test - public void equalsHashCodeAndToStringWork() { - Target t1 = - new HardCodedTarget(TestInterface.class, "http://localhost:8080"); - Target t2 = - new HardCodedTarget(TestInterface.class, "http://localhost:8888"); + void equalsHashCodeAndToStringWork() { + Target t1 = new HardCodedTarget<>(TestInterface.class, "http://localhost:8080"); + Target t2 = new HardCodedTarget<>(TestInterface.class, "http://localhost:8888"); Target t3 = - new HardCodedTarget(OtherTestInterface.class, "http://localhost:8080"); + new HardCodedTarget<>(OtherTestInterface.class, "http://localhost:8080"); TestInterface i1 = AsyncFeign.builder().target(t1); TestInterface i2 = AsyncFeign.builder().target(t1); TestInterface i3 = AsyncFeign.builder().target(t2); @@ -682,7 +656,7 @@ public void equalsHashCodeAndToStringWork() { } @Test - public void decodeLogicSupportsByteArray() throws Exception { + void decodeLogicSupportsByteArray() throws Exception { byte[] expectedResponse = {12, 34, 56}; server.enqueue(new MockResponse().setBody(new Buffer().write(expectedResponse))); @@ -694,7 +668,7 @@ public void decodeLogicSupportsByteArray() throws Exception { } @Test - public void encodeLogicSupportsByteArray() throws Exception { + void encodeLogicSupportsByteArray() throws Exception { byte[] expectedRequest = {12, 34, 56}; server.enqueue(new MockResponse()); @@ -708,7 +682,7 @@ public void encodeLogicSupportsByteArray() throws Exception { } @Test - public void encodedQueryParam() throws Exception { + void encodedQueryParam() throws Exception { server.enqueue(new MockResponse()); TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort()); @@ -719,7 +693,7 @@ public void encodedQueryParam() throws Exception { } @Test - public void responseMapperIsAppliedBeforeDelegate() throws IOException { + void responseMapperIsAppliedBeforeDelegate() throws IOException { ResponseMappingDecoder decoder = new ResponseMappingDecoder(upperCaseResponseMapper(), new StringDecoder()); String output = (String) decoder.decode(responseWithText("response"), String.class); @@ -728,16 +702,13 @@ public void responseMapperIsAppliedBeforeDelegate() throws IOException { } private ResponseMapper upperCaseResponseMapper() { - return new ResponseMapper() { - @Override - public Response map(Response response, Type type) { - try { - return response.toBuilder() - .body(Util.toString(response.body().asReader(UTF_8)).toUpperCase().getBytes()) - .build(); - } catch (IOException e) { - throw new RuntimeException(e); - } + return (response, type) -> { + try { + return response.toBuilder() + .body(Util.toString(response.body().asReader(UTF_8)).toUpperCase().getBytes()) + .build(); + } catch (IOException e) { + throw new RuntimeException(e); } }; } @@ -752,7 +723,7 @@ private Response responseWithText(String text) { } @Test - public void mapAndDecodeExecutesMapFunction() throws Exception { + void mapAndDecodeExecutesMapFunction() throws Exception { server.enqueue(new MockResponse().setBody("response!")); TestInterface api = @@ -760,11 +731,11 @@ public void mapAndDecodeExecutesMapFunction() throws Exception { .mapAndDecode(upperCaseResponseMapper(), new StringDecoder()) .target(TestInterface.class, "http://localhost:" + server.getPort()); - assertEquals(api.post(), "RESPONSE!"); + assertThat("RESPONSE!").isEqualTo(api.post()); } @Test - public void beanQueryMapEncoderWithPrivateGetterIgnored() throws Exception { + void beanQueryMapEncoderWithPrivateGetterIgnored() throws Exception { TestInterface api = new TestInterfaceBuilder() .queryMapEndcoder(new BeanQueryMapEncoder()) @@ -781,7 +752,7 @@ public void beanQueryMapEncoderWithPrivateGetterIgnored() throws Exception { } @Test - public void queryMap_with_child_pojo() throws Exception { + void queryMap_with_child_pojo() throws Exception { TestInterface api = new TestInterfaceBuilder() .queryMapEndcoder(new FieldQueryMapEncoder()) @@ -802,7 +773,7 @@ public void queryMap_with_child_pojo() throws Exception { } @Test - public void beanQueryMapEncoderWithNullValueIgnored() throws Exception { + void beanQueryMapEncoderWithNullValueIgnored() throws Exception { TestInterface api = new TestInterfaceBuilder() .queryMapEndcoder(new BeanQueryMapEncoder()) @@ -818,7 +789,7 @@ public void beanQueryMapEncoderWithNullValueIgnored() throws Exception { } @Test - public void beanQueryMapEncoderWithEmptyParams() throws Exception { + void beanQueryMapEncoderWithEmptyParams() throws Exception { TestInterface api = new TestInterfaceBuilder() .queryMapEndcoder(new BeanQueryMapEncoder()) @@ -986,14 +957,11 @@ static final class TestInterfaceBuilder { AsyncFeign.builder() .decoder(new Decoder.Default()) .encoder( - new Encoder() { - @Override - public void encode(Object object, Type bodyType, RequestTemplate template) { - if (object instanceof Map) { - template.body(new Gson().toJson(object)); - } else { - template.body(object.toString()); - } + (object, bodyType, template) -> { + if (object instanceof Map) { + template.body(new Gson().toJson(object)); + } else { + template.body(object.toString()); } }); @@ -1055,4 +1023,9 @@ public Instant instant() { return Instant.ofEpochMilli(millis); } } + + @AfterEach + void afterEachTest() throws IOException { + server.close(); + } } diff --git a/core/src/test/java/feign/LoggerTest.java b/core/src/test/java/feign/LoggerTest.java index 5526115e8..9e2871ddf 100644 --- a/core/src/test/java/feign/LoggerTest.java +++ b/core/src/test/java/feign/LoggerTest.java @@ -15,38 +15,27 @@ import static feign.Util.enumForName; import static java.util.Objects.nonNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import feign.Logger.Level; import feign.Request.ProtocolVersion; import java.io.IOException; import java.net.HttpURLConnection; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; import java.util.concurrent.TimeUnit; -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.MockWebServer; -import org.assertj.core.api.SoftAssertions; -import org.junit.Rule; -import org.junit.Test; -import org.junit.experimental.runners.Enclosed; -import org.junit.rules.ExpectedException; -import org.junit.rules.RuleChain; -import org.junit.rules.TestRule; -import org.junit.runner.Description; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.junit.runners.model.Statement; - -@RunWith(Enclosed.class) -public class LoggerTest { +import mockwebserver3.MockResponse; +import mockwebserver3.MockWebServer; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; - public final ExpectedException thrown = ExpectedException.none(); +public class LoggerTest { public final MockWebServer server = new MockWebServer(); public final RecordingLogger logger = new RecordingLogger(); - /** Ensure expected exception handling is done before logger rule. */ - @Rule public final RuleChain chain = RuleChain.outerRule(server).around(logger).around(thrown); - interface SendsStuff { @RequestLine("POST /") @@ -60,17 +49,16 @@ String login( @Param("password") String password); } - @RunWith(Parameterized.class) + @Nested public static class LogLevelEmitsTest extends LoggerTest { - private final Level logLevel; + private Level logLevel; - public LogLevelEmitsTest(Level logLevel, List expectedMessages) { + public void initLogLevelEmitsTest(Level logLevel, List expectedMessages) { this.logLevel = logLevel; logger.expectMessages(expectedMessages); } - @Parameters public static Iterable data() { return Arrays.asList( new Object[][] { @@ -111,8 +99,10 @@ public static Iterable data() { }); } - @Test - public void levelEmits() { + @MethodSource("data") + @ParameterizedTest + void levelEmits(Level logLevel, List expectedMessages) { + initLogLevelEmitsTest(logLevel, expectedMessages); server.enqueue(new MockResponse().setHeader("Y-Powered-By", "Mock").setBody("foo")); SendsStuff api = @@ -125,17 +115,16 @@ public void levelEmits() { } } - @RunWith(Parameterized.class) + @Nested public static class ReasonPhraseOptional extends LoggerTest { - private final Level logLevel; + private Level logLevel; - public ReasonPhraseOptional(Level logLevel, List expectedMessages) { + public void initReasonPhraseOptional(Level logLevel, List expectedMessages) { this.logLevel = logLevel; logger.expectMessages(expectedMessages); } - @Parameters public static Iterable data() { return Arrays.asList( new Object[][] { @@ -148,8 +137,10 @@ public static Iterable data() { }); } - @Test - public void reasonPhraseOptional() { + @MethodSource("data") + @ParameterizedTest + void reasonPhraseOptional(Level logLevel, List expectedMessages) { + initReasonPhraseOptional(logLevel, expectedMessages); server.enqueue(new MockResponse().setStatus("HTTP/1.1 " + 200)); SendsStuff api = @@ -162,20 +153,19 @@ public void reasonPhraseOptional() { } } - @RunWith(Parameterized.class) + @Nested public static class HttpProtocolVersionTest extends LoggerTest { - private final Level logLevel; - private final String protocolVersionName; + private Level logLevel; + private String protocolVersionName; - public HttpProtocolVersionTest( + public void initHttpProtocolVersionTest( Level logLevel, String protocolVersionName, List expectedMessages) { this.logLevel = logLevel; this.protocolVersionName = protocolVersionName; logger.expectMessages(expectedMessages); } - @Parameters public static Iterable data() { return Arrays.asList( new Object[][] { @@ -210,8 +200,11 @@ public static Iterable data() { }); } - @Test - public void testHttpProtocolVersion() { + @MethodSource("data") + @ParameterizedTest + void httpProtocolVersion( + Level logLevel, String protocolVersionName, List expectedMessages) { + initHttpProtocolVersionTest(logLevel, protocolVersionName, expectedMessages); server.enqueue(new MockResponse().setStatus("HTTP/1.1 " + 200)); SendsStuff api = @@ -225,17 +218,16 @@ public void testHttpProtocolVersion() { } } - @RunWith(Parameterized.class) + @Nested public static class ReadTimeoutEmitsTest extends LoggerTest { - private final Level logLevel; + private Level logLevel; - public ReadTimeoutEmitsTest(Level logLevel, List expectedMessages) { + public void initReadTimeoutEmitsTest(Level logLevel, List expectedMessages) { this.logLevel = logLevel; logger.expectMessages(expectedMessages); } - @Parameters public static Iterable data() { return Arrays.asList( new Object[][] { @@ -275,10 +267,11 @@ public static Iterable data() { }); } - @Test - public void levelEmitsOnReadTimeout() { + @MethodSource("data") + @ParameterizedTest + void levelEmitsOnReadTimeout(Level logLevel, List expectedMessages) { + initReadTimeoutEmitsTest(logLevel, expectedMessages); server.enqueue(new MockResponse().throttleBody(1, 1, TimeUnit.SECONDS).setBody("foo")); - thrown.expect(FeignException.class); SendsStuff api = Feign.builder() @@ -301,21 +294,20 @@ public Retryer clone() { }) .target(SendsStuff.class, "http://localhost:" + server.getPort()); - api.login("netflix", "denominator", "password"); + assertThrows(FeignException.class, () -> api.login("netflix", "denominator", "password")); } } - @RunWith(Parameterized.class) + @Nested public static class UnknownHostEmitsTest extends LoggerTest { - private final Level logLevel; + private Level logLevel; - public UnknownHostEmitsTest(Level logLevel, List expectedMessages) { + public void initUnknownHostEmitsTest(Level logLevel, List expectedMessages) { this.logLevel = logLevel; logger.expectMessages(expectedMessages); } - @Parameters public static Iterable data() { return Arrays.asList( new Object[][] { @@ -355,8 +347,10 @@ public static Iterable data() { }); } - @Test - public void unknownHostEmits() { + @MethodSource("data") + @ParameterizedTest + void unknownHostEmits(Level logLevel, List expectedMessages) { + initUnknownHostEmitsTest(logLevel, expectedMessages); SendsStuff api = Feign.builder() .logger(logger) @@ -375,23 +369,20 @@ public Retryer clone() { }) .target(SendsStuff.class, "http://non-exist.invalid"); - thrown.expect(FeignException.class); - - api.login("netflix", "denominator", "password"); + assertThrows(FeignException.class, () -> api.login("netflix", "denominator", "password")); } } - @RunWith(Parameterized.class) + @Nested public static class FormatCharacterTest extends LoggerTest { - private final Level logLevel; + private Level logLevel; - public FormatCharacterTest(Level logLevel, List expectedMessages) { + public void initFormatCharacterTest(Level logLevel, List expectedMessages) { this.logLevel = logLevel; logger.expectMessages(expectedMessages); } - @Parameters public static Iterable data() { return Arrays.asList( new Object[][] { @@ -431,8 +422,10 @@ public static Iterable data() { }); } - @Test - public void formatCharacterEmits() { + @MethodSource("data") + @ParameterizedTest + void formatCharacterEmits(Level logLevel, List expectedMessages) { + initFormatCharacterTest(logLevel, expectedMessages); SendsStuff api = Feign.builder() .logger(logger) @@ -451,23 +444,20 @@ public Retryer clone() { }) .target(SendsStuff.class, "http://non-exist.invalid"); - thrown.expect(FeignException.class); - - api.login("netflix", "denominator", "password"); + assertThrows(FeignException.class, () -> api.login("netflix", "denominator", "password")); } } - @RunWith(Parameterized.class) + @Nested public static class RetryEmitsTest extends LoggerTest { - private final Level logLevel; + private Level logLevel; - public RetryEmitsTest(Level logLevel, List expectedMessages) { + public void initRetryEmitsTest(Level logLevel, List expectedMessages) { this.logLevel = logLevel; logger.expectMessages(expectedMessages); } - @Parameters public static Iterable data() { return Arrays.asList( new Object[][] { @@ -486,9 +476,11 @@ public static Iterable data() { }); } - @Test - public void retryEmits() { - thrown.expect(FeignException.class); + @MethodSource("data") + @ParameterizedTest + void retryEmits(Level logLevel, List expectedMessages) { + + initRetryEmitsTest(logLevel, expectedMessages); SendsStuff api = Feign.builder() @@ -514,11 +506,11 @@ public Retryer clone() { }) .target(SendsStuff.class, "http://non-exist.invalid"); - api.login("netflix", "denominator", "password"); + assertThrows(FeignException.class, () -> api.login("netflix", "denominator", "password")); } } - private static final class RecordingLogger extends Logger implements TestRule { + private static final class RecordingLogger extends Logger { private static final String PREFIX_X = "x-"; private static final String PREFIX_Y = "y-"; @@ -545,21 +537,21 @@ protected void log(String configKey, String format, Object... args) { messages.add(methodTag(configKey) + String.format(format, args)); } - @Override - public Statement apply(final Statement base, Description description) { - return new Statement() { - @Override - public void evaluate() throws Throwable { - base.evaluate(); - SoftAssertions softly = new SoftAssertions(); - softly.assertThat(messages.size()).isEqualTo(expectedMessages.size()); - for (int i = 0; i < messages.size() && i < expectedMessages.size(); i++) { - softly.assertThat(messages.get(i)).matches(expectedMessages.get(i)); - } - softly.assertAll(); - } - }; - } + // @Override + // public Statement apply(final Statement base, Description description) { + // return new Statement() { + // @Override + // public void evaluate() throws Throwable { + // base.evaluate(); + // SoftAssertions softly = new SoftAssertions(); + // softly.assertThat(messages.size()).isEqualTo(expectedMessages.size()); + // for (int i = 0; i < messages.size() && i < expectedMessages.size(); i++) { + // softly.assertThat(messages.get(i)).matches(expectedMessages.get(i)); + // } + // softly.assertAll(); + // } + // }; + // } } private static final class TestProtocolVersionClient extends Client.Default { diff --git a/core/src/test/java/feign/MethodInfoTest.java b/core/src/test/java/feign/MethodInfoTest.java index 29214f1e2..c14fd469b 100644 --- a/core/src/test/java/feign/MethodInfoTest.java +++ b/core/src/test/java/feign/MethodInfoTest.java @@ -13,33 +13,33 @@ */ package feign; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.assertThat; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.List; import java.util.concurrent.CompletableFuture; -import org.junit.Test; -import org.junit.experimental.runners.Enclosed; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; -@RunWith(Enclosed.class) public class MethodInfoTest { - public static class AsyncClientTest { + @Nested + static class AsyncClientTest { public interface AsyncClient { CompletableFuture log(); } @Test - public void testCompletableFutureOfString() throws Exception { + void completableFutureOfString() throws Exception { MethodInfo mi = new MethodInfo(AsyncClient.class, AsyncClient.class.getMethod("log")); - assertTrue(mi.isAsyncReturnType()); - assertEquals(String.class, mi.underlyingReturnType()); + assertThat(mi.isAsyncReturnType()).isTrue(); + assertThat(mi.underlyingReturnType()).isEqualTo(String.class); } } - public static class GenericAsyncClientTest { + @Nested + static class GenericAsyncClientTest { public interface GenericAsyncClient { T log(); } @@ -47,27 +47,29 @@ public interface GenericAsyncClient { public interface AsyncClient extends GenericAsyncClient> {} @Test - public void testGenericCompletableFutureOfString() throws Exception { + void genericCompletableFutureOfString() throws Exception { MethodInfo mi = new MethodInfo(AsyncClient.class, AsyncClient.class.getMethod("log")); - assertTrue(mi.isAsyncReturnType()); - assertEquals(String.class, mi.underlyingReturnType()); + assertThat(mi.isAsyncReturnType()).isTrue(); + assertThat(mi.underlyingReturnType()).isEqualTo(String.class); } } - public static class SyncClientTest { + @Nested + static class SyncClientTest { public interface SyncClient { String log(); } @Test - public void testString() throws Exception { + void string() throws Exception { MethodInfo mi = new MethodInfo(SyncClient.class, SyncClient.class.getMethod("log")); - assertFalse(mi.isAsyncReturnType()); - assertEquals(String.class, mi.underlyingReturnType()); + assertThat(mi.isAsyncReturnType()).isFalse(); + assertThat(mi.underlyingReturnType()).isEqualTo(String.class); } } - public static class GenericSyncClientTest { + @Nested + static class GenericSyncClientTest { public interface GenericSyncClient { T log(); } @@ -92,10 +94,10 @@ public Type getOwnerType() { } @Test - public void testListOfStrings() throws Exception { + void listOfStrings() throws Exception { MethodInfo mi = new MethodInfo(SyncClient.class, SyncClient.class.getMethod("log")); - assertFalse(mi.isAsyncReturnType()); - assertTrue(Types.equals(new ListOfStrings(), mi.underlyingReturnType())); + assertThat(mi.isAsyncReturnType()).isFalse(); + assertThat(Types.equals(new ListOfStrings(), mi.underlyingReturnType())).isTrue(); } } } diff --git a/core/src/test/java/feign/MethodMetadataPresenceTest.java b/core/src/test/java/feign/MethodMetadataPresenceTest.java index 328ba504e..8e381a5ff 100644 --- a/core/src/test/java/feign/MethodMetadataPresenceTest.java +++ b/core/src/test/java/feign/MethodMetadataPresenceTest.java @@ -14,23 +14,24 @@ package feign; import static feign.assertj.MockWebServerAssertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertNotNull; import feign.FeignBuilderTest.TestInterface; import feign.codec.Decoder; import feign.codec.Encoder; -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.MockWebServer; -import org.junit.Rule; -import org.junit.Test; +import java.io.IOException; +import mockwebserver3.MockResponse; +import mockwebserver3.MockWebServer; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; public class MethodMetadataPresenceTest { - @Rule public final MockWebServer server = new MockWebServer(); + public final MockWebServer server = new MockWebServer(); @Test - public void client() throws Exception { + void client() throws Exception { server.enqueue(new MockResponse().setBody("response data")); final String url = "http://localhost:" + server.getPort(); @@ -46,13 +47,13 @@ public void client() throws Exception { .target(TestInterface.class, url); final Response response = api.codecPost("request data"); - assertEquals("response data", Util.toString(response.body().asReader(Util.UTF_8))); + assertThat(Util.toString(response.body().asReader(Util.UTF_8))).isEqualTo("response data"); assertThat(server.takeRequest()).hasBody("request data"); } @Test - public void encoder() throws Exception { + void encoder() throws Exception { server.enqueue(new MockResponse().setBody("response data")); final String url = "http://localhost:" + server.getPort(); @@ -68,13 +69,13 @@ public void encoder() throws Exception { .target(TestInterface.class, url); final Response response = api.codecPost("request data"); - assertEquals("response data", Util.toString(response.body().asReader(Util.UTF_8))); + assertThat(Util.toString(response.body().asReader(Util.UTF_8))).isEqualTo("response data"); assertThat(server.takeRequest()).hasBody("request data"); } @Test - public void decoder() throws Exception { + void decoder() throws Exception { server.enqueue(new MockResponse().setBody("response data")); final String url = "http://localhost:" + server.getPort(); @@ -91,8 +92,13 @@ public void decoder() throws Exception { .target(TestInterface.class, url); final Response response = api.codecPost("request data"); - assertEquals("response data", Util.toString(response.body().asReader(Util.UTF_8))); + assertThat(Util.toString(response.body().asReader(Util.UTF_8))).isEqualTo("response data"); assertThat(server.takeRequest()).hasBody("request data"); } + + @AfterEach + void afterEachTest() throws IOException { + server.close(); + } } diff --git a/core/src/test/java/feign/MultipleLoggerTest.java b/core/src/test/java/feign/MultipleLoggerTest.java index dbae5069a..234375242 100644 --- a/core/src/test/java/feign/MultipleLoggerTest.java +++ b/core/src/test/java/feign/MultipleLoggerTest.java @@ -13,14 +13,14 @@ */ package feign; +import java.io.File; import java.lang.reflect.Field; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; public class MultipleLoggerTest { - @Rule public TemporaryFolder tmp = new TemporaryFolder(); + @TempDir public File tmp; private static java.util.logging.Logger getInnerLogger(Logger.JavaLogger logger) throws Exception { @@ -31,21 +31,23 @@ private static java.util.logging.Logger getInnerLogger(Logger.JavaLogger logger) @SuppressWarnings("deprecation") @Test - public void testAppendSeveralFilesToOneJavaLogger() throws Exception { + void appendSeveralFilesToOneJavaLogger() throws Exception { Logger.JavaLogger logger = new Logger.JavaLogger() - .appendToFile(tmp.newFile("1.log").getAbsolutePath()) - .appendToFile(tmp.newFile("2.log").getAbsolutePath()); + .appendToFile(File.createTempFile("1.log", null, tmp).getAbsolutePath()) + .appendToFile(File.createTempFile("2.log", null, tmp).getAbsolutePath()); java.util.logging.Logger inner = getInnerLogger(logger); assert (inner.getHandlers().length == 2); } @Test - public void testJavaLoggerInstantiationWithLoggerName() throws Exception { + void javaLoggerInstantiationWithLoggerName() throws Exception { Logger.JavaLogger l1 = - new Logger.JavaLogger("First client").appendToFile(tmp.newFile("1.log").getAbsolutePath()); + new Logger.JavaLogger("First client") + .appendToFile(File.createTempFile("1.log", null, tmp).getAbsolutePath()); Logger.JavaLogger l2 = - new Logger.JavaLogger("Second client").appendToFile(tmp.newFile("2.log").getAbsolutePath()); + new Logger.JavaLogger("Second client") + .appendToFile(File.createTempFile("2.log", null, tmp).getAbsolutePath()); java.util.logging.Logger logger1 = getInnerLogger(l1); assert (logger1.getHandlers().length == 1); java.util.logging.Logger logger2 = getInnerLogger(l2); @@ -53,11 +55,13 @@ public void testJavaLoggerInstantiationWithLoggerName() throws Exception { } @Test - public void testJavaLoggerInstantationWithClazz() throws Exception { + void javaLoggerInstantationWithClazz() throws Exception { Logger.JavaLogger l1 = - new Logger.JavaLogger(String.class).appendToFile(tmp.newFile("1.log").getAbsolutePath()); + new Logger.JavaLogger(String.class) + .appendToFile(File.createTempFile("1.log", null, tmp).getAbsolutePath()); Logger.JavaLogger l2 = - new Logger.JavaLogger(Integer.class).appendToFile(tmp.newFile("2.log").getAbsolutePath()); + new Logger.JavaLogger(Integer.class) + .appendToFile(File.createTempFile("2.log", null, tmp).getAbsolutePath()); java.util.logging.Logger logger1 = getInnerLogger(l1); assert (logger1.getHandlers().length == 1); java.util.logging.Logger logger2 = getInnerLogger(l2); diff --git a/core/src/test/java/feign/OptionsTest.java b/core/src/test/java/feign/OptionsTest.java index ad971038f..e9934b52f 100644 --- a/core/src/test/java/feign/OptionsTest.java +++ b/core/src/test/java/feign/OptionsTest.java @@ -14,23 +14,21 @@ package feign; import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.net.SocketTimeoutException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.MockWebServer; -import org.hamcrest.CoreMatchers; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import mockwebserver3.MockResponse; +import mockwebserver3.MockWebServer; +import org.junit.jupiter.api.Test; /** * @author pengfei.zhao */ @SuppressWarnings("deprecation") -public class OptionsTest { +class OptionsTest { static class ChildOptions extends Request.Options { public ChildOptions(int connectTimeoutMillis, int readTimeoutMillis) { @@ -49,10 +47,8 @@ interface OptionsInterface { String get(); } - @Rule public final ExpectedException thrown = ExpectedException.none(); - @Test - public void socketTimeoutTest() { + void socketTimeoutTest() { final MockWebServer server = new MockWebServer(); server.enqueue(new MockResponse().setBody("foo").setBodyDelay(3, TimeUnit.SECONDS)); @@ -61,14 +57,12 @@ public void socketTimeoutTest() { .options(new Request.Options(1000, 1000)) .target(OptionsInterface.class, server.url("/").toString()); - thrown.expect(FeignException.class); - thrown.expectCause(CoreMatchers.isA(SocketTimeoutException.class)); - - api.get(); + FeignException exception = assertThrows(FeignException.class, () -> api.get()); + assertThat(exception).hasCauseInstanceOf(SocketTimeoutException.class); } @Test - public void normalResponseTest() { + void normalResponseTest() { final MockWebServer server = new MockWebServer(); server.enqueue(new MockResponse().setBody("foo").setBodyDelay(3, TimeUnit.SECONDS)); @@ -81,7 +75,7 @@ public void normalResponseTest() { } @Test - public void normalResponseForChildOptionsTest() { + void normalResponseForChildOptionsTest() { final MockWebServer server = new MockWebServer(); server.enqueue(new MockResponse().setBody("foo").setBodyDelay(3, TimeUnit.SECONDS)); @@ -94,7 +88,7 @@ public void normalResponseForChildOptionsTest() { } @Test - public void socketTimeoutWithMethodOptionsTest() throws Exception { + void socketTimeoutWithMethodOptionsTest() throws Exception { final MockWebServer server = new MockWebServer(); server.enqueue(new MockResponse().setBody("foo").setBodyDelay(2, TimeUnit.SECONDS)); Request.Options options = new Request.Options(1000, 3000); @@ -114,13 +108,14 @@ public void socketTimeoutWithMethodOptionsTest() throws Exception { }); thread.start(); thread.join(); - thrown.expect(FeignException.class); - thrown.expectCause(CoreMatchers.isA(SocketTimeoutException.class)); - throw exceptionAtomicReference.get(); + + Exception exception = exceptionAtomicReference.get(); + assertThat(exception).isInstanceOf(FeignException.class); + assertThat(exception).hasCauseInstanceOf(SocketTimeoutException.class); } @Test - public void normalResponseWithMethodOptionsTest() throws Exception { + void normalResponseWithMethodOptionsTest() throws Exception { final MockWebServer server = new MockWebServer(); server.enqueue(new MockResponse().setBody("foo").setBodyDelay(2, TimeUnit.SECONDS)); Request.Options options = new Request.Options(1000, 1000); diff --git a/core/src/test/java/feign/RequestTemplateTest.java b/core/src/test/java/feign/RequestTemplateTest.java index 7b35c5c47..422281e94 100644 --- a/core/src/test/java/feign/RequestTemplateTest.java +++ b/core/src/test/java/feign/RequestTemplateTest.java @@ -17,9 +17,7 @@ import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.data.MapEntry.entry; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertThrows; import feign.Request.HttpMethod; import feign.template.UriUtils; @@ -28,14 +26,10 @@ import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; public class RequestTemplateTest { - @Rule public final ExpectedException thrown = ExpectedException.none(); - /** Avoid depending on guava solely for map literals. */ private static Map mapOf(K key, V val) { Map result = new LinkedHashMap<>(); @@ -62,7 +56,7 @@ private static String expand(String template, Map variables) { } @Test - public void expandUrlEncoded() { + void expandUrlEncoded() { for (String val : Arrays.asList("apples", "sp ace", "unic???de", "qu?stion")) { assertThat(expand("/users/{user}", mapOf("user", val))) .isEqualTo("/users/" + UriUtils.encode(val, Util.UTF_8)); @@ -70,23 +64,23 @@ public void expandUrlEncoded() { } @Test - public void expandMultipleParams() { + void expandMultipleParams() { assertThat(expand("/users/{user}/{repo}", mapOf("user", "unic???de", "repo", "foo"))) .isEqualTo("/users/unic%3F%3F%3Fde/foo"); } @Test - public void expandParamKeyHyphen() { + void expandParamKeyHyphen() { assertThat(expand("/{user-dir}", mapOf("user-dir", "foo"))).isEqualTo("/foo"); } @Test - public void expandMissingParamProceeds() { + void expandMissingParamProceeds() { assertThat(expand("/{user-dir}", mapOf("user_dir", "foo"))).isEqualTo("/"); } @Test - public void resolveTemplateWithParameterizedPathSkipsEncodingSlash() { + void resolveTemplateWithParameterizedPathSkipsEncodingSlash() { RequestTemplate template = new RequestTemplate().method(HttpMethod.GET).uri("{zoneId}"); template = template.resolve(mapOf("zoneId", "/hostedzone/Z1PA6795UKMFR9")); @@ -95,7 +89,7 @@ public void resolveTemplateWithParameterizedPathSkipsEncodingSlash() { } @Test - public void resolveTemplateWithBinaryBody() { + void resolveTemplateWithBinaryBody() { RequestTemplate template = new RequestTemplate() .method(HttpMethod.GET) @@ -107,7 +101,7 @@ public void resolveTemplateWithBinaryBody() { } @Test - public void canInsertAbsoluteHref() { + void canInsertAbsoluteHref() { RequestTemplate template = new RequestTemplate().method(HttpMethod.GET).uri("/hostedzone/Z1PA6795UKMFR9"); @@ -118,7 +112,7 @@ public void canInsertAbsoluteHref() { } @Test - public void resolveTemplateWithRelativeUriWithQuery() { + void resolveTemplateWithRelativeUriWithQuery() { RequestTemplate template = new RequestTemplate() .method(HttpMethod.GET) @@ -129,7 +123,7 @@ public void resolveTemplateWithRelativeUriWithQuery() { } @Test - public void resolveTemplateWithBaseAndParameterizedQuery() { + void resolveTemplateWithBaseAndParameterizedQuery() { RequestTemplate template = new RequestTemplate() .method(HttpMethod.GET) @@ -145,7 +139,7 @@ public void resolveTemplateWithBaseAndParameterizedQuery() { } @Test - public void resolveTemplateWithBaseAndParameterizedIterableQuery() { + void resolveTemplateWithBaseAndParameterizedIterableQuery() { RequestTemplate template = new RequestTemplate() .method(HttpMethod.GET) @@ -161,13 +155,15 @@ public void resolveTemplateWithBaseAndParameterizedIterableQuery() { } @Test - public void resolveTemplateWithMixedCollectionFormatsByQuery() { + void resolveTemplateWithMixedCollectionFormatsByQuery() { RequestTemplate template = new RequestTemplate() .method(HttpMethod.GET) .collectionFormat(CollectionFormat.EXPLODED) .uri("/api/collections") - .query("keys", "{keys}") // default collection format + .query("keys", "{keys}") // default + // collection + // format .query("values[]", Collections.singletonList("{values[]}"), CollectionFormat.CSV); template = @@ -179,7 +175,7 @@ public void resolveTemplateWithMixedCollectionFormatsByQuery() { } @Test - public void resolveTemplateWithHeaderSubstitutions() { + void resolveTemplateWithHeaderSubstitutions() { RequestTemplate template = new RequestTemplate().method(HttpMethod.GET).header("Auth-Token", "{authToken}"); @@ -189,7 +185,7 @@ public void resolveTemplateWithHeaderSubstitutions() { } @Test - public void resolveTemplateWithHeaderSubstitutionsNotAtStart() { + void resolveTemplateWithHeaderSubstitutionsNotAtStart() { RequestTemplate template = new RequestTemplate().method(HttpMethod.GET).header("Authorization", "Bearer {token}"); @@ -200,7 +196,7 @@ public void resolveTemplateWithHeaderSubstitutionsNotAtStart() { } @Test - public void resolveTemplateWithHeaderWithEscapedCurlyBrace() { + void resolveTemplateWithHeaderWithEscapedCurlyBrace() { RequestTemplate template = new RequestTemplate().method(HttpMethod.GET).header("Encoded", "{{{{dont_expand_me}}"); @@ -211,7 +207,7 @@ public void resolveTemplateWithHeaderWithEscapedCurlyBrace() { } @Test - public void resolveTemplateWithHeaderContainingJsonLiteral() { + void resolveTemplateWithHeaderContainingJsonLiteral() { String json = "{\"A\":{\"B\":\"C\"}}"; RequestTemplate template = new RequestTemplate().method(HttpMethod.GET).header("A-Header", json); @@ -221,7 +217,7 @@ public void resolveTemplateWithHeaderContainingJsonLiteral() { } @Test - public void resolveTemplateWithHeaderWithJson() { + void resolveTemplateWithHeaderWithJson() { String json = "{ \"string\": \"val\", \"string2\": \"this should not be truncated\"}"; RequestTemplate template = new RequestTemplate().method(HttpMethod.GET).header("A-Header", "{aHeader}"); @@ -232,7 +228,7 @@ public void resolveTemplateWithHeaderWithJson() { } @Test - public void resolveTemplateWithHeaderWithNestedJson() { + void resolveTemplateWithHeaderWithNestedJson() { String json = "{ \"string\": \"val\", \"string2\": \"this should not be truncated\", \"property\":" + " {\"nested\": true}}"; @@ -246,7 +242,7 @@ public void resolveTemplateWithHeaderWithNestedJson() { /** This ensures we don't mess up vnd types */ @Test - public void resolveTemplateWithHeaderIncludingSpecialCharacters() { + void resolveTemplateWithHeaderIncludingSpecialCharacters() { RequestTemplate template = new RequestTemplate() .method(HttpMethod.GET) @@ -259,7 +255,7 @@ public void resolveTemplateWithHeaderIncludingSpecialCharacters() { } @Test - public void resolveTemplateWithHeaderEmptyResult() { + void resolveTemplateWithHeaderEmptyResult() { RequestTemplate template = new RequestTemplate().method(HttpMethod.GET).header("Encoded", "{var}"); @@ -269,7 +265,7 @@ public void resolveTemplateWithHeaderEmptyResult() { } @Test - public void resolveTemplateWithMixedRequestLineParams() { + void resolveTemplateWithMixedRequestLineParams() { RequestTemplate template = new RequestTemplate() .method(HttpMethod.GET) // @@ -286,7 +282,7 @@ public void resolveTemplateWithMixedRequestLineParams() { } @Test - public void insertHasQueryParams() { + void insertHasQueryParams() { RequestTemplate template = new RequestTemplate() .method(HttpMethod.GET) // @@ -305,7 +301,7 @@ public void insertHasQueryParams() { } @Test - public void resolveTemplateWithBodyTemplateSetsBodyAndContentLength() { + void resolveTemplateWithBodyTemplateSetsBodyAndContentLength() { RequestTemplate template = new RequestTemplate() .method(HttpMethod.POST) @@ -316,10 +312,7 @@ public void resolveTemplateWithBodyTemplateSetsBodyAndContentLength() { template = template.resolve( - mapOf( - "customer_name", "netflix", - "user_name", "denominator", - "password", "password")); + mapOf("customer_name", "netflix", "user_name", "denominator", "password", "password")); assertThat(template) .hasBody( @@ -332,7 +325,7 @@ public void resolveTemplateWithBodyTemplateSetsBodyAndContentLength() { } @Test - public void resolveTemplateWithBodyTemplateDoesNotDoubleDecode() { + void resolveTemplateWithBodyTemplateDoesNotDoubleDecode() { RequestTemplate template = new RequestTemplate() .method(HttpMethod.POST) @@ -344,9 +337,12 @@ public void resolveTemplateWithBodyTemplateDoesNotDoubleDecode() { template = template.resolve( mapOf( - "customer_name", "netflix", - "user_name", "denominator", - "password", "abc+123%25d8")); + "customer_name", + "netflix", + "user_name", + "denominator", + "password", + "abc+123%25d8")); assertThat(template) .hasBody( @@ -355,7 +351,7 @@ public void resolveTemplateWithBodyTemplateDoesNotDoubleDecode() { } @Test - public void skipUnresolvedQueries() { + void skipUnresolvedQueries() { RequestTemplate template = new RequestTemplate() .method(HttpMethod.GET) @@ -369,7 +365,7 @@ public void skipUnresolvedQueries() { } @Test - public void allQueriesUnresolvable() { + void allQueriesUnresolvable() { RequestTemplate template = new RequestTemplate() .method(HttpMethod.GET) // @@ -383,7 +379,7 @@ public void allQueriesUnresolvable() { } @Test - public void spaceEncodingInUrlParam() { + void spaceEncodingInUrlParam() { RequestTemplate template = new RequestTemplate() .method(HttpMethod.GET) // @@ -395,7 +391,7 @@ public void spaceEncodingInUrlParam() { } @Test - public void useCaseInsensitiveHeaderFieldNames() { + void useCaseInsensitiveHeaderFieldNames() { final RequestTemplate template = new RequestTemplate(); final String value = "value1"; @@ -408,15 +404,15 @@ public void useCaseInsensitiveHeaderFieldNames() { final String assertionMessage = "Header field names should be case insensitive"; - assertNotNull(assertionMessage, test); - assertTrue(assertionMessage, test.contains(value)); - assertTrue(assertionMessage, test.contains(value2)); - assertEquals(1, template.headers().size()); - assertEquals(2, template.headers().get("tesT").size()); + assertThat(test).as(assertionMessage).isNotNull(); + assertThat(test.contains(value)).as(assertionMessage).isTrue(); + assertThat(test.contains(value2)).as(assertionMessage).isTrue(); + assertThat(template.headers()).hasSize(1); + assertThat(template.headers().get("tesT")).hasSize(2); } @Test - public void encodeSlashTest() { + void encodeSlashTest() { RequestTemplate template = new RequestTemplate().method(HttpMethod.GET).uri("/api/{vhost}").decodeSlash(false); @@ -428,14 +424,17 @@ public void encodeSlashTest() { /** Implementations have a bug if they pass junk as the http method. */ @SuppressWarnings("deprecation") @Test - public void uriStuffedIntoMethod() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Invalid HTTP Method: /path?queryParam={queryParam}"); - new RequestTemplate().method("/path?queryParam={queryParam}"); + void uriStuffedIntoMethod() { + Throwable exception = + assertThrows( + IllegalArgumentException.class, + () -> new RequestTemplate().method("/path?queryParam={queryParam}")); + assertThat(exception.getMessage()) + .contains("Invalid HTTP Method: /path?queryParam={queryParam}"); } @Test - public void encodedQueryClearedOnNull() { + void encodedQueryClearedOnNull() { RequestTemplate template = new RequestTemplate(); template.query("param[]", "value"); @@ -446,17 +445,18 @@ public void encodedQueryClearedOnNull() { } @Test - public void encodedQuery() { + void encodedQuery() { RequestTemplate template = new RequestTemplate().query("params[]", "foo%20bar"); assertThat(template.queryLine()).isEqualTo("?params%5B%5D=foo%20bar"); assertThat(template).hasQueries(entry("params[]", Collections.singletonList("foo%20bar"))); } @Test - public void encodedQueryWithUnsafeCharactersMixedWithUnencoded() { + void encodedQueryWithUnsafeCharactersMixedWithUnencoded() { RequestTemplate template = new RequestTemplate() - .query("params[]", "not encoded") // stored as "param%5D%5B" + .query("params[]", "not encoded") // stored as + // "param%5D%5B" .query("params[]", "encoded"); // stored as "param[]" assertThat(template.queryLine()).isEqualTo("?params%5B%5D=not%20encoded¶ms%5B%5D=encoded"); @@ -467,7 +467,7 @@ public void encodedQueryWithUnsafeCharactersMixedWithUnencoded() { @SuppressWarnings("unchecked") @Test - public void shouldRetrieveHeadersWithoutNull() { + void shouldRetrieveHeadersWithoutNull() { RequestTemplate template = new RequestTemplate() .header("key1", (String) null) @@ -503,7 +503,7 @@ public void shouldNotMutateInternalHeadersMap() { } @Test - public void fragmentShouldNotBeEncodedInUri() { + void fragmentShouldNotBeEncodedInUri() { RequestTemplate template = new RequestTemplate() .method(HttpMethod.GET) @@ -514,7 +514,7 @@ public void fragmentShouldNotBeEncodedInUri() { } @Test - public void fragmentShouldNotBeEncodedInTarget() { + void fragmentShouldNotBeEncodedInTarget() { RequestTemplate template = new RequestTemplate() .method(HttpMethod.GET) @@ -525,7 +525,7 @@ public void fragmentShouldNotBeEncodedInTarget() { } @Test - public void urlEncodingRemainsInPlace() { + void urlEncodingRemainsInPlace() { RequestTemplate template = new RequestTemplate().method(HttpMethod.GET).target("https://exa%23mple.com/path%7Cpath"); @@ -533,7 +533,7 @@ public void urlEncodingRemainsInPlace() { } @Test - public void slashShouldNotBeAppendedForMatrixParams() { + void slashShouldNotBeAppendedForMatrixParams() { RequestTemplate template = new RequestTemplate().method(HttpMethod.GET).uri("/path;key1=value1;key2=value2", true); @@ -541,7 +541,7 @@ public void slashShouldNotBeAppendedForMatrixParams() { } @Test - public void encodedReservedPreserveSlash() { + void encodedReservedPreserveSlash() { RequestTemplate template = new RequestTemplate(); template.uri("/get?url={url}"); template.method(HttpMethod.GET); @@ -550,7 +550,7 @@ public void encodedReservedPreserveSlash() { } @Test - public void encodedReservedEncodeSlash() { + void encodedReservedEncodeSlash() { RequestTemplate template = new RequestTemplate(); template.uri("/get?url={url}"); template.decodeSlash(false); diff --git a/core/src/test/java/feign/ResponseTest.java b/core/src/test/java/feign/ResponseTest.java index daf9fac21..915964b9b 100644 --- a/core/src/test/java/feign/ResponseTest.java +++ b/core/src/test/java/feign/ResponseTest.java @@ -13,18 +13,23 @@ */ package feign; -import static feign.assertj.FeignAssertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import feign.Request.HttpMethod; -import java.util.*; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; import org.assertj.core.util.Lists; -import org.junit.Test; +import org.junit.jupiter.api.Test; @SuppressWarnings("deprecation") -public class ResponseTest { +class ResponseTest { @Test - public void reasonPhraseIsOptional() { + void reasonPhraseIsOptional() { Response response = Response.builder() .status(200) @@ -39,7 +44,7 @@ public void reasonPhraseIsOptional() { } @Test - public void canAccessHeadersCaseInsensitively() { + void canAccessHeadersCaseInsensitively() { Map> headersMap = new LinkedHashMap<>(); List valueList = Collections.singletonList("application/json"); headersMap.put("Content-Type", valueList); @@ -65,7 +70,7 @@ public void canAccessHeadersCaseInsensitively() { } @Test - public void headerValuesWithSameNameOnlyVaryingInCaseAreMerged() { + void headerValuesWithSameNameOnlyVaryingInCaseAreMerged() { Map> headersMap = new LinkedHashMap<>(); headersMap.put("Set-Cookie", Arrays.asList("Cookie-A=Value", "Cookie-B=Value")); headersMap.put("set-cookie", Collections.singletonList("Cookie-C=Value")); @@ -88,7 +93,7 @@ public void headerValuesWithSameNameOnlyVaryingInCaseAreMerged() { } @Test - public void headersAreOptional() { + void headersAreOptional() { Response response = Response.builder() .status(200) @@ -100,7 +105,7 @@ public void headersAreOptional() { } @Test - public void support1xxStatusCodes() { + void support1xxStatusCodes() { Response response = Response.builder() .status(103) @@ -113,7 +118,7 @@ public void support1xxStatusCodes() { } @Test - public void statusCodesOfAnyValueAreAllowed() { + void statusCodesOfAnyValueAreAllowed() { Lists.list(600, 50, 35600) .forEach( statusCode -> { diff --git a/core/src/test/java/feign/RetryableExceptionTest.java b/core/src/test/java/feign/RetryableExceptionTest.java index 87b52d6aa..45cabdde2 100644 --- a/core/src/test/java/feign/RetryableExceptionTest.java +++ b/core/src/test/java/feign/RetryableExceptionTest.java @@ -14,16 +14,20 @@ package feign; import static feign.Util.UTF_8; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.assertThat; import java.nio.charset.StandardCharsets; -import java.util.*; -import org.junit.Test; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import org.junit.jupiter.api.Test; -public class RetryableExceptionTest { +class RetryableExceptionTest { @Test - public void createRetryableExceptionWithResponseAndResponseHeader() { + void createRetryableExceptionWithResponseAndResponseHeader() { // given Long retryAfter = 5000L; Request request = @@ -37,10 +41,10 @@ public void createRetryableExceptionWithResponseAndResponseHeader() { new RetryableException(-1, null, null, retryAfter, request, response, responseHeader); // then - assertNotNull(retryableException); - assertEquals(retryAfter, retryableException.retryAfter()); - assertEquals(new String(response, UTF_8), retryableException.contentUTF8()); - assertTrue(retryableException.responseHeaders().containsKey("TEST_HEADER")); - assertTrue(retryableException.responseHeaders().get("TEST_HEADER").contains("TEST_CONTENT")); + assertThat(retryableException).isNotNull(); + assertThat(retryableException.retryAfter()).isEqualTo(retryAfter); + assertThat(retryableException.contentUTF8()).isEqualTo(new String(response, UTF_8)); + assertThat(retryableException.responseHeaders()).containsKey("TEST_HEADER"); + assertThat(retryableException.responseHeaders().get("TEST_HEADER")).contains("TEST_CONTENT"); } } diff --git a/core/src/test/java/feign/RetryerTest.java b/core/src/test/java/feign/RetryerTest.java index 986950fc2..cef416d33 100644 --- a/core/src/test/java/feign/RetryerTest.java +++ b/core/src/test/java/feign/RetryerTest.java @@ -13,72 +13,72 @@ */ package feign; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; +import static org.junit.jupiter.api.Assertions.assertThrows; import feign.Retryer.Default; import java.util.Collections; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; @SuppressWarnings("deprecation") -public class RetryerTest { - - @Rule public final ExpectedException thrown = ExpectedException.none(); +class RetryerTest { private static final Request REQUEST = Request.create(Request.HttpMethod.GET, "/", Collections.emptyMap(), null, Util.UTF_8); @Test - public void only5TriesAllowedAndExponentialBackoff() { + void only5TriesAllowedAndExponentialBackoff() { final Long nonRetryable = null; RetryableException e = new RetryableException(-1, null, null, nonRetryable, REQUEST); Default retryer = new Retryer.Default(); - assertEquals(1, retryer.attempt); - assertEquals(0, retryer.sleptForMillis); - - retryer.continueOrPropagate(e); - assertEquals(2, retryer.attempt); - assertEquals(150, retryer.sleptForMillis); + assertThat(retryer.attempt).isEqualTo(1); + assertThat(retryer.sleptForMillis).isEqualTo(0); retryer.continueOrPropagate(e); - assertEquals(3, retryer.attempt); - assertEquals(375, retryer.sleptForMillis); + assertThat(retryer.attempt).isEqualTo(2); + assertThat(retryer.sleptForMillis).isEqualTo(150); retryer.continueOrPropagate(e); - assertEquals(4, retryer.attempt); - assertEquals(712, retryer.sleptForMillis); + assertThat(retryer.attempt).isEqualTo(3); + assertThat(retryer.sleptForMillis).isEqualTo(375); retryer.continueOrPropagate(e); - assertEquals(5, retryer.attempt); - assertEquals(1218, retryer.sleptForMillis); + assertThat(retryer.attempt).isEqualTo(4); + assertThat(retryer.sleptForMillis).isEqualTo(712); - thrown.expect(RetryableException.class); retryer.continueOrPropagate(e); + assertThat(retryer.attempt).isEqualTo(5); + assertThat(retryer.sleptForMillis).isEqualTo(1218); + assertThrows(RetryableException.class, () -> retryer.continueOrPropagate(e)); } @Test - public void considersRetryAfterButNotMoreThanMaxPeriod() { + void considersRetryAfterButNotMoreThanMaxPeriod() { Default retryer = new Retryer.Default() { + @Override protected long currentTimeMillis() { return 0; } }; retryer.continueOrPropagate(new RetryableException(-1, null, null, 5000L, REQUEST)); - assertEquals(2, retryer.attempt); - assertEquals(1000, retryer.sleptForMillis); + assertThat(retryer.attempt).isEqualTo(2); + assertThat(retryer.sleptForMillis).isEqualTo(1000); } - @Test(expected = RetryableException.class) - public void neverRetryAlwaysPropagates() { - Retryer.NEVER_RETRY.continueOrPropagate(new RetryableException(-1, null, null, 5000L, REQUEST)); + @Test + void neverRetryAlwaysPropagates() { + assertThrows( + RetryableException.class, + () -> + Retryer.NEVER_RETRY.continueOrPropagate( + new RetryableException(-1, null, null, 5000L, REQUEST))); } @Test - public void defaultRetryerFailsOnInterruptedException() { + void defaultRetryerFailsOnInterruptedException() { Default retryer = new Retryer.Default(); Thread.currentThread().interrupt(); @@ -87,11 +87,11 @@ public void defaultRetryerFailsOnInterruptedException() { try { retryer.continueOrPropagate(expected); Thread.interrupted(); // reset interrupted flag in case it wasn't - Assert.fail("Retryer continued despite interruption"); + fail("Retryer continued despite interruption"); } catch (RetryableException e) { - Assert.assertTrue("Interrupted status not reset", Thread.interrupted()); - Assert.assertEquals("Retry attempt not registered as expected", 2, retryer.attempt); - Assert.assertEquals("Unexpected exception found", expected, e); + assertThat(Thread.interrupted()).as("Interrupted status not reset").isTrue(); + assertThat(retryer.attempt).as("Retry attempt not registered as expected").isEqualTo(2); + assertThat(e).as("Unexpected exception found").isEqualTo(expected); } } } diff --git a/core/src/test/java/feign/TargetTest.java b/core/src/test/java/feign/TargetTest.java index a5c85991b..afac1824e 100644 --- a/core/src/test/java/feign/TargetTest.java +++ b/core/src/test/java/feign/TargetTest.java @@ -16,16 +16,17 @@ import static feign.assertj.MockWebServerAssertions.assertThat; import feign.Target.HardCodedTarget; +import java.io.IOException; import java.net.URI; -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.MockWebServer; -import org.junit.Rule; -import org.junit.Test; +import mockwebserver3.MockResponse; +import mockwebserver3.MockWebServer; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; @SuppressWarnings("deprecation") public class TargetTest { - @Rule public final MockWebServer server = new MockWebServer(); + public final MockWebServer server = new MockWebServer(); interface TestQuery { @@ -34,7 +35,7 @@ interface TestQuery { } @Test - public void baseCaseQueryParamsArePercentEncoded() throws InterruptedException { + void baseCaseQueryParamsArePercentEncoded() throws InterruptedException { server.enqueue(new MockResponse()); String baseUrl = server.url("/default").toString(); @@ -49,12 +50,12 @@ public void baseCaseQueryParamsArePercentEncoded() throws InterruptedException { * percent encoding. Here's how. */ @Test - public void targetCanCreateCustomRequest() throws InterruptedException { + void targetCanCreateCustomRequest() throws InterruptedException { server.enqueue(new MockResponse()); String baseUrl = server.url("/default").toString(); Target custom = - new HardCodedTarget(TestQuery.class, baseUrl) { + new HardCodedTarget<>(TestQuery.class, baseUrl) { @Override public Request apply(RequestTemplate input) { @@ -80,7 +81,7 @@ interface UriTarget { } @Test - public void emptyTarget() throws InterruptedException { + void emptyTarget() throws InterruptedException { server.enqueue(new MockResponse()); UriTarget uriTarget = Feign.builder().target(Target.EmptyTarget.create(UriTarget.class)); @@ -94,7 +95,7 @@ public void emptyTarget() throws InterruptedException { } @Test - public void hardCodedTargetWithURI() throws InterruptedException { + void hardCodedTargetWithURI() throws InterruptedException { server.enqueue(new MockResponse()); String host = server.getHostName(); @@ -107,4 +108,9 @@ public void hardCodedTargetWithURI() throws InterruptedException { assertThat(server.takeRequest()).hasPath("/path?query=param").hasQueryParams("query=param"); } + + @AfterEach + void afterEachTest() throws IOException { + server.close(); + } } diff --git a/core/src/test/java/feign/TypesResolveReturnTypeTest.java b/core/src/test/java/feign/TypesResolveReturnTypeTest.java index 206a56365..d6127d1cb 100644 --- a/core/src/test/java/feign/TypesResolveReturnTypeTest.java +++ b/core/src/test/java/feign/TypesResolveReturnTypeTest.java @@ -13,6 +13,8 @@ */ package feign; +import static org.assertj.core.api.Assertions.assertThat; + import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; @@ -24,8 +26,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import org.assertj.core.api.Assertions; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TypesResolveReturnTypeTest { @@ -48,42 +49,42 @@ public Method[] getMethods(Class c) { } @Test - public void simple() { + void simple() { Method[] methods = Simple.class.getMethods(); - Assertions.assertThat(methods.length).isEqualTo(1); + assertThat(methods.length).isEqualTo(1); Type resolved = Types.resolve(Simple.class, Simple.class, methods[0].getGenericReturnType()); - Assertions.assertThat(resolved).isEqualTo(String.class); + assertThat(resolved).isEqualTo(String.class); // included for completeness sake only Type resolvedType = Types.resolveReturnType(Object.class, resolved); - Assertions.assertThat(resolvedType).isEqualTo(resolved); + assertThat(resolvedType).isEqualTo(resolved); } @Test - public void concreteSimple() { + void concreteSimple() { Method[] methods = ConcreteSimple.class.getMethods(); - Assertions.assertThat(methods.length).isEqualTo(1); + assertThat(methods.length).isEqualTo(1); Type resolved = Types.resolve( ConcreteSimple.class, ConcreteSimple.class, methods[0].getGenericReturnType()); - Assertions.assertThat(resolved).isEqualTo(String.class); + assertThat(resolved).isEqualTo(String.class); // included for completeness sake only Type resolvedType = Types.resolveReturnType(Object.class, resolved); - Assertions.assertThat(resolvedType).isEqualTo(resolved); + assertThat(resolvedType).isEqualTo(resolved); } @Test - public void overridingConcreteSimple() { + void overridingConcreteSimple() { Method[] methods = OverridingConcreteSimple.class.getMethods(); - Assertions.assertThat(methods.length).isEqualTo(1); + assertThat(methods.length).isEqualTo(1); Type resolved = Types.resolve( OverridingConcreteSimple.class, OverridingConcreteSimple.class, methods[0].getGenericReturnType()); - Assertions.assertThat(resolved).isEqualTo(String.class); + assertThat(resolved).isEqualTo(String.class); // included for completeness sake only Type resolvedType = Types.resolveReturnType(Object.class, resolved); - Assertions.assertThat(resolvedType).isEqualTo(resolved); + assertThat(resolvedType).isEqualTo(resolved); } interface SimplePrimitive { @@ -98,46 +99,46 @@ interface OverridingConcreteSimplePrimitive extends SimplePrimitive { } @Test - public void simplePrimitive() { + void simplePrimitive() { Method[] methods = SimplePrimitive.class.getMethods(); - Assertions.assertThat(methods.length).isEqualTo(1); + assertThat(methods.length).isEqualTo(1); Type resolved = Types.resolve( SimplePrimitive.class, SimplePrimitive.class, methods[0].getGenericReturnType()); - Assertions.assertThat(resolved).isEqualTo(long.class); + assertThat(resolved).isEqualTo(long.class); // included for completeness sake only Type resolvedType = Types.resolveReturnType(long.class, resolved); - Assertions.assertThat(resolvedType).isEqualTo(resolved); + assertThat(resolvedType).isEqualTo(resolved); } @Test - public void concreteSimplePrimitive() { + void concreteSimplePrimitive() { Method[] methods = ConcreteSimplePrimitive.class.getMethods(); - Assertions.assertThat(methods.length).isEqualTo(1); + assertThat(methods.length).isEqualTo(1); Type resolved = Types.resolve( ConcreteSimplePrimitive.class, ConcreteSimplePrimitive.class, methods[0].getGenericReturnType()); - Assertions.assertThat(resolved).isEqualTo(long.class); + assertThat(resolved).isEqualTo(long.class); // included for completeness sake only Type resolvedType = Types.resolveReturnType(long.class, resolved); - Assertions.assertThat(resolvedType).isEqualTo(resolved); + assertThat(resolvedType).isEqualTo(resolved); } @Test - public void overridingConcreteSimplePrimitive() { + void overridingConcreteSimplePrimitive() { Method[] methods = OverridingConcreteSimplePrimitive.class.getMethods(); - Assertions.assertThat(methods.length).isEqualTo(1); + assertThat(methods.length).isEqualTo(1); Type resolved = Types.resolve( OverridingConcreteSimplePrimitive.class, OverridingConcreteSimplePrimitive.class, methods[0].getGenericReturnType()); - Assertions.assertThat(resolved).isEqualTo(long.class); + assertThat(resolved).isEqualTo(long.class); // included for completeness sake only Type resolvedType = Types.resolveReturnType(long.class, resolved); - Assertions.assertThat(resolvedType).isEqualTo(resolved); + assertThat(resolvedType).isEqualTo(resolved); } interface Generic { @@ -152,49 +153,49 @@ interface OverridingConcreteSimpleClassGenericSecondLevel extends Generic } @Test - public void generic() { + void generic() { Method[] methods = Generic.class.getMethods(); - Assertions.assertThat(methods.length).isEqualTo(1); + assertThat(methods.length).isEqualTo(1); Type resolved = Types.resolve( Generic.class, Generic.class, Generic.class.getMethods()[0].getGenericReturnType()); - Assertions.assertThat(resolved instanceof TypeVariable).isTrue(); + assertThat(resolved instanceof TypeVariable).isTrue(); Type resolvedType = Types.resolveReturnType(Object.class, resolved); - Assertions.assertThat(resolvedType).isEqualTo(resolved); + assertThat(resolvedType).isEqualTo(resolved); } @Test - public void concreteSimpleClassGenericSecondLevel() { + void concreteSimpleClassGenericSecondLevel() { Method[] methods = ConcreteSimpleClassGenericSecondLevel.class.getMethods(); - Assertions.assertThat(methods.length).isEqualTo(1); + assertThat(methods.length).isEqualTo(1); Type resolved = Types.resolve( ConcreteSimpleClassGenericSecondLevel.class, ConcreteSimpleClassGenericSecondLevel.class, methods[0].getGenericReturnType()); - Assertions.assertThat(resolved).isEqualTo(Long.class); + assertThat(resolved).isEqualTo(Long.class); Type resolvedType = Types.resolveReturnType(Object.class, resolved); - Assertions.assertThat(resolvedType).isEqualTo(resolved); + assertThat(resolvedType).isEqualTo(resolved); } @Test - public void overridingConcreteSimpleClassGenericSecondLevel() { + void overridingConcreteSimpleClassGenericSecondLevel() { Method[] methods = getMethods(OverridingConcreteSimpleClassGenericSecondLevel.class); - Assertions.assertThat(methods.length).isEqualTo(2); + assertThat(methods.length).isEqualTo(2); Type resolved = Types.resolve( OverridingConcreteSimpleClassGenericSecondLevel.class, OverridingConcreteSimpleClassGenericSecondLevel.class, methods[0].getGenericReturnType()); - Assertions.assertThat(resolved).isEqualTo(Long.class); + assertThat(resolved).isEqualTo(Long.class); Type resolved2 = Types.resolve( OverridingConcreteSimpleClassGenericSecondLevel.class, OverridingConcreteSimpleClassGenericSecondLevel.class, methods[1].getGenericReturnType()); - Assertions.assertThat(resolved2).isEqualTo(Object.class); + assertThat(resolved2).isEqualTo(Object.class); Type resolvedType = Types.resolveReturnType(resolved, resolved2); - Assertions.assertThat(resolvedType).isEqualTo(resolved); + assertThat(resolvedType).isEqualTo(resolved); } interface SecondGeneric { @@ -229,149 +230,149 @@ interface RealizingOverridingSimpleClassMultipleGenericThirdLevel } @Test - public void concreteSimpleClassMultipleGenericSecondLevel() { + void concreteSimpleClassMultipleGenericSecondLevel() { Method[] methods = ConcreteSimpleClassMultipleGenericSecondLevel.class.getMethods(); - Assertions.assertThat(methods.length).isEqualTo(2); + assertThat(methods.length).isEqualTo(2); Type resolved = Types.resolve( ConcreteSimpleClassMultipleGenericSecondLevel.class, ConcreteSimpleClassMultipleGenericSecondLevel.class, methods[0].getGenericReturnType()); - Assertions.assertThat(resolved).isEqualTo(Long.class); + assertThat(resolved).isEqualTo(Long.class); Type resolved2 = Types.resolve( ConcreteSimpleClassMultipleGenericSecondLevel.class, ConcreteSimpleClassMultipleGenericSecondLevel.class, methods[1].getGenericReturnType()); - Assertions.assertThat(resolved).isEqualTo(Long.class); + assertThat(resolved).isEqualTo(Long.class); Type resolvedType = Types.resolveReturnType(resolved, resolved2); - Assertions.assertThat(resolvedType).isEqualTo(resolved); + assertThat(resolvedType).isEqualTo(resolved); } @Test - public void overridingConcreteSimpleClassMultipleGenericSecondLevel() { + void overridingConcreteSimpleClassMultipleGenericSecondLevel() { Method[] methods = getMethods(OverridingConcreteSimpleClassMultipleGenericSecondLevel.class); - Assertions.assertThat(methods.length).isEqualTo(2); + assertThat(methods.length).isEqualTo(2); Type resolved = Types.resolve( OverridingConcreteSimpleClassMultipleGenericSecondLevel.class, OverridingConcreteSimpleClassMultipleGenericSecondLevel.class, methods[0].getGenericReturnType()); - Assertions.assertThat(resolved).isEqualTo(Long.class); + assertThat(resolved).isEqualTo(Long.class); Type resolved2 = Types.resolve( OverridingConcreteSimpleClassMultipleGenericSecondLevel.class, OverridingConcreteSimpleClassMultipleGenericSecondLevel.class, methods[1].getGenericReturnType()); - Assertions.assertThat(resolved2).isEqualTo(Object.class); + assertThat(resolved2).isEqualTo(Object.class); Type resolvedType = Types.resolveReturnType(resolved, resolved2); - Assertions.assertThat(resolvedType).isEqualTo(resolved); + assertThat(resolvedType).isEqualTo(resolved); } @Test - public void realizingSimpleClassGenericThirdLevel() { + void realizingSimpleClassGenericThirdLevel() { Method[] methods = RealizingSimpleClassGenericThirdLevel.class.getMethods(); // TODO: BUG IN Java Compiler? Multiple same name methods with same return type for same // parameters - Assertions.assertThat(methods.length).isEqualTo(2); + assertThat(methods.length).isEqualTo(2); Type resolved = Types.resolve( RealizingSimpleClassGenericThirdLevel.class, RealizingSimpleClassGenericThirdLevel.class, methods[0].getGenericReturnType()); - Assertions.assertThat(resolved).isEqualTo(Long.class); + assertThat(resolved).isEqualTo(Long.class); Type resolved2 = Types.resolve( RealizingSimpleClassGenericThirdLevel.class, RealizingSimpleClassGenericThirdLevel.class, methods[1].getGenericReturnType()); - Assertions.assertThat(resolved2).isEqualTo(Long.class); + assertThat(resolved2).isEqualTo(Long.class); Type resolvedType = Types.resolveReturnType(resolved, resolved2); - Assertions.assertThat(resolvedType).isEqualTo(resolved); + assertThat(resolvedType).isEqualTo(resolved); } @Test - public void realizingSimpleClassMultipleGenericThirdLevel() { + void realizingSimpleClassMultipleGenericThirdLevel() { Method[] methods = getMethods(RealizingSimpleClassMultipleGenericThirdLevel.class); - Assertions.assertThat(methods.length).isEqualTo(2); + assertThat(methods.length).isEqualTo(2); Type resolved = Types.resolve( RealizingSimpleClassMultipleGenericThirdLevel.class, RealizingSimpleClassMultipleGenericThirdLevel.class, methods[0].getGenericReturnType()); - Assertions.assertThat(resolved).isEqualTo(Long.class); + assertThat(resolved).isEqualTo(Long.class); Type resolved2 = Types.resolve( RealizingSimpleClassMultipleGenericThirdLevel.class, RealizingSimpleClassMultipleGenericThirdLevel.class, methods[1].getGenericReturnType()); - Assertions.assertThat(resolved2).isEqualTo(Object.class); + assertThat(resolved2).isEqualTo(Object.class); Type resolvedType = Types.resolveReturnType(resolved, resolved2); - Assertions.assertThat(resolvedType).isEqualTo(resolved); + assertThat(resolvedType).isEqualTo(resolved); } @Test - public void realizingOverridingSimpleClassGenericThirdLevel() { + void realizingOverridingSimpleClassGenericThirdLevel() { Method[] methods = getMethods(RealizingOverridingSimpleClassGenericThirdLevel.class); - Assertions.assertThat(methods.length).isEqualTo(2); + assertThat(methods.length).isEqualTo(2); Type resolved = Types.resolve( RealizingOverridingSimpleClassGenericThirdLevel.class, RealizingOverridingSimpleClassGenericThirdLevel.class, methods[0].getGenericReturnType()); - Assertions.assertThat(resolved).isEqualTo(Long.class); + assertThat(resolved).isEqualTo(Long.class); Type resolved2 = Types.resolve( RealizingOverridingSimpleClassGenericThirdLevel.class, RealizingOverridingSimpleClassGenericThirdLevel.class, methods[1].getGenericReturnType()); - Assertions.assertThat(resolved2).isEqualTo(Object.class); + assertThat(resolved2).isEqualTo(Object.class); Type resolvedType = Types.resolveReturnType(resolved, resolved2); - Assertions.assertThat(resolvedType).isEqualTo(resolved); + assertThat(resolvedType).isEqualTo(resolved); } @Test - public void realizingOverridingSimpleClassMultipleGenericThirdLevel() { + void realizingOverridingSimpleClassMultipleGenericThirdLevel() { Method[] methods = getMethods(RealizingOverridingSimpleClassMultipleGenericThirdLevel.class); - Assertions.assertThat(methods.length).isEqualTo(2); + assertThat(methods.length).isEqualTo(2); Type resolved = Types.resolve( RealizingOverridingSimpleClassMultipleGenericThirdLevel.class, RealizingOverridingSimpleClassMultipleGenericThirdLevel.class, methods[0].getGenericReturnType()); - Assertions.assertThat(resolved).isEqualTo(Long.class); + assertThat(resolved).isEqualTo(Long.class); Type resolved2 = Types.resolve( RealizingOverridingSimpleClassMultipleGenericThirdLevel.class, RealizingOverridingSimpleClassMultipleGenericThirdLevel.class, methods[1].getGenericReturnType()); - Assertions.assertThat(resolved2).isEqualTo(Object.class); + assertThat(resolved2).isEqualTo(Object.class); Type resolvedType = Types.resolveReturnType(resolved, resolved2); - Assertions.assertThat(resolvedType).isEqualTo(resolved); - Assertions.assertThat(resolvedType).isNotEqualTo(resolved2); + assertThat(resolvedType).isEqualTo(resolved); + assertThat(resolvedType).isNotEqualTo(resolved2); } interface MultipleInheritedGeneric extends Generic, SecondGeneric {} @Test - public void multipleInheritedGeneric() { + void multipleInheritedGeneric() { Method[] methods = MultipleInheritedGeneric.class.getMethods(); - Assertions.assertThat(methods.length).isEqualTo(2); + assertThat(methods.length).isEqualTo(2); Type resolved = Types.resolve( MultipleInheritedGeneric.class, MultipleInheritedGeneric.class, methods[0].getGenericReturnType()); - Assertions.assertThat(resolved instanceof TypeVariable).isTrue(); + assertThat(resolved instanceof TypeVariable).isTrue(); Type resolved2 = Types.resolve( MultipleInheritedGeneric.class, MultipleInheritedGeneric.class, methods[1].getGenericReturnType()); - Assertions.assertThat(resolved2 instanceof TypeVariable).isTrue(); + assertThat(resolved2 instanceof TypeVariable).isTrue(); Type resolvedType = Types.resolveReturnType(resolved, resolved2); - Assertions.assertThat(resolvedType).isEqualTo(resolved2); - Assertions.assertThat(resolvedType).isEqualTo(resolved); + assertThat(resolvedType).isEqualTo(resolved2); + assertThat(resolvedType).isEqualTo(resolved); } interface SecondLevelSimpleClassGeneric extends Generic {} @@ -385,51 +386,51 @@ interface OverridingConcreteSimpleClassGenericThirdLevel } @Test - public void secondLevelSimpleClassGeneric() { + void secondLevelSimpleClassGeneric() { Method[] methods = SecondLevelSimpleClassGeneric.class.getMethods(); - Assertions.assertThat(methods.length).isEqualTo(1); + assertThat(methods.length).isEqualTo(1); Type resolved = Types.resolve( SecondLevelSimpleClassGeneric.class, SecondLevelSimpleClassGeneric.class, methods[0].getGenericReturnType()); - Assertions.assertThat(resolved instanceof TypeVariable).isTrue(); + assertThat(resolved instanceof TypeVariable).isTrue(); Type resolvedType = Types.resolveReturnType(Object.class, resolved); - Assertions.assertThat(resolvedType).isEqualTo(resolved); + assertThat(resolvedType).isEqualTo(resolved); } @Test - public void concreteSimpleClassGenericThirdLevel() { + void concreteSimpleClassGenericThirdLevel() { Method[] methods = ConcreteSimpleClassGenericThirdLevel.class.getMethods(); - Assertions.assertThat(methods.length).isEqualTo(1); + assertThat(methods.length).isEqualTo(1); Type resolved = Types.resolve( ConcreteSimpleClassGenericThirdLevel.class, ConcreteSimpleClassGenericThirdLevel.class, methods[0].getGenericReturnType()); - Assertions.assertThat(resolved).isEqualTo(Long.class); + assertThat(resolved).isEqualTo(Long.class); Type resolvedType = Types.resolveReturnType(Object.class, resolved); - Assertions.assertThat(resolvedType).isEqualTo(resolved); + assertThat(resolvedType).isEqualTo(resolved); } @Test - public void OverridingConcreteSimpleClassGenericThirdLevel() { + void OverridingConcreteSimpleClassGenericThirdLevel() { Method[] methods = getMethods(OverridingConcreteSimpleClassGenericThirdLevel.class); - Assertions.assertThat(methods.length).isEqualTo(2); + assertThat(methods.length).isEqualTo(2); Type resolved = Types.resolve( OverridingConcreteSimpleClassGenericThirdLevel.class, OverridingConcreteSimpleClassGenericThirdLevel.class, methods[0].getGenericReturnType()); - Assertions.assertThat(resolved).isEqualTo(Long.class); + assertThat(resolved).isEqualTo(Long.class); Type resolved2 = Types.resolve( OverridingConcreteSimpleClassGenericThirdLevel.class, OverridingConcreteSimpleClassGenericThirdLevel.class, methods[1].getGenericReturnType()); - Assertions.assertThat(resolved2).isEqualTo(Object.class); + assertThat(resolved2).isEqualTo(Object.class); Type resolvedType = Types.resolveReturnType(resolved, resolved2); - Assertions.assertThat(resolvedType).isEqualTo(resolved); + assertThat(resolvedType).isEqualTo(resolved); } interface SecondLevelGenericClassGeneric> extends Generic {} @@ -477,134 +478,134 @@ interface OverridingConcreteGenericCollectionGenericFifthLevel } @Test - public void secondLevelCollectionGeneric() { + void secondLevelCollectionGeneric() { Method[] methods = SecondLevelCollectionGeneric.class.getMethods(); - Assertions.assertThat(methods.length).isEqualTo(1); + assertThat(methods.length).isEqualTo(1); Type resolved = Types.resolve( SecondLevelCollectionGeneric.class, SecondLevelCollectionGeneric.class, methods[0].getGenericReturnType()); - Assertions.assertThat(resolved instanceof TypeVariable).isTrue(); + assertThat(resolved instanceof TypeVariable).isTrue(); Type resolvedType = Types.resolveReturnType(Object.class, resolved); - Assertions.assertThat(resolvedType).isEqualTo(resolved); + assertThat(resolvedType).isEqualTo(resolved); } @Test - public void thirdLevelCollectionGeneric() { + void thirdLevelCollectionGeneric() { Method[] methods = ThirdLevelCollectionGeneric.class.getMethods(); - Assertions.assertThat(methods.length).isEqualTo(1); + assertThat(methods.length).isEqualTo(1); Type resolved = Types.resolve( ThirdLevelCollectionGeneric.class, ThirdLevelCollectionGeneric.class, methods[0].getGenericReturnType()); - Assertions.assertThat(resolved instanceof TypeVariable).isTrue(); + assertThat(resolved instanceof TypeVariable).isTrue(); Type resolvedType = Types.resolveReturnType(Object.class, resolved); - Assertions.assertThat(resolvedType).isEqualTo(resolved); + assertThat(resolvedType).isEqualTo(resolved); } @Test - public void concreteCollectionGenericFourthLevel() { + void concreteCollectionGenericFourthLevel() { Method[] methods = ConcreteCollectionGenericFourthLevel.class.getMethods(); - Assertions.assertThat(methods.length).isEqualTo(1); + assertThat(methods.length).isEqualTo(1); Type resolved = Types.resolve( ConcreteCollectionGenericFourthLevel.class, ConcreteCollectionGenericFourthLevel.class, methods[0].getGenericReturnType()); - Assertions.assertThat(resolved instanceof ParameterizedType).isTrue(); + assertThat(resolved instanceof ParameterizedType).isTrue(); Type resolvedType = Types.resolveReturnType(Object.class, resolved); - Assertions.assertThat(resolvedType).isEqualTo(resolved); + assertThat(resolvedType).isEqualTo(resolved); } @Test - public void overridingConcreteCollectionGenericFourthLevel() { + void overridingConcreteCollectionGenericFourthLevel() { Method[] methods = getMethods(OverridingConcreteCollectionGenericFourthLevel.class); - Assertions.assertThat(methods.length).isEqualTo(2); + assertThat(methods.length).isEqualTo(2); Type resolved = Types.resolve( OverridingConcreteCollectionGenericFourthLevel.class, OverridingConcreteCollectionGenericFourthLevel.class, methods[1].getGenericReturnType()); - Assertions.assertThat(resolved instanceof ParameterizedType).isTrue(); + assertThat(resolved instanceof ParameterizedType).isTrue(); Type resolved2 = Types.resolve( OverridingConcreteCollectionGenericFourthLevel.class, OverridingConcreteCollectionGenericFourthLevel.class, methods[0].getGenericReturnType()); - Assertions.assertThat(resolved2).isEqualTo(Object.class); + assertThat(resolved2).isEqualTo(Object.class); Type resolvedType = Types.resolveReturnType(resolved, resolved2); - Assertions.assertThat(resolvedType).isEqualTo(resolved); + assertThat(resolvedType).isEqualTo(resolved); } @Test - public void overrideOverridingConcreteCollectionGenericFourthLevel() { + void overrideOverridingConcreteCollectionGenericFourthLevel() { Method[] methods = getMethods(OverrideOverridingConcreteCollectionGenericFourthLevel.class); - Assertions.assertThat(methods.length).isEqualTo(2); + assertThat(methods.length).isEqualTo(2); Type resolved = Types.resolve( OverrideOverridingConcreteCollectionGenericFourthLevel.class, OverrideOverridingConcreteCollectionGenericFourthLevel.class, methods[1].getGenericReturnType()); - Assertions.assertThat(resolved instanceof ParameterizedType).isTrue(); + assertThat(resolved instanceof ParameterizedType).isTrue(); Type resolved2 = Types.resolve( OverrideOverridingConcreteCollectionGenericFourthLevel.class, OverrideOverridingConcreteCollectionGenericFourthLevel.class, methods[0].getGenericReturnType()); - Assertions.assertThat(resolved2).isEqualTo(Object.class); + assertThat(resolved2).isEqualTo(Object.class); Type resolvedType = Types.resolveReturnType(resolved, resolved2); - Assertions.assertThat(resolvedType).isEqualTo(resolved); + assertThat(resolvedType).isEqualTo(resolved); } @Test - public void genericFourthLevelCollectionGeneric() { + void genericFourthLevelCollectionGeneric() { Method[] methods = GenericFourthLevelCollectionGeneric.class.getMethods(); - Assertions.assertThat(methods.length).isEqualTo(1); + assertThat(methods.length).isEqualTo(1); Type resolved = Types.resolve( GenericFourthLevelCollectionGeneric.class, GenericFourthLevelCollectionGeneric.class, methods[0].getGenericReturnType()); - Assertions.assertThat(resolved instanceof ParameterizedType).isTrue(); + assertThat(resolved instanceof ParameterizedType).isTrue(); Type resolvedType = Types.resolveReturnType(Object.class, resolved); - Assertions.assertThat(resolvedType).isEqualTo(resolved); + assertThat(resolvedType).isEqualTo(resolved); } @Test - public void concreteGenericCollectionGenericFifthLevel() { + void concreteGenericCollectionGenericFifthLevel() { Method[] methods = ConcreteGenericCollectionGenericFifthLevel.class.getMethods(); - Assertions.assertThat(methods.length).isEqualTo(1); + assertThat(methods.length).isEqualTo(1); Type resolved = Types.resolve( ConcreteGenericCollectionGenericFifthLevel.class, ConcreteGenericCollectionGenericFifthLevel.class, methods[0].getGenericReturnType()); - Assertions.assertThat(resolved instanceof ParameterizedType).isTrue(); + assertThat(resolved instanceof ParameterizedType).isTrue(); ParameterizedType parameterizedType = (ParameterizedType) resolved; } @Test - public void overridingConcreteGenericCollectionGenericFifthLevel() { + void overridingConcreteGenericCollectionGenericFifthLevel() { Method[] methods = getMethods(OverridingConcreteGenericCollectionGenericFifthLevel.class); - Assertions.assertThat(methods.length).isEqualTo(2); + assertThat(methods.length).isEqualTo(2); Type resolved = Types.resolve( OverridingConcreteGenericCollectionGenericFifthLevel.class, OverridingConcreteGenericCollectionGenericFifthLevel.class, methods[1].getGenericReturnType()); - Assertions.assertThat(resolved instanceof ParameterizedType).isTrue(); + assertThat(resolved instanceof ParameterizedType).isTrue(); Type resolved2 = Types.resolve( OverridingConcreteGenericCollectionGenericFifthLevel.class, OverridingConcreteGenericCollectionGenericFifthLevel.class, methods[0].getGenericReturnType()); - Assertions.assertThat(resolved2).isEqualTo(Object.class); + assertThat(resolved2).isEqualTo(Object.class); Type resolvedType = Types.resolveReturnType( methods[1].getGenericReturnType(), methods[0].getGenericReturnType()); - Assertions.assertThat(resolvedType).isEqualTo(resolved); + assertThat(resolvedType).isEqualTo(resolved); } interface SecondLevelMapGeneric> extends Generic {} diff --git a/core/src/test/java/feign/UtilTest.java b/core/src/test/java/feign/UtilTest.java index cf22fdd17..09eff6971 100644 --- a/core/src/test/java/feign/UtilTest.java +++ b/core/src/test/java/feign/UtilTest.java @@ -19,8 +19,7 @@ import static feign.Util.resolveLastTypeParameter; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; import feign.codec.Decoder; import java.io.Reader; @@ -34,132 +33,134 @@ import java.util.Map; import java.util.Optional; import java.util.Set; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; -public class UtilTest { - - @Rule public ExpectedException thrown = ExpectedException.none(); +class UtilTest { @Test - public void removesEmptyStrings() { + void removesEmptyStrings() { String[] values = new String[] {"", null}; assertThat(removeValues(values, value -> emptyToNull(value) == null, String.class)).isEmpty(); } @Test - public void removesEvenNumbers() { + void removesEvenNumbers() { Integer[] values = {22, 23}; assertThat(removeValues(values, number -> number % 2 == 0, Integer.class)).containsExactly(23); } @Test - public void emptyValueOf() throws Exception { - assertEquals(false, Util.emptyValueOf(boolean.class)); - assertEquals(false, Util.emptyValueOf(Boolean.class)); + void emptyValueOf() throws Exception { + assertThat(Util.emptyValueOf(boolean.class)).isEqualTo(false); + assertThat(Util.emptyValueOf(Boolean.class)).isEqualTo(false); assertThat((byte[]) Util.emptyValueOf(byte[].class)).isEmpty(); - assertEquals(Collections.emptyList(), Util.emptyValueOf(Collection.class)); + assertThat(Util.emptyValueOf(Collection.class)).isEqualTo(Collections.emptyList()); assertThat(((Iterator) Util.emptyValueOf(Iterator.class)).hasNext()).isFalse(); - assertEquals(Collections.emptyList(), Util.emptyValueOf(List.class)); - assertEquals(Collections.emptyMap(), Util.emptyValueOf(Map.class)); - assertEquals(Collections.emptySet(), Util.emptyValueOf(Set.class)); - assertEquals(Optional.empty(), Util.emptyValueOf(Optional.class)); + assertThat(Util.emptyValueOf(List.class)).isEqualTo(Collections.emptyList()); + assertThat(Util.emptyValueOf(Map.class)).isEqualTo(Collections.emptyMap()); + assertThat(Util.emptyValueOf(Set.class)).isEqualTo(Collections.emptySet()); + assertThat(Util.emptyValueOf(Optional.class)).isEqualTo(Optional.empty()); } /** In other words, {@code List} is as empty as {@code List}. */ @Test - public void emptyValueOf_considersRawType() throws Exception { + void emptyValueOf_considersRawType() throws Exception { Type listStringType = LastTypeParameter.class.getDeclaredField("LIST_STRING").getGenericType(); assertThat((List) Util.emptyValueOf(listStringType)).isEmpty(); } /** Ex. your {@code Foo} object would be null, but so would things like Number. */ @Test - public void emptyValueOf_nullForUndefined() throws Exception { + void emptyValueOf_nullForUndefined() throws Exception { assertThat(Util.emptyValueOf(Number.class)).isNull(); assertThat(Util.emptyValueOf(Parameterized.class)).isNull(); } @Test - public void resolveLastTypeParameterWhenNotSubtype() throws Exception { + void resolveLastTypeParameterWhenNotSubtype() throws Exception { Type context = LastTypeParameter.class.getDeclaredField("PARAMETERIZED_LIST_STRING").getGenericType(); Type listStringType = LastTypeParameter.class.getDeclaredField("LIST_STRING").getGenericType(); Type last = resolveLastTypeParameter(context, Parameterized.class); - assertEquals(listStringType, last); + assertThat(last).isEqualTo(listStringType); } @Test - public void lastTypeFromInstance() throws Exception { + void lastTypeFromInstance() throws Exception { Parameterized instance = new ParameterizedSubtype(); Type last = resolveLastTypeParameter(instance.getClass(), Parameterized.class); - assertEquals(String.class, last); + assertThat(last).isEqualTo(String.class); } @Test - public void lastTypeFromAnonymous() throws Exception { + void lastTypeFromAnonymous() throws Exception { Parameterized instance = new Parameterized() {}; Type last = resolveLastTypeParameter(instance.getClass(), Parameterized.class); - assertEquals(Reader.class, last); + assertThat(last).isEqualTo(Reader.class); } @Test - public void resolveLastTypeParameterWhenWildcard() throws Exception { + void resolveLastTypeParameterWhenWildcard() throws Exception { Type context = LastTypeParameter.class .getDeclaredField("PARAMETERIZED_WILDCARD_LIST_STRING") .getGenericType(); Type listStringType = LastTypeParameter.class.getDeclaredField("LIST_STRING").getGenericType(); Type last = resolveLastTypeParameter(context, Parameterized.class); - assertEquals(listStringType, last); + assertThat(last).isEqualTo(listStringType); } @Test - public void resolveLastTypeParameterWhenParameterizedSubtype() throws Exception { + void resolveLastTypeParameterWhenParameterizedSubtype() throws Exception { Type context = LastTypeParameter.class .getDeclaredField("PARAMETERIZED_DECODER_LIST_STRING") .getGenericType(); Type listStringType = LastTypeParameter.class.getDeclaredField("LIST_STRING").getGenericType(); Type last = resolveLastTypeParameter(context, ParameterizedDecoder.class); - assertEquals(listStringType, last); + assertThat(last).isEqualTo(listStringType); } @Test - public void unboundWildcardIsObject() throws Exception { + void unboundWildcardIsObject() throws Exception { Type context = LastTypeParameter.class.getDeclaredField("PARAMETERIZED_DECODER_UNBOUND").getGenericType(); Type last = resolveLastTypeParameter(context, ParameterizedDecoder.class); - assertEquals(Object.class, last); + assertThat(last).isEqualTo(Object.class); } @Test - public void checkArgumentInputFalseNotNullNullOutputIllegalArgumentException() { - // Arrange - final boolean expression = false; - final String errorMessageTemplate = ""; - final Object[] errorMessageArgs = null; - // Act - thrown.expect(IllegalArgumentException.class); - Util.checkArgument(expression, errorMessageTemplate, errorMessageArgs); + void checkArgumentInputFalseNotNullNullOutputIllegalArgumentException() { + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy( + () -> { + // Arrange + final boolean expression = false; + final String errorMessageTemplate = ""; + final Object[] errorMessageArgs = null; + Util.checkArgument(expression, errorMessageTemplate, errorMessageArgs); + // Method is not expected to return due to exception thrown + }); // Method is not expected to return due to exception thrown } @Test - public void checkNotNullInputNullNotNullNullOutputNullPointerException() { - // Arrange - final Object reference = null; - final String errorMessageTemplate = ""; - final Object[] errorMessageArgs = null; - // Act - thrown.expect(NullPointerException.class); - Util.checkNotNull(reference, errorMessageTemplate, errorMessageArgs); + void checkNotNullInputNullNotNullNullOutputNullPointerException() { + assertThatExceptionOfType(NullPointerException.class) + .isThrownBy( + () -> { + // Arrange + final Object reference = null; + final String errorMessageTemplate = ""; + final Object[] errorMessageArgs = null; + Util.checkNotNull(reference, errorMessageTemplate, errorMessageArgs); + // Method is not expected to return due to exception thrown + }); // Method is not expected to return due to exception thrown } @Test - public void checkNotNullInputZeroNotNull0OutputZero() { + void checkNotNullInputZeroNotNull0OutputZero() { // Arrange final Object reference = 0; final String errorMessageTemplate = " "; @@ -167,83 +168,86 @@ public void checkNotNullInputZeroNotNull0OutputZero() { // Act final Object retval = Util.checkNotNull(reference, errorMessageTemplate, errorMessageArgs); // Assert result - assertEquals(0, retval); + assertThat(retval).isEqualTo(0); } @Test - public void checkStateInputFalseNotNullNullOutputIllegalStateException() { - // Arrange - final boolean expression = false; - final String errorMessageTemplate = ""; - final Object[] errorMessageArgs = null; - // Act - thrown.expect(IllegalStateException.class); - Util.checkState(expression, errorMessageTemplate, errorMessageArgs); + void checkStateInputFalseNotNullNullOutputIllegalStateException() { + assertThatExceptionOfType(IllegalStateException.class) + .isThrownBy( + () -> { + // Arrange + final boolean expression = false; + final String errorMessageTemplate = ""; + final Object[] errorMessageArgs = null; + Util.checkState(expression, errorMessageTemplate, errorMessageArgs); + // Method is not expected to return due to exception thrown + }); // Method is not expected to return due to exception thrown } @Test - public void emptyToNullInputNotNullOutputNotNull() { + void emptyToNullInputNotNullOutputNotNull() { // Arrange final String string = "AAAAAAAA"; // Act final String retval = Util.emptyToNull(string); // Assert result - assertEquals("AAAAAAAA", retval); + assertThat(retval).isEqualTo("AAAAAAAA"); } @Test - public void emptyToNullInputNullOutputNull() { + void emptyToNullInputNullOutputNull() { // Arrange final String string = null; // Act final String retval = Util.emptyToNull(string); // Assert result - assertNull(retval); + assertThat(retval).isNull(); } @Test - public void isBlankInputNotNullOutputFalse() { + void isBlankInputNotNullOutputFalse() { // Arrange final String value = "AAAAAAAA"; // Act final boolean retval = Util.isBlank(value); // Assert result - assertEquals(false, retval); + assertThat(retval).isEqualTo(false); } @Test - public void isBlankInputNullOutputTrue() { + void isBlankInputNullOutputTrue() { // Arrange final String value = null; // Act final boolean retval = Util.isBlank(value); // Assert result - assertEquals(true, retval); + assertThat(retval).isEqualTo(true); } @Test - public void isNotBlankInputNotNullOutputFalse() { + void isNotBlankInputNotNullOutputFalse() { // Arrange final String value = ""; // Act final boolean retval = Util.isNotBlank(value); // Assert result - assertEquals(false, retval); + assertThat(retval).isEqualTo(false); } @Test - public void isNotBlankInputNotNullOutputTrue() { + void isNotBlankInputNotNullOutputTrue() { // Arrange final String value = "AAAAAAAA"; // Act final boolean retval = Util.isNotBlank(value); // Assert result - assertEquals(true, retval); + assertThat(retval).isEqualTo(true); } @Test - public void caseInsensitiveCopyOfMap() { + void caseInsensitiveCopyOfMap() { // Arrange Map> sourceMap = new HashMap<>(); @@ -276,7 +280,7 @@ public void caseInsensitiveCopyOfMap() { } @Test - public void copyIsUnmodifiable() { + void copyIsUnmodifiable() { // Arrange Map> sourceMap = new HashMap<>(); @@ -292,7 +296,7 @@ public void copyIsUnmodifiable() { } @Test - public void nullMap() { + void nullMap() { // Act Map> actualMap = caseInsensitiveCopyOf(null); // Assert result diff --git a/core/src/test/java/feign/assertj/MockWebServerAssertions.java b/core/src/test/java/feign/assertj/MockWebServerAssertions.java index af2483547..707798e02 100644 --- a/core/src/test/java/feign/assertj/MockWebServerAssertions.java +++ b/core/src/test/java/feign/assertj/MockWebServerAssertions.java @@ -13,7 +13,7 @@ */ package feign.assertj; -import okhttp3.mockwebserver.RecordedRequest; +import mockwebserver3.RecordedRequest; import org.assertj.core.api.Assertions; public class MockWebServerAssertions extends Assertions { diff --git a/core/src/test/java/feign/assertj/RecordedRequestAssert.java b/core/src/test/java/feign/assertj/RecordedRequestAssert.java index 0a155f2b2..d1ea85820 100644 --- a/core/src/test/java/feign/assertj/RecordedRequestAssert.java +++ b/core/src/test/java/feign/assertj/RecordedRequestAssert.java @@ -28,8 +28,8 @@ import java.util.Set; import java.util.zip.GZIPInputStream; import java.util.zip.InflaterInputStream; +import mockwebserver3.RecordedRequest; import okhttp3.Headers; -import okhttp3.mockwebserver.RecordedRequest; import org.assertj.core.api.AbstractAssert; import org.assertj.core.data.MapEntry; import org.assertj.core.internal.ByteArrays; @@ -138,7 +138,7 @@ public RecordedRequestAssert hasHeaders(String... headerLines) { for (String next : headerLines) { builder.add(next); } - List expected = new ArrayList(); + List expected = new ArrayList<>(); for (Map.Entry> next : builder.build().toMultimap().entrySet()) { expected.add(entry(next.getKey(), next.getValue())); } @@ -154,7 +154,7 @@ public RecordedRequestAssert hasHeaders(MapEntry... expected) { public RecordedRequestAssert hasNoHeaderNamed(final String... names) { isNotNull(); - Set found = new LinkedHashSet(); + Set found = new LinkedHashSet<>(); for (String header : actual.getHeaders().names()) { for (String name : names) { if (header.equalsIgnoreCase(name)) { diff --git a/core/src/test/java/feign/auth/BasicAuthRequestInterceptorTest.java b/core/src/test/java/feign/auth/BasicAuthRequestInterceptorTest.java index 0400665bb..9d15e3859 100644 --- a/core/src/test/java/feign/auth/BasicAuthRequestInterceptorTest.java +++ b/core/src/test/java/feign/auth/BasicAuthRequestInterceptorTest.java @@ -18,12 +18,12 @@ import static org.assertj.core.data.MapEntry.entry; import feign.RequestTemplate; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class BasicAuthRequestInterceptorTest { +class BasicAuthRequestInterceptorTest { @Test - public void addsAuthorizationHeader() { + void addsAuthorizationHeader() { RequestTemplate template = new RequestTemplate(); BasicAuthRequestInterceptor interceptor = new BasicAuthRequestInterceptor("Aladdin", "open sesame"); @@ -34,7 +34,7 @@ public void addsAuthorizationHeader() { } @Test - public void addsAuthorizationHeader_longUserAndPassword() { + void addsAuthorizationHeader_longUserAndPassword() { RequestTemplate template = new RequestTemplate(); BasicAuthRequestInterceptor interceptor = new BasicAuthRequestInterceptor( diff --git a/core/src/test/java/feign/client/AbstractClientTest.java b/core/src/test/java/feign/client/AbstractClientTest.java index f8c1628a9..ccf83e48c 100644 --- a/core/src/test/java/feign/client/AbstractClientTest.java +++ b/core/src/test/java/feign/client/AbstractClientTest.java @@ -16,8 +16,8 @@ import static feign.Util.UTF_8; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.entry; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.fail; +import static org.junit.jupiter.api.Assertions.assertThrows; import feign.Client; import feign.CollectionFormat; @@ -39,22 +39,19 @@ import java.util.List; import java.util.zip.DeflaterOutputStream; import java.util.zip.GZIPOutputStream; -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.MockWebServer; -import okhttp3.mockwebserver.RecordedRequest; +import mockwebserver3.MockResponse; +import mockwebserver3.MockWebServer; +import mockwebserver3.RecordedRequest; import okio.Buffer; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; /** * {@link AbstractClientTest} can be extended to run a set of tests against any {@link Client} * implementation. */ public abstract class AbstractClientTest { - - @Rule public final ExpectedException thrown = ExpectedException.none(); - @Rule public final MockWebServer server = new MockWebServer(); + public final MockWebServer server = new MockWebServer(); /** Create a Feign {@link Builder} with a client configured */ public abstract Builder newBuilder(); @@ -64,14 +61,14 @@ public abstract class AbstractClientTest { * unsupported. */ @Test - public void testPatch() throws Exception { + public void patch() throws Exception { server.enqueue(new MockResponse().setBody("foo")); server.enqueue(new MockResponse()); TestInterface api = newBuilder().target(TestInterface.class, "http://localhost:" + server.getPort()); - assertEquals("foo", api.patch("")); + assertThat(api.patch("")).isEqualTo("foo"); MockWebServerAssertions.assertThat(server.takeRequest()) .hasHeaders( @@ -128,23 +125,23 @@ public void reasonPhraseIsOptional() throws IOException, InterruptedException { } @Test - public void parsesErrorResponse() { - thrown.expect(FeignException.class); - thrown.expectMessage( - "[500 Server Error] during [GET] to [http://localhost:" - + server.getPort() - + "/] [TestInterface#get()]: [ARGHH]"); + void parsesErrorResponse() { server.enqueue(new MockResponse().setResponseCode(500).setBody("ARGHH")); TestInterface api = newBuilder().target(TestInterface.class, "http://localhost:" + server.getPort()); - api.get(); + Throwable exception = assertThrows(FeignException.class, () -> api.get()); + assertThat(exception.getMessage()) + .contains( + "[500 Server Error] during [GET] to [http://localhost:" + + server.getPort() + + "/] [TestInterface#get()]: [ARGHH]"); } @Test - public void parsesErrorResponseBody() { + void parsesErrorResponseBody() { String expectedResponseBody = "ARGHH"; server.enqueue(new MockResponse().setResponseCode(500).setBody("ARGHH")); @@ -176,7 +173,7 @@ public void parsesUnauthorizedResponseBody() { } @Test - public void safeRebuffering() { + void safeRebuffering() { server.enqueue(new MockResponse().setBody("foo")); TestInterface api = @@ -194,7 +191,7 @@ protected void log(String configKey, String format, Object... args) {} /** This shows that is a no-op or otherwise doesn't cause an NPE when there's no content. */ @Test - public void safeRebuffering_noContent() { + void safeRebuffering_noContent() { server.enqueue(new MockResponse().setResponseCode(204)); TestInterface api = @@ -211,7 +208,7 @@ protected void log(String configKey, String format, Object... args) {} } @Test - public void noResponseBodyForPost() throws Exception { + void noResponseBodyForPost() throws Exception { server.enqueue(new MockResponse()); TestInterface api = @@ -245,7 +242,7 @@ public void noResponseBodyForPatch() { } @Test - public void parsesResponseMissingLength() throws IOException { + void parsesResponseMissingLength() throws IOException { server.enqueue(new MockResponse().setChunkedBody("foo", 1)); TestInterface api = @@ -260,7 +257,7 @@ public void parsesResponseMissingLength() throws IOException { } @Test - public void postWithSpacesInPath() throws InterruptedException { + void postWithSpacesInPath() throws InterruptedException { server.enqueue(new MockResponse().setBody("foo")); TestInterface api = @@ -274,7 +271,7 @@ public void postWithSpacesInPath() throws InterruptedException { } @Test - public void testVeryLongResponseNullLength() { + public void veryLongResponseNullLength() { server.enqueue( new MockResponse().setBody("AAAAAAAA").addHeader("Content-Length", Long.MAX_VALUE)); TestInterface api = @@ -286,7 +283,7 @@ public void testVeryLongResponseNullLength() { } @Test - public void testResponseLength() { + void responseLength() { server.enqueue(new MockResponse().setBody("test")); TestInterface api = newBuilder().target(TestInterface.class, "http://localhost:" + server.getPort()); @@ -294,33 +291,33 @@ public void testResponseLength() { Integer expected = 4; Response response = api.post(""); Integer actual = response.body().length(); - assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test - public void testContentTypeWithCharset() throws Exception { + void contentTypeWithCharset() throws Exception { server.enqueue(new MockResponse().setBody("AAAAAAAA")); TestInterface api = newBuilder().target(TestInterface.class, "http://localhost:" + server.getPort()); Response response = api.postWithContentType("foo", "text/plain;charset=utf-8"); // Response length should not be null - assertEquals("AAAAAAAA", Util.toString(response.body().asReader(UTF_8))); + assertThat(Util.toString(response.body().asReader(UTF_8))).isEqualTo("AAAAAAAA"); } @Test - public void testContentTypeWithoutCharset() throws Exception { + void contentTypeWithoutCharset() throws Exception { server.enqueue(new MockResponse().setBody("AAAAAAAA")); TestInterface api = newBuilder().target(TestInterface.class, "http://localhost:" + server.getPort()); Response response = api.postWithContentType("foo", "text/plain"); // Response length should not be null - assertEquals("AAAAAAAA", Util.toString(response.body().asReader(UTF_8))); + assertThat(Util.toString(response.body().asReader(UTF_8))).isEqualTo("AAAAAAAA"); } @Test - public void testContentTypeDefaultsToRequestCharset() throws Exception { + public void contentTypeDefaultsToRequestCharset() throws Exception { server.enqueue(new MockResponse().setBody("foo")); TestInterface api = newBuilder().target(TestInterface.class, "http://localhost:" + server.getPort()); @@ -333,7 +330,7 @@ public void testContentTypeDefaultsToRequestCharset() throws Exception { } @Test - public void testDefaultCollectionFormat() throws Exception { + void defaultCollectionFormat() throws Exception { server.enqueue(new MockResponse().setBody("body")); TestInterface api = @@ -350,7 +347,7 @@ public void testDefaultCollectionFormat() throws Exception { } @Test - public void testHeadersWithNullParams() throws InterruptedException { + void headersWithNullParams() throws InterruptedException { server.enqueue(new MockResponse().setBody("body")); TestInterface api = @@ -368,7 +365,7 @@ public void testHeadersWithNullParams() throws InterruptedException { } @Test - public void testHeadersWithNotEmptyParams() throws InterruptedException { + void headersWithNotEmptyParams() throws InterruptedException { server.enqueue(new MockResponse().setBody("body")); TestInterface api = @@ -386,7 +383,7 @@ public void testHeadersWithNotEmptyParams() throws InterruptedException { } @Test - public void testAlternativeCollectionFormat() throws Exception { + void alternativeCollectionFormat() throws Exception { server.enqueue(new MockResponse().setBody("body")); TestInterface api = @@ -397,7 +394,8 @@ public void testAlternativeCollectionFormat() throws Exception { assertThat(response.status()).isEqualTo(200); assertThat(response.reason()).isEqualTo("OK"); - // Some HTTP libraries percent-encode commas in query parameters and others don't. + // Some HTTP libraries percent-encode commas in query parameters and others + // don't. MockWebServerAssertions.assertThat(server.takeRequest()) .hasMethod("GET") .hasOneOfPath("/?foo=bar,baz", "/?foo=bar%2Cbaz"); @@ -573,4 +571,9 @@ private byte[] deflate(String data) throws Exception { return bos.toByteArray(); } } + + @AfterEach + void afterEachTest() throws IOException { + server.close(); + } } diff --git a/core/src/test/java/feign/client/DefaultClientTest.java b/core/src/test/java/feign/client/DefaultClientTest.java index 41f3ec519..e520fe486 100644 --- a/core/src/test/java/feign/client/DefaultClientTest.java +++ b/core/src/test/java/feign/client/DefaultClientTest.java @@ -15,8 +15,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.entry; -import static org.hamcrest.core.Is.isA; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import feign.Client; import feign.Client.Proxied; @@ -33,24 +32,15 @@ import java.net.SocketAddress; import java.net.URL; import java.util.Collections; -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.SSLSession; -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.SocketPolicy; -import org.junit.Test; +import mockwebserver3.MockResponse; +import mockwebserver3.SocketPolicy; +import org.junit.jupiter.api.Test; /** Tests client-specific behavior, such as ensuring Content-Length is sent when specified. */ public class DefaultClientTest extends AbstractClientTest { protected Client disableHostnameVerification = - new Client.Default( - TrustingSSLSocketFactory.get(), - new HostnameVerifier() { - @Override - public boolean verify(String s, SSLSession sslSession) { - return true; - } - }); + new Client.Default(TrustingSSLSocketFactory.get(), (s, sslSession) -> true); @Override public Builder newBuilder() { @@ -58,8 +48,8 @@ public Builder newBuilder() { } @Test - public void retriesFailedHandshake() throws IOException, InterruptedException { - server.useHttps(TrustingSSLSocketFactory.get("localhost"), false); + void retriesFailedHandshake() throws IOException, InterruptedException { + server.useHttps(TrustingSSLSocketFactory.get("localhost")); server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.FAIL_HANDSHAKE)); server.enqueue(new MockResponse()); @@ -67,12 +57,12 @@ public void retriesFailedHandshake() throws IOException, InterruptedException { newBuilder().target(TestInterface.class, "https://localhost:" + server.getPort()); api.post("foo"); - assertEquals(2, server.getRequestCount()); + assertThat(server.getRequestCount()).isEqualTo(2); } @Test - public void canOverrideSSLSocketFactory() throws IOException, InterruptedException { - server.useHttps(TrustingSSLSocketFactory.get("localhost"), false); + void canOverrideSSLSocketFactory() throws IOException, InterruptedException { + server.useHttps(TrustingSSLSocketFactory.get("localhost")); server.enqueue(new MockResponse()); TestInterface api = @@ -89,10 +79,9 @@ public void canOverrideSSLSocketFactory() throws IOException, InterruptedExcepti */ @Test @Override - public void testPatch() throws Exception { - thrown.expect(RetryableException.class); - thrown.expectCause(isA(ProtocolException.class)); - super.testPatch(); + public void patch() throws Exception { + RetryableException exception = assertThrows(RetryableException.class, super::patch); + assertThat(exception).hasCauseInstanceOf(ProtocolException.class); } @Override @@ -114,14 +103,14 @@ public void noResponseBodyForPut() throws Exception { @Test @Override public void noResponseBodyForPatch() { - thrown.expect(RetryableException.class); - thrown.expectCause(isA(ProtocolException.class)); - super.noResponseBodyForPatch(); + RetryableException exception = + assertThrows(RetryableException.class, super::noResponseBodyForPatch); + assertThat(exception).hasCauseInstanceOf(ProtocolException.class); } @Test - public void canOverrideHostnameVerifier() throws IOException, InterruptedException { - server.useHttps(TrustingSSLSocketFactory.get("bad.example.com"), false); + void canOverrideHostnameVerifier() throws IOException, InterruptedException { + server.useHttps(TrustingSSLSocketFactory.get("bad.example.com")); server.enqueue(new MockResponse()); TestInterface api = @@ -140,7 +129,7 @@ public void canOverrideHostnameVerifier() throws IOException, InterruptedExcepti * we are looking to do here. */ @Test - public void canCreateWithImplicitOrNoCredentials() throws Exception { + void canCreateWithImplicitOrNoCredentials() throws Exception { Proxied proxied = new Proxied(TrustingSSLSocketFactory.get(), null, new Proxy(Type.HTTP, proxyAddress)); assertThat(proxied).isNotNull(); @@ -152,7 +141,7 @@ public void canCreateWithImplicitOrNoCredentials() throws Exception { } @Test - public void canCreateWithExplicitCredentials() throws Exception { + void canCreateWithExplicitCredentials() throws Exception { Proxied proxied = new Proxied( TrustingSSLSocketFactory.get(), diff --git a/core/src/test/java/feign/client/TrustingSSLSocketFactory.java b/core/src/test/java/feign/client/TrustingSSLSocketFactory.java index 8b904b50b..5cb94435d 100644 --- a/core/src/test/java/feign/client/TrustingSSLSocketFactory.java +++ b/core/src/test/java/feign/client/TrustingSSLSocketFactory.java @@ -26,14 +26,19 @@ import java.util.Arrays; import java.util.LinkedHashMap; import java.util.Map; -import javax.net.ssl.*; +import javax.net.ssl.KeyManager; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSocket; +import javax.net.ssl.SSLSocketFactory; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509KeyManager; +import javax.net.ssl.X509TrustManager; /** Used for ssl tests to simplify setup. */ public final class TrustingSSLSocketFactory extends SSLSocketFactory implements X509TrustManager, X509KeyManager { - private static final Map sslSocketFactories = - new LinkedHashMap(); + private static final Map sslSocketFactories = new LinkedHashMap<>(); private static final char[] KEYSTORE_PASSWORD = "password".toCharArray(); private static final String[] ENABLED_CIPHER_SUITES = {"TLS_RSA_WITH_AES_256_CBC_SHA"}; private final SSLSocketFactory delegate; @@ -132,12 +137,15 @@ public Socket createSocket(InetAddress address, int port, InetAddress localAddre return setEnabledCipherSuites(delegate.createSocket(address, port, localAddress, localPort)); } + @Override public X509Certificate[] getAcceptedIssuers() { return null; } + @Override public void checkClientTrusted(X509Certificate[] certs, String authType) {} + @Override public void checkServerTrusted(X509Certificate[] certs, String authType) {} @Override diff --git a/core/src/test/java/feign/codec/DefaultDecoderTest.java b/core/src/test/java/feign/codec/DefaultDecoderTest.java index be1343db2..4b3dfba00 100644 --- a/core/src/test/java/feign/codec/DefaultDecoderTest.java +++ b/core/src/test/java/feign/codec/DefaultDecoderTest.java @@ -14,8 +14,8 @@ package feign.codec; import static feign.Util.UTF_8; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; import feign.Request; import feign.Request.HttpMethod; @@ -27,51 +27,46 @@ import java.util.Collections; import java.util.HashMap; import java.util.Map; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; import org.w3c.dom.Document; @SuppressWarnings("deprecation") -public class DefaultDecoderTest { - - @Rule public final ExpectedException thrown = ExpectedException.none(); +class DefaultDecoderTest { private final Decoder decoder = new Decoder.Default(); @Test - public void testDecodesToString() throws Exception { + void decodesToString() throws Exception { Response response = knownResponse(); Object decodedObject = decoder.decode(response, String.class); - assertEquals(String.class, decodedObject.getClass()); - assertEquals("response body", decodedObject.toString()); + assertThat(decodedObject.getClass()).isEqualTo(String.class); + assertThat(decodedObject.toString()).isEqualTo("response body"); } @Test - public void testDecodesToByteArray() throws Exception { + void decodesToByteArray() throws Exception { Response response = knownResponse(); Object decodedObject = decoder.decode(response, byte[].class); - assertEquals(byte[].class, decodedObject.getClass()); - assertEquals("response body", new String((byte[]) decodedObject, UTF_8)); + assertThat(decodedObject.getClass()).isEqualTo(byte[].class); + assertThat(new String((byte[]) decodedObject, UTF_8)).isEqualTo("response body"); } @Test - public void testDecodesNullBodyToNull() throws Exception { - assertNull(decoder.decode(nullBodyResponse(), Document.class)); + void decodesNullBodyToNull() throws Exception { + assertThat(decoder.decode(nullBodyResponse(), Document.class)).isNull(); } @Test - public void testRefusesToDecodeOtherTypes() throws Exception { - thrown.expect(DecodeException.class); - thrown.expectMessage(" is not a type supported by this decoder."); - - decoder.decode(knownResponse(), Document.class); + void refusesToDecodeOtherTypes() throws Exception { + Throwable exception = + assertThrows(DecodeException.class, () -> decoder.decode(knownResponse(), Document.class)); + assertThat(exception.getMessage()).contains(" is not a type supported by this decoder."); } private Response knownResponse() { String content = "response body"; InputStream inputStream = new ByteArrayInputStream(content.getBytes(UTF_8)); - Map> headers = new HashMap>(); + Map> headers = new HashMap<>(); headers.put("Content-Type", Collections.singleton("text/plain")); return Response.builder() .status(200) diff --git a/core/src/test/java/feign/codec/DefaultEncoderTest.java b/core/src/test/java/feign/codec/DefaultEncoderTest.java index 1fd09c83f..c3d890cd5 100644 --- a/core/src/test/java/feign/codec/DefaultEncoderTest.java +++ b/core/src/test/java/feign/codec/DefaultEncoderTest.java @@ -14,43 +14,40 @@ package feign.codec; import static feign.Util.UTF_8; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; import feign.RequestTemplate; import java.time.Clock; import java.util.Arrays; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; -public class DefaultEncoderTest { - - @Rule public final ExpectedException thrown = ExpectedException.none(); +class DefaultEncoderTest { private final Encoder encoder = new Encoder.Default(); @Test - public void testEncodesStrings() throws Exception { + void encodesStrings() throws Exception { String content = "This is my content"; RequestTemplate template = new RequestTemplate(); encoder.encode(content, String.class, template); - assertEquals(content, new String(template.body(), UTF_8)); + assertThat(new String(template.body(), UTF_8)).isEqualTo(content); } @Test - public void testEncodesByteArray() throws Exception { + void encodesByteArray() throws Exception { byte[] content = {12, 34, 56}; RequestTemplate template = new RequestTemplate(); encoder.encode(content, byte[].class, template); - assertTrue(Arrays.equals(content, template.body())); + assertThat(Arrays.equals(content, template.body())).isTrue(); } @Test - public void testRefusesToEncodeOtherTypes() throws Exception { - thrown.expect(EncodeException.class); - thrown.expectMessage("is not a type supported by this encoder."); - - encoder.encode(Clock.systemUTC(), Clock.class, new RequestTemplate()); + void refusesToEncodeOtherTypes() throws Exception { + Throwable exception = + assertThrows( + EncodeException.class, + () -> encoder.encode(Clock.systemUTC(), Clock.class, new RequestTemplate())); + assertThat(exception.getMessage()).contains("is not a type supported by this encoder."); } } diff --git a/core/src/test/java/feign/codec/DefaultErrorDecoderHttpErrorTest.java b/core/src/test/java/feign/codec/DefaultErrorDecoderHttpErrorTest.java index a9d5ab9fb..6ad7ce24a 100644 --- a/core/src/test/java/feign/codec/DefaultErrorDecoderHttpErrorTest.java +++ b/core/src/test/java/feign/codec/DefaultErrorDecoderHttpErrorTest.java @@ -24,15 +24,12 @@ import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; @SuppressWarnings("deprecation") -@RunWith(Parameterized.class) public class DefaultErrorDecoderHttpErrorTest { - @Parameterized.Parameters(name = "error: [{0}], exception: [{1}]") public static Object[][] errorCodes() { return new Object[][] { { @@ -123,20 +120,19 @@ public static Object[][] errorCodes() { }; } - @Parameterized.Parameter public int httpStatus; - - @Parameterized.Parameter(1) + public int httpStatus; public Class expectedExceptionClass; - - @Parameterized.Parameter(2) public String expectedMessage; private ErrorDecoder errorDecoder = new ErrorDecoder.Default(); private Map> headers = new LinkedHashMap<>(); - @Test - public void testExceptionIsHttpSpecific() throws Throwable { + @MethodSource("errorCodes") + @ParameterizedTest(name = "error: [{0}], exception: [{1}]") + void exceptionIsHttpSpecific(int httpStatus, Class expectedExceptionClass, String expectedMessage) + throws Throwable { + initDefaultErrorDecoderHttpErrorTest(httpStatus, expectedExceptionClass, expectedMessage); Response response = Response.builder() .status(httpStatus) @@ -158,4 +154,11 @@ public void testExceptionIsHttpSpecific() throws Throwable { assertThat(((FeignException) exception).status()).isEqualTo(httpStatus); assertThat(exception.getMessage()).isEqualTo(expectedMessage); } + + public void initDefaultErrorDecoderHttpErrorTest( + int httpStatus, Class expectedExceptionClass, String expectedMessage) { + this.httpStatus = httpStatus; + this.expectedExceptionClass = expectedExceptionClass; + this.expectedMessage = expectedMessage; + } } diff --git a/core/src/test/java/feign/codec/DefaultErrorDecoderTest.java b/core/src/test/java/feign/codec/DefaultErrorDecoderTest.java index 86f1b4770..c7bd27d1b 100644 --- a/core/src/test/java/feign/codec/DefaultErrorDecoderTest.java +++ b/core/src/test/java/feign/codec/DefaultErrorDecoderTest.java @@ -29,23 +29,17 @@ import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; @SuppressWarnings("deprecation") -public class DefaultErrorDecoderTest { - - @Rule public final ExpectedException thrown = ExpectedException.none(); +class DefaultErrorDecoderTest { private ErrorDecoder errorDecoder = new ErrorDecoder.Default(); private Map> headers = new LinkedHashMap<>(); @Test - public void throwsFeignException() throws Throwable { - thrown.expect(FeignException.class); - thrown.expectMessage("[500 Internal server error] during [GET] to [/api] [Service#foo()]: []"); + void throwsFeignException() throws Throwable { Response response = Response.builder() @@ -56,11 +50,13 @@ public void throwsFeignException() throws Throwable { .headers(headers) .build(); - throw errorDecoder.decode("Service#foo()", response); + Throwable exception = errorDecoder.decode("Service#foo()", response); + assertThat(exception.getMessage()) + .contains("[500 Internal server error] during [GET] to [/api] [Service#foo()]: []"); } @Test - public void throwsFeignExceptionIncludingBody() throws Throwable { + void throwsFeignExceptionIncludingBody() throws Throwable { Response response = Response.builder() .status(500) @@ -82,7 +78,7 @@ public void throwsFeignExceptionIncludingBody() throws Throwable { } @Test - public void throwsFeignExceptionIncludingLongBody() throws Throwable { + void throwsFeignExceptionIncludingLongBody() throws Throwable { String actualBody = repeatString("hello world ", 200); Response response = Response.builder() @@ -116,7 +112,7 @@ private String repeatString(String string, int times) { } @Test - public void testFeignExceptionIncludesStatus() { + void feignExceptionIncludesStatus() { Response response = Response.builder() .status(400) @@ -133,9 +129,7 @@ public void testFeignExceptionIncludesStatus() { } @Test - public void retryAfterHeaderThrowsRetryableException() throws Throwable { - thrown.expect(FeignException.class); - thrown.expectMessage("[503 Service Unavailable] during [GET] to [/api] [Service#foo()]: []"); + void retryAfterHeaderThrowsRetryableException() throws Throwable { headers.put(RETRY_AFTER, Collections.singletonList("Sat, 1 Jan 2000 00:00:00 GMT")); Response response = @@ -147,11 +141,13 @@ public void retryAfterHeaderThrowsRetryableException() throws Throwable { .headers(headers) .build(); - throw errorDecoder.decode("Service#foo()", response); + Throwable exception = errorDecoder.decode("Service#foo()", response); + assertThat(exception.getMessage()) + .contains("[503 Service Unavailable] during [GET] to [/api] [Service#foo()]: []"); } @Test - public void lengthOfBodyExceptionTest() { + void lengthOfBodyExceptionTest() { Response response = bigBodyResponse(); Exception defaultException = errorDecoder.decode("Service#foo()", response); assertThat(defaultException.getMessage().length()).isLessThan(response.body().length()); @@ -185,7 +181,7 @@ private Response bigBodyResponse() { + "And bubbling wine dropped from her hand"; InputStream inputStream = new ByteArrayInputStream(content.getBytes(UTF_8)); - Map> headers = new HashMap>(); + Map> headers = new HashMap<>(); headers.put("Content-Type", Collections.singleton("text/plain")); return Response.builder() .status(400) diff --git a/core/src/test/java/feign/codec/RetryAfterDecoderTest.java b/core/src/test/java/feign/codec/RetryAfterDecoderTest.java index 56a739a6f..68c866d64 100644 --- a/core/src/test/java/feign/codec/RetryAfterDecoderTest.java +++ b/core/src/test/java/feign/codec/RetryAfterDecoderTest.java @@ -14,43 +14,43 @@ package feign.codec; import static java.time.format.DateTimeFormatter.RFC_1123_DATE_TIME; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.assertThat; import feign.codec.ErrorDecoder.RetryAfterDecoder; import java.text.ParseException; import java.time.ZonedDateTime; import java.time.format.DateTimeParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class RetryAfterDecoderTest { +class RetryAfterDecoderTest { private final RetryAfterDecoder decoder = new RetryAfterDecoder(RFC_1123_DATE_TIME) { + @Override protected long currentTimeMillis() { return parseDateTime("Sat, 1 Jan 2000 00:00:00 GMT"); } }; @Test - public void malformedDateFailsGracefully() { - assertNull(decoder.apply("Fri, 31 Dec 1999 23:59:59 ZBW")); + void malformedDateFailsGracefully() { + assertThat(decoder.apply("Fri, 31 Dec 1999 23:59:59 ZBW")).isNull(); } @Test - public void rfc822Parses() throws ParseException { - assertEquals( - parseDateTime("Fri, 31 Dec 1999 23:59:59 GMT"), - decoder.apply("Fri, 31 Dec 1999 23:59:59 GMT")); + void rfc822Parses() throws ParseException { + assertThat(decoder.apply("Fri, 31 Dec 1999 23:59:59 GMT")) + .isEqualTo(parseDateTime("Fri, 31 Dec 1999 23:59:59 GMT")); } @Test - public void relativeSecondsParses() throws ParseException { - assertEquals(parseDateTime("Sun, 2 Jan 2000 00:00:00 GMT"), decoder.apply("86400")); + void relativeSecondsParses() throws ParseException { + assertThat(decoder.apply("86400")).isEqualTo(parseDateTime("Sun, 2 Jan 2000 00:00:00 GMT")); } @Test - public void relativeSecondsParseDecimalIntegers() throws ParseException { - assertEquals(parseDateTime("Sun, 2 Jan 2000 00:00:00 GMT"), decoder.apply("86400.0")); + void relativeSecondsParseDecimalIntegers() throws ParseException { + assertThat(decoder.apply("86400.0")).isEqualTo(parseDateTime("Sun, 2 Jan 2000 00:00:00 GMT")); } private Long parseDateTime(String text) { diff --git a/core/src/test/java/feign/optionals/OptionalDecoderTests.java b/core/src/test/java/feign/optionals/OptionalDecoderTests.java index 35d3426b4..ecd65683d 100644 --- a/core/src/test/java/feign/optionals/OptionalDecoderTests.java +++ b/core/src/test/java/feign/optionals/OptionalDecoderTests.java @@ -20,11 +20,11 @@ import feign.codec.Decoder; import java.io.IOException; import java.util.Optional; -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.MockWebServer; -import org.junit.Test; +import mockwebserver3.MockResponse; +import mockwebserver3.MockWebServer; +import org.junit.jupiter.api.Test; -public class OptionalDecoderTests { +class OptionalDecoderTests { interface OptionalInterface { @RequestLine("GET /") @@ -35,7 +35,7 @@ interface OptionalInterface { } @Test - public void simple404OptionalTest() throws IOException, InterruptedException { + void simple404OptionalTest() throws IOException, InterruptedException { final MockWebServer server = new MockWebServer(); server.enqueue(new MockResponse().setResponseCode(404)); server.enqueue(new MockResponse().setBody("foo")); @@ -47,11 +47,11 @@ public void simple404OptionalTest() throws IOException, InterruptedException { .target(OptionalInterface.class, server.url("/").toString()); assertThat(api.getAsOptional().isPresent()).isFalse(); - assertThat(api.getAsOptional().get()).isEqualTo("foo"); + assertThat(api.getAsOptional()).contains("foo"); } @Test - public void simple204OptionalTest() throws IOException, InterruptedException { + void simple204OptionalTest() throws IOException, InterruptedException { final MockWebServer server = new MockWebServer(); server.enqueue(new MockResponse().setResponseCode(204)); @@ -64,7 +64,7 @@ public void simple204OptionalTest() throws IOException, InterruptedException { } @Test - public void test200WithOptionalString() throws IOException, InterruptedException { + void test200WithOptionalString() throws IOException, InterruptedException { final MockWebServer server = new MockWebServer(); server.enqueue(new MockResponse().setResponseCode(200).setBody("foo")); @@ -75,12 +75,12 @@ public void test200WithOptionalString() throws IOException, InterruptedException Optional response = api.getAsOptional(); - assertThat(response.isPresent()).isTrue(); + assertThat(response).isPresent(); assertThat(response).isEqualTo(Optional.of("foo")); } @Test - public void test200WhenResponseBodyIsNull() throws IOException, InterruptedException { + void test200WhenResponseBodyIsNull() throws IOException, InterruptedException { final MockWebServer server = new MockWebServer(); server.enqueue(new MockResponse().setResponseCode(200)); @@ -93,7 +93,7 @@ public void test200WhenResponseBodyIsNull() throws IOException, InterruptedExcep } @Test - public void test200WhenDecodingNoOptional() throws IOException, InterruptedException { + void test200WhenDecodingNoOptional() throws IOException, InterruptedException { final MockWebServer server = new MockWebServer(); server.enqueue(new MockResponse().setResponseCode(200).setBody("foo")); diff --git a/core/src/test/java/feign/querymap/BeanQueryMapEncoderTest.java b/core/src/test/java/feign/querymap/BeanQueryMapEncoderTest.java index 3e2edc5e0..23016c3e4 100644 --- a/core/src/test/java/feign/querymap/BeanQueryMapEncoderTest.java +++ b/core/src/test/java/feign/querymap/BeanQueryMapEncoderTest.java @@ -13,8 +13,7 @@ */ package feign.querymap; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import feign.Param; import feign.QueryMapEncoder; @@ -22,24 +21,22 @@ import java.util.HashMap; import java.util.HashSet; import java.util.Map; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; /** Test for {@link BeanQueryMapEncoder} */ -public class BeanQueryMapEncoderTest { - - @Rule public final ExpectedException thrown = ExpectedException.none(); +class BeanQueryMapEncoderTest { private final QueryMapEncoder encoder = new BeanQueryMapEncoder(); @Test - public void testDefaultEncoder_acceptNullValue() { - assertEquals("Empty map should be returned", Collections.EMPTY_MAP, encoder.encode(null)); + void defaultEncoder_acceptNullValue() { + assertThat(encoder.encode(null)) + .as("Empty map should be returned") + .isEqualTo(Collections.EMPTY_MAP); } @Test - public void testDefaultEncoder_normalClassWithValues() { + void defaultEncoder_normalClassWithValues() { Map expected = new HashMap<>(); expected.put("foo", "fooz"); expected.put("bar", "barz"); @@ -48,20 +45,22 @@ public void testDefaultEncoder_normalClassWithValues() { Map encodedMap = encoder.encode(normalObject); - assertEquals("Unexpected encoded query map", expected, encodedMap); + assertThat(encodedMap).as("Unexpected encoded query map").isEqualTo(expected); } @Test - public void testDefaultEncoder_normalClassWithOutValues() { + void defaultEncoder_normalClassWithOutValues() { NormalObject normalObject = new NormalObject(null, null); Map encodedMap = encoder.encode(normalObject); - assertTrue("Non-empty map generated from null getter: " + encodedMap, encodedMap.isEmpty()); + assertThat(encodedMap.isEmpty()) + .as("Non-empty map generated from null getter: " + encodedMap) + .isTrue(); } @Test - public void testDefaultEncoder_haveSuperClass() { + void defaultEncoder_haveSuperClass() { Map expected = new HashMap<>(); expected.put("page", 1); expected.put("size", 10); @@ -73,11 +72,11 @@ public void testDefaultEncoder_haveSuperClass() { Map encodedMap = encoder.encode(subClass); - assertEquals("Unexpected encoded query map", expected, encodedMap); + assertThat(encodedMap).as("Unexpected encoded query map").isEqualTo(expected); } @Test - public void testDefaultEncoder_withOverriddenParamName() { + void defaultEncoder_withOverriddenParamName() { HashSet expectedNames = new HashSet<>(); expectedNames.add("fooAlias"); expectedNames.add("bar"); @@ -86,7 +85,7 @@ public void testDefaultEncoder_withOverriddenParamName() { final Map encodedMap = encoder.encode(normalObject); - assertEquals("@Param ignored", expectedNames, encodedMap.keySet()); + assertThat(encodedMap.keySet()).as("@Param ignored").isEqualTo(expectedNames); } class NormalObjectWithOverriddenParamName { diff --git a/core/src/test/java/feign/querymap/FieldQueryMapEncoderTest.java b/core/src/test/java/feign/querymap/FieldQueryMapEncoderTest.java index 4e9a77227..d76a7ad33 100644 --- a/core/src/test/java/feign/querymap/FieldQueryMapEncoderTest.java +++ b/core/src/test/java/feign/querymap/FieldQueryMapEncoderTest.java @@ -13,7 +13,7 @@ */ package feign.querymap; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.assertThat; import feign.Param; import feign.QueryMapEncoder; @@ -21,24 +21,22 @@ import java.util.HashMap; import java.util.HashSet; import java.util.Map; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; /** Test for {@link FieldQueryMapEncoder} */ -public class FieldQueryMapEncoderTest { - - @Rule public final ExpectedException thrown = ExpectedException.none(); +class FieldQueryMapEncoderTest { private final QueryMapEncoder encoder = new FieldQueryMapEncoder(); @Test - public void testDefaultEncoder_acceptNullValue() { - assertEquals("Empty map should be returned", Collections.EMPTY_MAP, encoder.encode(null)); + void defaultEncoder_acceptNullValue() { + assertThat(encoder.encode(null)) + .as("Empty map should be returned") + .isEqualTo(Collections.EMPTY_MAP); } @Test - public void testDefaultEncoder_normalClassWithValues() { + void defaultEncoder_normalClassWithValues() { final Map expected = new HashMap<>(); expected.put("foo", "fooz"); expected.put("bar", "barz"); @@ -46,20 +44,22 @@ public void testDefaultEncoder_normalClassWithValues() { final Map encodedMap = encoder.encode(normalObject); - assertEquals("Unexpected encoded query map", expected, encodedMap); + assertThat(encodedMap).as("Unexpected encoded query map").isEqualTo(expected); } @Test - public void testDefaultEncoder_normalClassWithOutValues() { + void defaultEncoder_normalClassWithOutValues() { final NormalObject normalObject = new NormalObject(null, null); final Map encodedMap = encoder.encode(normalObject); - assertTrue("Non-empty map generated from null getter: " + encodedMap, encodedMap.isEmpty()); + assertThat(encodedMap.isEmpty()) + .as("Non-empty map generated from null getter: " + encodedMap) + .isTrue(); } @Test - public void testDefaultEncoder_withOverriddenParamName() { + void defaultEncoder_withOverriddenParamName() { HashSet expectedNames = new HashSet<>(); expectedNames.add("fooAlias"); expectedNames.add("bar"); @@ -68,7 +68,7 @@ public void testDefaultEncoder_withOverriddenParamName() { final Map encodedMap = encoder.encode(normalObject); - assertEquals("@Param ignored", expectedNames, encodedMap.keySet()); + assertThat(encodedMap.keySet()).as("@Param ignored").isEqualTo(expectedNames); } class NormalObject { diff --git a/core/src/test/java/feign/stream/StreamDecoderTest.java b/core/src/test/java/feign/stream/StreamDecoderTest.java index c8b702113..2683fb0c3 100644 --- a/core/src/test/java/feign/stream/StreamDecoderTest.java +++ b/core/src/test/java/feign/stream/StreamDecoderTest.java @@ -17,8 +17,12 @@ import static org.assertj.core.api.Assertions.assertThat; import com.fasterxml.jackson.core.type.TypeReference; -import feign.*; +import feign.Feign; +import feign.Request; import feign.Request.HttpMethod; +import feign.RequestLine; +import feign.Response; +import feign.Util; import java.io.BufferedReader; import java.io.Closeable; import java.io.IOException; @@ -27,12 +31,12 @@ import java.util.Iterator; import java.util.stream.Collectors; import java.util.stream.Stream; -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.MockWebServer; -import org.junit.Test; +import mockwebserver3.MockResponse; +import mockwebserver3.MockWebServer; +import org.junit.jupiter.api.Test; @SuppressWarnings("deprecation") -public class StreamDecoderTest { +class StreamDecoderTest { interface StreamInterface { @RequestLine("GET /") @@ -64,7 +68,7 @@ class Car { + "]\n"; @Test - public void simpleStreamTest() { + void simpleStreamTest() { MockWebServer server = new MockWebServer(); server.enqueue(new MockResponse().setBody("foo\nbar")); @@ -83,7 +87,7 @@ public void simpleStreamTest() { } @Test - public void simpleDefaultStreamTest() { + void simpleDefaultStreamTest() { MockWebServer server = new MockWebServer(); server.enqueue(new MockResponse().setBody("foo\nbar")); @@ -104,7 +108,7 @@ public void simpleDefaultStreamTest() { } @Test - public void simpleDeleteDecoderTest() { + void simpleDeleteDecoderTest() { MockWebServer server = new MockWebServer(); server.enqueue(new MockResponse().setBody("foo\nbar")); @@ -125,7 +129,7 @@ public void simpleDeleteDecoderTest() { } @Test - public void shouldCloseIteratorWhenStreamClosed() throws IOException { + void shouldCloseIteratorWhenStreamClosed() throws IOException { Response response = Response.builder() .status(200) diff --git a/core/src/test/java/feign/template/BodyTemplateTest.java b/core/src/test/java/feign/template/BodyTemplateTest.java index 96df8ca10..3d7d3571e 100644 --- a/core/src/test/java/feign/template/BodyTemplateTest.java +++ b/core/src/test/java/feign/template/BodyTemplateTest.java @@ -16,12 +16,12 @@ import static org.assertj.core.api.Assertions.assertThat; import java.util.Collections; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class BodyTemplateTest { +class BodyTemplateTest { @Test - public void bodyTemplatesSupportJsonOnlyWhenEncoded() { + void bodyTemplatesSupportJsonOnlyWhenEncoded() { String bodyTemplate = "%7B\"resize\": %7B\"method\": \"fit\",\"width\": {size},\"height\": {size}%7D%7D"; BodyTemplate template = BodyTemplate.create(bodyTemplate); diff --git a/core/src/test/java/feign/template/ExpressionsTest.java b/core/src/test/java/feign/template/ExpressionsTest.java index 19e2992e4..ae0ecf3a5 100644 --- a/core/src/test/java/feign/template/ExpressionsTest.java +++ b/core/src/test/java/feign/template/ExpressionsTest.java @@ -19,10 +19,10 @@ import java.util.Collections; import org.junit.jupiter.api.Test; -public class ExpressionsTest { +class ExpressionsTest { @Test - public void simpleExpression() { + void simpleExpression() { Expression expression = Expressions.create("{foo}"); assertThat(expression).isNotNull(); String expanded = expression.expand(Collections.singletonMap("foo", "bar"), false); @@ -30,7 +30,7 @@ public void simpleExpression() { } @Test - public void malformedExpression() { + void malformedExpression() { String[] malformedStrings = {"{:}", "{str1:}", "{str1:{:}", "{str1:{str2:}"}; for (String malformed : malformedStrings) { @@ -43,7 +43,7 @@ public void malformedExpression() { } @Test - public void malformedBodyTemplate() { + void malformedBodyTemplate() { String bodyTemplate = "{" + "a".repeat(65536) + "}"; try { @@ -54,7 +54,7 @@ public void malformedBodyTemplate() { } @Test - public void androidCompatibility() { + void androidCompatibility() { // To match close brace on Android, it must be escaped due to the simpler ICU regex engine String pattern = Expressions.EXPRESSION_PATTERN.pattern(); assertThat(pattern.contains("}")).isEqualTo(pattern.contains("\\}")); diff --git a/core/src/test/java/feign/template/HeaderTemplateTest.java b/core/src/test/java/feign/template/HeaderTemplateTest.java index 266d6d49c..74e9afbec 100644 --- a/core/src/test/java/feign/template/HeaderTemplateTest.java +++ b/core/src/test/java/feign/template/HeaderTemplateTest.java @@ -13,88 +13,84 @@ */ package feign.template; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThrows; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class HeaderTemplateTest { +class HeaderTemplateTest { @Test - public void it_should_throw_exception_when_name_is_null() { + void it_should_throw_exception_when_name_is_null() { IllegalArgumentException exception = assertThrows( IllegalArgumentException.class, () -> HeaderTemplate.create(null, Collections.singletonList("test"))); - assertEquals("name is required.", exception.getMessage()); + assertThat(exception.getMessage()).isEqualTo("name is required."); } @Test - public void it_should_throw_exception_when_name_is_empty() { + void it_should_throw_exception_when_name_is_empty() { IllegalArgumentException exception = assertThrows( IllegalArgumentException.class, () -> HeaderTemplate.create("", Collections.singletonList("test"))); - assertEquals("name is required.", exception.getMessage()); + assertThat(exception.getMessage()).isEqualTo("name is required."); } @Test - public void it_should_throw_exception_when_value_is_null() { + void it_should_throw_exception_when_value_is_null() { IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> HeaderTemplate.create("test", null)); - assertEquals("values are required", exception.getMessage()); + assertThat(exception.getMessage()).isEqualTo("values are required"); } @Test - public void it_should_return_name() { + void it_should_return_name() { HeaderTemplate headerTemplate = HeaderTemplate.create("test", Arrays.asList("test 1", "test 2")); - assertEquals("test", headerTemplate.getName()); + assertThat(headerTemplate.getName()).isEqualTo("test"); } @Test - public void it_should_return_expanded() { + void it_should_return_expanded() { HeaderTemplate headerTemplate = HeaderTemplate.create("hello", Arrays.asList("emre", "savci", "{name}", "{missing}")); - assertEquals("emre, savci", headerTemplate.expand(Collections.emptyMap())); - assertEquals( - "emre, savci, firsts", headerTemplate.expand(Collections.singletonMap("name", "firsts"))); + assertThat(headerTemplate.expand(Collections.emptyMap())).isEqualTo("emre, savci"); + assertThat(headerTemplate.expand(Collections.singletonMap("name", "firsts"))) + .isEqualTo("emre, savci, firsts"); } @Test - public void it_should_return_expanded_literals() { + void it_should_return_expanded_literals() { HeaderTemplate headerTemplate = HeaderTemplate.create("hello", Arrays.asList("emre", "savci", "{replace_me}")); - assertEquals( - "emre, savci, {}", headerTemplate.expand(Collections.singletonMap("replace_me", "{}"))); + assertThat(headerTemplate.expand(Collections.singletonMap("replace_me", "{}"))) + .isEqualTo("emre, savci, {}"); } @Test - public void create_should_preserve_order() { + void create_should_preserve_order() { /* * Since Java 7, HashSet order is stable within a since JVM process, so one of these assertions * should fail if a HashSet is used. */ HeaderTemplate headerTemplateWithFirstOrdering = HeaderTemplate.create("hello", Arrays.asList("test 1", "test 2")); - assertThat( - new ArrayList<>(headerTemplateWithFirstOrdering.getValues()), - equalTo(Arrays.asList("test 1", "test 2"))); + assertThat(new ArrayList<>(headerTemplateWithFirstOrdering.getValues())) + .isEqualTo(Arrays.asList("test 1", "test 2")); HeaderTemplate headerTemplateWithSecondOrdering = HeaderTemplate.create("hello", Arrays.asList("test 2", "test 1")); - assertThat( - new ArrayList<>(headerTemplateWithSecondOrdering.getValues()), - equalTo(Arrays.asList("test 2", "test 1"))); + assertThat(new ArrayList<>(headerTemplateWithSecondOrdering.getValues())) + .isEqualTo(Arrays.asList("test 2", "test 1")); } @Test - public void append_should_preserve_order() { + void append_should_preserve_order() { /* * Since Java 7, HashSet order is stable within a since JVM process, so one of these assertions * should fail if a HashSet is used. @@ -103,39 +99,37 @@ public void append_should_preserve_order() { HeaderTemplate.append( HeaderTemplate.create("hello", Collections.emptyList()), Arrays.asList("test 1", "test 2")); - assertThat( - new ArrayList<>(headerTemplateWithFirstOrdering.getValues()), - equalTo(Arrays.asList("test 1", "test 2"))); + assertThat(new ArrayList<>(headerTemplateWithFirstOrdering.getValues())) + .isEqualTo(Arrays.asList("test 1", "test 2")); HeaderTemplate headerTemplateWithSecondOrdering = HeaderTemplate.append( HeaderTemplate.create("hello", Collections.emptyList()), Arrays.asList("test 2", "test 1")); - assertThat( - new ArrayList<>(headerTemplateWithSecondOrdering.getValues()), - equalTo(Arrays.asList("test 2", "test 1"))); + assertThat(new ArrayList<>(headerTemplateWithSecondOrdering.getValues())) + .isEqualTo(Arrays.asList("test 2", "test 1")); } @Test - public void it_should_support_http_date() { + void it_should_support_http_date() { HeaderTemplate headerTemplate = HeaderTemplate.create("Expires", Collections.singletonList("{expires}")); - assertEquals( - "Wed, 4 Jul 2001 12:08:56 -0700", - headerTemplate.expand( - Collections.singletonMap("expires", "Wed, 4 Jul 2001 12:08:56 -0700"))); + assertThat( + headerTemplate.expand( + Collections.singletonMap("expires", "Wed, 4 Jul 2001 12:08:56 -0700"))) + .isEqualTo("Wed, 4 Jul 2001 12:08:56 -0700"); } @Test - public void it_should_support_json_literal_values() { + void it_should_support_json_literal_values() { HeaderTemplate headerTemplate = HeaderTemplate.create("CustomHeader", Collections.singletonList("{jsonParam}")); - assertEquals( - "{\"string\": \"val\", \"string2\": \"this should not be truncated\"}", - headerTemplate.expand( - Collections.singletonMap( - "jsonParam", - "{\"string\": \"val\", \"string2\": \"this should not be truncated\"}"))); + assertThat( + headerTemplate.expand( + Collections.singletonMap( + "jsonParam", + "{\"string\": \"val\", \"string2\": \"this should not be truncated\"}"))) + .isEqualTo("{\"string\": \"val\", \"string2\": \"this should not be truncated\"}"); } } diff --git a/core/src/test/java/feign/template/QueryTemplateTest.java b/core/src/test/java/feign/template/QueryTemplateTest.java index 02d3b00f9..03aaec41c 100644 --- a/core/src/test/java/feign/template/QueryTemplateTest.java +++ b/core/src/test/java/feign/template/QueryTemplateTest.java @@ -19,19 +19,19 @@ import feign.Util; import java.util.Arrays; import java.util.Collections; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class QueryTemplateTest { +class QueryTemplateTest { @Test - public void templateToQueryString() { + void templateToQueryString() { QueryTemplate template = QueryTemplate.create("name", Arrays.asList("Bob", "James", "Jason"), Util.UTF_8); assertThat(template.toString()).isEqualToIgnoringCase("name=Bob&name=James&name=Jason"); } @Test - public void expandEmptyCollection() { + void expandEmptyCollection() { QueryTemplate template = QueryTemplate.create("people", Collections.singletonList("{people}"), Util.UTF_8); String expanded = template.expand(Collections.singletonMap("people", Collections.emptyList())); @@ -39,7 +39,7 @@ public void expandEmptyCollection() { } @Test - public void expandCollection() { + void expandCollection() { QueryTemplate template = QueryTemplate.create("people", Collections.singletonList("{people}"), Util.UTF_8); String expanded = @@ -48,7 +48,7 @@ public void expandCollection() { } @Test - public void expandCollectionWithBlanks() { + void expandCollectionWithBlanks() { QueryTemplate template = QueryTemplate.create("people", Collections.singletonList("{people}"), Util.UTF_8); String expanded = @@ -57,7 +57,7 @@ public void expandCollectionWithBlanks() { } @Test - public void expandSingleValue() { + void expandSingleValue() { QueryTemplate template = QueryTemplate.create("name", Collections.singletonList("{value}"), Util.UTF_8); String expanded = template.expand(Collections.singletonMap("value", "Magnum P.I.")); @@ -65,7 +65,7 @@ public void expandSingleValue() { } @Test - public void expandMultipleValues() { + void expandMultipleValues() { QueryTemplate template = QueryTemplate.create("name", Arrays.asList("Bob", "James", "Jason"), Util.UTF_8); String expanded = template.expand(Collections.emptyMap()); @@ -73,7 +73,7 @@ public void expandMultipleValues() { } @Test - public void unresolvedQuery() { + void unresolvedQuery() { QueryTemplate template = QueryTemplate.create("name", Collections.singletonList("{value}"), Util.UTF_8); String expanded = template.expand(Collections.emptyMap()); @@ -81,7 +81,7 @@ public void unresolvedQuery() { } @Test - public void unresolvedMultiValueQueryTemplates() { + void unresolvedMultiValueQueryTemplates() { QueryTemplate template = QueryTemplate.create("name", Arrays.asList("{bob}", "{james}", "{jason}"), Util.UTF_8); String expanded = template.expand(Collections.emptyMap()); @@ -89,7 +89,7 @@ public void unresolvedMultiValueQueryTemplates() { } @Test - public void explicitNullValuesAreRemoved() { + void explicitNullValuesAreRemoved() { QueryTemplate template = QueryTemplate.create("name", Collections.singletonList("{value}"), Util.UTF_8); String expanded = template.expand(Collections.singletonMap("value", null)); @@ -97,7 +97,7 @@ public void explicitNullValuesAreRemoved() { } @Test - public void emptyParameterRemains() { + void emptyParameterRemains() { QueryTemplate template = QueryTemplate.create("name", Collections.singletonList("{value}"), Util.UTF_8); String expanded = template.expand(Collections.singletonMap("value", "")); @@ -105,7 +105,7 @@ public void emptyParameterRemains() { } @Test - public void collectionFormat() { + void collectionFormat() { QueryTemplate template = QueryTemplate.create( "name", Arrays.asList("James", "Jason"), Util.UTF_8, CollectionFormat.CSV); @@ -114,7 +114,7 @@ public void collectionFormat() { } @Test - public void expandName() { + void expandName() { QueryTemplate template = QueryTemplate.create("{name}", Arrays.asList("James", "Jason"), Util.UTF_8); String expanded = template.expand(Collections.singletonMap("name", "firsts")); @@ -122,14 +122,14 @@ public void expandName() { } @Test - public void expandPureParameter() { + void expandPureParameter() { QueryTemplate template = QueryTemplate.create("{name}", Collections.emptyList(), Util.UTF_8); String expanded = template.expand(Collections.singletonMap("name", "firsts")); assertThat(expanded).isEqualToIgnoringCase("firsts"); } @Test - public void expandPureParameterWithSlash() { + void expandPureParameterWithSlash() { QueryTemplate template = QueryTemplate.create("/path/{name}", Collections.emptyList(), Util.UTF_8); String expanded = template.expand(Collections.singletonMap("name", "firsts")); @@ -137,7 +137,7 @@ public void expandPureParameterWithSlash() { } @Test - public void expandNameUnresolved() { + void expandNameUnresolved() { QueryTemplate template = QueryTemplate.create("{parameter}", Arrays.asList("James", "Jason"), Util.UTF_8); String expanded = template.expand(Collections.singletonMap("name", "firsts")); @@ -145,7 +145,7 @@ public void expandNameUnresolved() { } @Test - public void expandSingleValueWithComma() { + void expandSingleValueWithComma() { QueryTemplate template = QueryTemplate.create("collection", Collections.singletonList("{collection}"), Util.UTF_8); String expanded = template.expand(Collections.singletonMap("collection", "one,two,three")); @@ -153,7 +153,7 @@ public void expandSingleValueWithComma() { } @Test - public void expandSingleValueWithPipe() { + void expandSingleValueWithPipe() { QueryTemplate template = QueryTemplate.create("collection", Collections.singletonList("{collection}"), Util.UTF_8); String expanded = template.expand(Collections.singletonMap("collection", "one|two|three")); @@ -161,7 +161,7 @@ public void expandSingleValueWithPipe() { } @Test - public void expandSingleValueWithSpace() { + void expandSingleValueWithSpace() { QueryTemplate template = QueryTemplate.create("collection", Collections.singletonList("{collection}"), Util.UTF_8); String expanded = template.expand(Collections.singletonMap("collection", "one two three")); @@ -169,7 +169,7 @@ public void expandSingleValueWithSpace() { } @Test - public void expandSingleValueWithTab() { + void expandSingleValueWithTab() { QueryTemplate template = QueryTemplate.create("collection", Collections.singletonList("{collection}"), Util.UTF_8); String expanded = template.expand(Collections.singletonMap("collection", "one\ttwo\tthree")); @@ -177,7 +177,7 @@ public void expandSingleValueWithTab() { } @Test - public void expandSingleValueWithJson() { + void expandSingleValueWithJson() { QueryTemplate template = QueryTemplate.create("json", Collections.singletonList("{json}"), Util.UTF_8); String expanded = @@ -188,7 +188,7 @@ public void expandSingleValueWithJson() { } @Test - public void expandCollectionValueWithBrackets() { + void expandCollectionValueWithBrackets() { QueryTemplate template = QueryTemplate.create( "collection[]", @@ -202,7 +202,7 @@ public void expandCollectionValueWithBrackets() { } @Test - public void expandCollectionValueWithDollar() { + void expandCollectionValueWithDollar() { QueryTemplate template = QueryTemplate.create( "$collection", diff --git a/core/src/test/java/feign/template/UriTemplateTest.java b/core/src/test/java/feign/template/UriTemplateTest.java index 8f76349fc..c11f6d7df 100644 --- a/core/src/test/java/feign/template/UriTemplateTest.java +++ b/core/src/test/java/feign/template/UriTemplateTest.java @@ -14,7 +14,7 @@ package feign.template; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.junit.jupiter.api.Assertions.assertThrows; import feign.Util; import java.net.URI; @@ -23,29 +23,29 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class UriTemplateTest { +class UriTemplateTest { @Test - public void emptyRelativeTemplate() { + void emptyRelativeTemplate() { String template = "/"; UriTemplate uriTemplate = UriTemplate.create(template, Util.UTF_8); assertThat(uriTemplate.expand(Collections.emptyMap())).isEqualToIgnoringCase("/"); } - @Test(expected = IllegalArgumentException.class) - public void nullTemplate() { - UriTemplate.create(null, Util.UTF_8); + @Test + void nullTemplate() { + assertThrows(IllegalArgumentException.class, () -> UriTemplate.create(null, Util.UTF_8)); } @Test - public void emptyTemplate() { + void emptyTemplate() { UriTemplate.create("", Util.UTF_8); } @Test - public void simpleTemplate() { + void simpleTemplate() { String template = "https://www.example.com/foo/{bar}"; UriTemplate uriTemplate = UriTemplate.create(template, Util.UTF_8); @@ -62,7 +62,7 @@ public void simpleTemplate() { } @Test - public void simpleTemplateMultipleExpressions() { + void simpleTemplateMultipleExpressions() { String template = "https://www.example.com/{foo}/{bar}/details"; UriTemplate uriTemplate = UriTemplate.create(template, Util.UTF_8); @@ -81,7 +81,7 @@ public void simpleTemplateMultipleExpressions() { } @Test - public void simpleTemplateMultipleSequentialExpressions() { + void simpleTemplateMultipleSequentialExpressions() { String template = "https://www.example.com/{foo}{bar}/{baz}/details"; UriTemplate uriTemplate = UriTemplate.create(template, Util.UTF_8); @@ -101,7 +101,7 @@ public void simpleTemplateMultipleSequentialExpressions() { } @Test - public void simpleTemplateUnresolvedVariablesAreRemoved() { + void simpleTemplateUnresolvedVariablesAreRemoved() { String template = "https://www.example.com/{foo}?name={name}"; UriTemplate uriTemplate = UriTemplate.create(template, Util.UTF_8); assertThat(uriTemplate.getVariables()).contains("foo", "name").hasSize(2); @@ -114,7 +114,7 @@ public void simpleTemplateUnresolvedVariablesAreRemoved() { } @Test - public void missingVariablesOnPathAreRemoved() { + void missingVariablesOnPathAreRemoved() { String template = "https://www.example.com/{foo}/items?name={name}"; UriTemplate uriTemplate = UriTemplate.create(template, Util.UTF_8); assertThat(uriTemplate.getVariables()).contains("foo", "name").hasSize(2); @@ -128,7 +128,7 @@ public void missingVariablesOnPathAreRemoved() { } @Test - public void simpleTemplateWithRegularExpressions() { + void simpleTemplateWithRegularExpressions() { String template = "https://www.example.com/{foo:[0-9]{4}}/{bar}"; UriTemplate uriTemplate = UriTemplate.create(template, Util.UTF_8); assertThat(uriTemplate.getVariables()).contains("foo", "bar").hasSize(2); @@ -141,8 +141,8 @@ public void simpleTemplateWithRegularExpressions() { assertThat(URI.create(expandedTemplate)).isNotNull(); } - @Test(expected = IllegalArgumentException.class) - public void simpleTemplateWithRegularExpressionsValidation() { + @Test + void simpleTemplateWithRegularExpressionsValidation() { String template = "https://www.example.com/{foo:[0-9]{4}}/{bar}"; UriTemplate uriTemplate = UriTemplate.create(template, Util.UTF_8); assertThat(uriTemplate.getVariables()).contains("foo", "bar").hasSize(2); @@ -152,13 +152,14 @@ public void simpleTemplateWithRegularExpressionsValidation() { variables.put("bar", "stuff"); /* the foo variable must be a number and no more than four, this should fail */ - uriTemplate.expand(variables); - fail("Should not be able to expand, pattern does not match"); + assertThrows(IllegalArgumentException.class, () -> uriTemplate.expand(variables)); } @Test - public void nestedExpressionsAreLiterals() { - /* the template of {foo{bar}}, will be treated as literals as nested templates are ignored */ + void nestedExpressionsAreLiterals() { + /* + * the template of {foo{bar}}, will be treated as literals as nested templates are ignored + */ String template = "https://www.example.com/{foo{bar}}/{baz}"; UriTemplate uriTemplate = UriTemplate.create(template, Util.UTF_8); assertThat(uriTemplate.getVariables()).contains("baz").hasSize(1); @@ -168,12 +169,12 @@ public void nestedExpressionsAreLiterals() { String expandedTemplate = uriTemplate.expand(variables); assertThat(expandedTemplate) .isEqualToIgnoringCase("https://www.example.com/%7Bfoo%7Bbar%7D%7D/stuff"); - assertThat(URI.create(expandedTemplate)) - .isNotNull(); // this should fail, the result is not a valid uri + assertThat(URI.create(expandedTemplate)).isNotNull(); // this should fail, the result is not a + // valid uri } @Test - public void literalTemplate() { + void literalTemplate() { String template = "https://www.example.com/do/stuff"; UriTemplate uriTemplate = UriTemplate.create(template, Util.UTF_8); String expandedTemplate = uriTemplate.expand(Collections.emptyMap()); @@ -181,22 +182,21 @@ public void literalTemplate() { assertThat(URI.create(expandedTemplate)).isNotNull(); } - @Test(expected = IllegalArgumentException.class) - public void rejectEmptyExpressions() { + @Test + void rejectEmptyExpressions() { String template = "https://www.example.com/{}/things"; - UriTemplate.create(template, Util.UTF_8); - fail("Should not accept empty expressions"); + assertThrows(IllegalArgumentException.class, () -> UriTemplate.create(template, Util.UTF_8)); } @Test - public void testToString() { + void testToString() { String template = "https://www.example.com/foo/{bar}/{baz:[0-9]}"; UriTemplate uriTemplate = UriTemplate.create(template, Util.UTF_8); assertThat(uriTemplate.toString()).isEqualToIgnoringCase(template); } @Test - public void encodeVariables() { + void encodeVariables() { String template = "https://www.example.com/{first}/{last}"; UriTemplate uriTemplate = UriTemplate.create(template, Util.UTF_8); Map variables = new LinkedHashMap<>(); @@ -208,7 +208,7 @@ public void encodeVariables() { } @Test - public void encodeLiterals() { + void encodeLiterals() { String template = "https://www.example.com/A Team"; UriTemplate uriTemplate = UriTemplate.create(template, Util.UTF_8); String expandedTemplate = uriTemplate.expand(Collections.emptyMap()); @@ -216,7 +216,7 @@ public void encodeLiterals() { } @Test - public void ensurePlusIsSupportedOnPath() { + void ensurePlusIsSupportedOnPath() { String template = "https://www.example.com/sam+adams/beer/{type}"; UriTemplate uriTemplate = UriTemplate.create(template, Util.UTF_8); String expanded = uriTemplate.expand(Collections.emptyMap()); @@ -224,7 +224,7 @@ public void ensurePlusIsSupportedOnPath() { } @Test - public void ensurePlusInEncodedAs2BOnQuery() { + void ensurePlusInEncodedAs2BOnQuery() { String template = "https://www.example.com/beer?type={type}"; UriTemplate uriTemplate = UriTemplate.create(template, Util.UTF_8); Map parameters = Collections.singletonMap("type", "sam+adams"); @@ -233,20 +233,21 @@ public void ensurePlusInEncodedAs2BOnQuery() { } @Test - public void incompleteTemplateIsALiteral() { + void incompleteTemplateIsALiteral() { String template = "https://www.example.com/testing/foo}}"; UriTemplate uriTemplate = UriTemplate.create(template, Util.UTF_8); assertThat(uriTemplate.expand(Collections.emptyMap())) .isEqualToIgnoringCase("https://www.example.com/testing/foo%7D%7D"); } - @Test(expected = IllegalArgumentException.class) - public void substituteNullMap() { - UriTemplate.create("stuff", Util.UTF_8).expand(null); + @Test + void substituteNullMap() { + assertThrows( + IllegalArgumentException.class, () -> UriTemplate.create("stuff", Util.UTF_8).expand(null)); } @Test - public void skipAlreadyEncodedLiteral() { + void skipAlreadyEncodedLiteral() { String template = "https://www.example.com/A%20Team"; UriTemplate uriTemplate = UriTemplate.create(template, Util.UTF_8); String expandedTemplate = uriTemplate.expand(Collections.emptyMap()); @@ -254,7 +255,7 @@ public void skipAlreadyEncodedLiteral() { } @Test - public void skipAlreadyEncodedVariable() { + void skipAlreadyEncodedVariable() { String template = "https://www.example.com/testing/{foo}"; UriTemplate uriTemplate = UriTemplate.create(template, Util.UTF_8); String encodedVariable = UriUtils.encode("Johnny Appleseed", Util.UTF_8); @@ -265,7 +266,7 @@ public void skipAlreadyEncodedVariable() { } @Test - public void skipSlashes() { + void skipSlashes() { String template = "https://www.example.com/{path}"; UriTemplate uriTemplate = UriTemplate.create(template, false, Util.UTF_8); Map variables = new LinkedHashMap<>(); @@ -275,7 +276,7 @@ public void skipSlashes() { } @Test - public void encodeSlashes() { + void encodeSlashes() { String template = "https://www.example.com/{path}"; UriTemplate uriTemplate = UriTemplate.create(template, Util.UTF_8); Map variables = new LinkedHashMap<>(); @@ -285,7 +286,7 @@ public void encodeSlashes() { } @Test - public void testLiteralTemplateWithQueryString() { + void literalTemplateWithQueryString() { String template = "https://api.example.com?wsdl"; UriTemplate uriTemplate = UriTemplate.create(template, Util.UTF_8); String expanded = uriTemplate.expand(Collections.emptyMap()); @@ -293,7 +294,7 @@ public void testLiteralTemplateWithQueryString() { } @Test - public void encodeReserved() { + void encodeReserved() { String template = "/get?url={url}"; UriTemplate uriTemplate = UriTemplate.create(template, Util.UTF_8); String expanded = uriTemplate.expand(Collections.singletonMap("url", "https://www.google.com")); @@ -301,7 +302,7 @@ public void encodeReserved() { } @Test - public void pathStyleExpansionSupported() { + void pathStyleExpansionSupported() { String template = "{;who}"; UriTemplate uriTemplate = UriTemplate.create(template, Util.UTF_8); String expanded = uriTemplate.expand(Collections.singletonMap("who", "fred")); @@ -309,7 +310,7 @@ public void pathStyleExpansionSupported() { } @Test - public void pathStyleExpansionEncodesReservedCharacters() { + void pathStyleExpansionEncodesReservedCharacters() { String template = "{;half}"; UriTemplate uriTemplate = UriTemplate.create(template, Util.UTF_8); String expanded = uriTemplate.expand(Collections.singletonMap("half", "50%")); @@ -317,7 +318,7 @@ public void pathStyleExpansionEncodesReservedCharacters() { } @Test - public void pathStyleExpansionSupportedWithLists() { + void pathStyleExpansionSupportedWithLists() { String template = "{;list}"; UriTemplate uriTemplate = UriTemplate.create(template, Util.UTF_8); @@ -331,7 +332,7 @@ public void pathStyleExpansionSupportedWithLists() { } @Test - public void pathStyleExpansionSupportedWithMap() { + void pathStyleExpansionSupportedWithMap() { String template = "/server/matrixParams{;parameters}"; Map parameters = new LinkedHashMap<>(); parameters.put("account", "a"); diff --git a/core/src/test/java/feign/template/UriUtilsTest.java b/core/src/test/java/feign/template/UriUtilsTest.java index 069a1a334..9e273d1a3 100644 --- a/core/src/test/java/feign/template/UriUtilsTest.java +++ b/core/src/test/java/feign/template/UriUtilsTest.java @@ -16,13 +16,13 @@ import static java.nio.charset.StandardCharsets.UTF_8; import static org.assertj.core.api.Assertions.assertThat; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class UriUtilsTest { +class UriUtilsTest { /** pct-encode a String, ensuring that all reserved characters are encoded. */ @Test - public void pctEncode() { + void pctEncode() { String queryParameterValue = "firstName=James;lastName=Bond;location=England&Britain?"; assertThat(UriUtils.encode(queryParameterValue, UTF_8)) .isEqualToIgnoringCase( @@ -31,7 +31,7 @@ public void pctEncode() { /** pct-encode preserving reserved characters. */ @Test - public void pctEncodeWithReservedCharacters() { + void pctEncodeWithReservedCharacters() { String withReserved = "/api/user@host:port#section[a-z]/data"; String encoded = UriUtils.encode(withReserved, UTF_8, true); assertThat(encoded).isEqualTo("/api/user@host:port#section[a-z]/data"); diff --git a/core/src/test/java/feign/utils/ExceptionUtilsTest.java b/core/src/test/java/feign/utils/ExceptionUtilsTest.java index e5ceadf20..1d89ffa20 100644 --- a/core/src/test/java/feign/utils/ExceptionUtilsTest.java +++ b/core/src/test/java/feign/utils/ExceptionUtilsTest.java @@ -15,25 +15,25 @@ import static org.assertj.core.api.Assertions.assertThat; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class ExceptionUtilsTest { +class ExceptionUtilsTest { @Test - public void rootCauseOfNullIsNull() { + void rootCauseOfNullIsNull() { Throwable e = null; Throwable rootCause = ExceptionUtils.getRootCause(e); assertThat(rootCause).isNull(); } @Test - public void rootCauseIsSelf() { + void rootCauseIsSelf() { Throwable e = new Exception(); Throwable rootCause = ExceptionUtils.getRootCause(e); assertThat(rootCause).isSameAs(e); } @Test - public void rootCauseIsDifferent() { + void rootCauseIsDifferent() { Throwable rootCause = new Exception(); Throwable e = new Exception(rootCause); Throwable actualRootCause = ExceptionUtils.getRootCause(e); diff --git a/dropwizard-metrics4/pom.xml b/dropwizard-metrics4/pom.xml index 5f1d60b74..65778b35c 100644 --- a/dropwizard-metrics4/pom.xml +++ b/dropwizard-metrics4/pom.xml @@ -44,11 +44,6 @@ metrics-core 4.2.23 - - org.hamcrest - hamcrest - test - ${project.groupId} feign-micrometer diff --git a/dropwizard-metrics4/src/test/java/feign/metrics4/Metrics4CapabilityTest.java b/dropwizard-metrics4/src/test/java/feign/metrics4/Metrics4CapabilityTest.java index a20c00884..d6717994c 100644 --- a/dropwizard-metrics4/src/test/java/feign/metrics4/Metrics4CapabilityTest.java +++ b/dropwizard-metrics4/src/test/java/feign/metrics4/Metrics4CapabilityTest.java @@ -13,9 +13,6 @@ */ package feign.metrics4; -import static org.hamcrest.Matchers.allOf; -import static org.hamcrest.Matchers.containsString; - import com.codahale.metrics.Metered; import com.codahale.metrics.Metric; import com.codahale.metrics.MetricRegistry; @@ -25,7 +22,6 @@ import java.util.Arrays; import java.util.Map; import java.util.Map.Entry; -import org.hamcrest.Matcher; public class Metrics4CapabilityTest extends AbstractMetricsTestBase { @@ -47,9 +43,8 @@ protected Map getFeignMetrics() { @Override protected boolean doesMetricIdIncludeClient(String metricId) { - Matcher containsBase = containsString("feign.micrometer.AbstractMetricsTestBase$"); - Matcher containsSource = containsString("Source"); - return allOf(containsBase, containsSource).matches(metricId); + return metricId.contains("feign.micrometer.AbstractMetricsTestBase$") + && metricId.contains("Source"); } @Override diff --git a/dropwizard-metrics5/pom.xml b/dropwizard-metrics5/pom.xml index c5fbebc5b..1e4b967d1 100644 --- a/dropwizard-metrics5/pom.xml +++ b/dropwizard-metrics5/pom.xml @@ -44,11 +44,6 @@ metrics-core 5.0.0 - - org.hamcrest - hamcrest - test - ${project.groupId} feign-micrometer diff --git a/dropwizard-metrics5/src/test/java/feign/metrics5/Metrics5CapabilityTest.java b/dropwizard-metrics5/src/test/java/feign/metrics5/Metrics5CapabilityTest.java index 39e83f0ce..67027aa35 100644 --- a/dropwizard-metrics5/src/test/java/feign/metrics5/Metrics5CapabilityTest.java +++ b/dropwizard-metrics5/src/test/java/feign/metrics5/Metrics5CapabilityTest.java @@ -13,10 +13,6 @@ */ package feign.metrics5; -import static org.hamcrest.Matchers.allOf; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.hasEntry; - import feign.Capability; import feign.Util; import feign.micrometer.AbstractMetricsTestBase; @@ -27,7 +23,6 @@ import java.util.Arrays; import java.util.Map; import java.util.Map.Entry; -import org.hamcrest.Matcher; public class Metrics5CapabilityTest extends AbstractMetricsTestBase { @@ -50,20 +45,20 @@ protected Map getFeignMetrics() { @Override protected boolean doesMetricIdIncludeClient(MetricName metricId) { String tag = metricId.getTags().get("client"); - Matcher containsBase = containsString("feign.micrometer.AbstractMetricsTestBase$"); - Matcher containsSource = containsString("Source"); - return allOf(containsBase, containsSource).matches(tag); + return tag.contains("feign.micrometer.AbstractMetricsTestBase$") && tag.contains("Source"); } @Override protected boolean doesMetricIncludeVerb(MetricName metricId, String verb) { - return hasEntry("method", verb).matches(metricId.getTags()); + String entry = metricId.getTags().get("method"); + return entry != null && entry.equals(verb); } @Override protected boolean doesMetricIncludeHost(MetricName metricId) { // hostname is null due to feign-mock shortfalls - return hasEntry("host", null).matches(metricId.getTags()); + String entry = metricId.getTags().get("host"); + return entry == null; } @Override diff --git a/example-github-with-coroutine/src/test/java/feign/example/github/GitHubExampleIT.java b/example-github-with-coroutine/src/test/java/feign/example/github/GitHubExampleIT.java index 2e580c2f7..8293497e2 100644 --- a/example-github-with-coroutine/src/test/java/feign/example/github/GitHubExampleIT.java +++ b/example-github-with-coroutine/src/test/java/feign/example/github/GitHubExampleIT.java @@ -13,20 +13,19 @@ */ package feign.example.github; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.util.Arrays; import org.apache.commons.exec.CommandLine; import org.apache.commons.exec.DefaultExecutor; -import org.hamcrest.CoreMatchers; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Run main for {@link GitHubExampleIT} */ -public class GitHubExampleIT { +class GitHubExampleIT { @Test - public void runMain() throws Exception { + void runMain() throws Exception { final String jar = Arrays.stream(new File("target").listFiles()) .filter( @@ -41,6 +40,6 @@ public void runMain() throws Exception { final CommandLine cmdLine = CommandLine.parse(line); final int exitValue = new DefaultExecutor().execute(cmdLine); - assertThat(exitValue, CoreMatchers.equalTo(0)); + assertThat(exitValue).isEqualTo(0); } } diff --git a/example-github/src/test/java/feign/example/github/GitHubExampleIT.java b/example-github/src/test/java/feign/example/github/GitHubExampleIT.java index 2161c4499..e83c75342 100644 --- a/example-github/src/test/java/feign/example/github/GitHubExampleIT.java +++ b/example-github/src/test/java/feign/example/github/GitHubExampleIT.java @@ -13,20 +13,19 @@ */ package feign.example.github; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.util.Arrays; import org.apache.commons.exec.CommandLine; import org.apache.commons.exec.DefaultExecutor; -import org.hamcrest.CoreMatchers; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Run main for {@link GitHubExampleIT} */ -public class GitHubExampleIT { +class GitHubExampleIT { @Test - public void runMain() throws Exception { + void runMain() throws Exception { final String jar = Arrays.stream(new File("target").listFiles()) .filter( @@ -41,6 +40,6 @@ public void runMain() throws Exception { final CommandLine cmdLine = CommandLine.parse(line); final int exitValue = new DefaultExecutor().execute(cmdLine); - assertThat(exitValue, CoreMatchers.equalTo(0)); + assertThat(exitValue).isEqualTo(0); } } diff --git a/example-wikipedia-with-springboot/src/test/java/feign/example/wikipedia/WikipediaExampleIT.java b/example-wikipedia-with-springboot/src/test/java/feign/example/wikipedia/WikipediaExampleIT.java index 74113257d..bd3592174 100644 --- a/example-wikipedia-with-springboot/src/test/java/feign/example/wikipedia/WikipediaExampleIT.java +++ b/example-wikipedia-with-springboot/src/test/java/feign/example/wikipedia/WikipediaExampleIT.java @@ -13,20 +13,19 @@ */ package feign.example.wikipedia; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.util.Arrays; import org.apache.commons.exec.CommandLine; import org.apache.commons.exec.DefaultExecutor; -import org.hamcrest.CoreMatchers; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Run main for {@link WikipediaExampleIT} */ -public class WikipediaExampleIT { +class WikipediaExampleIT { @Test - public void runMain() throws Exception { + void runMain() throws Exception { final String jar = Arrays.stream(new File("target").listFiles()) .filter( @@ -41,6 +40,6 @@ public void runMain() throws Exception { final CommandLine cmdLine = CommandLine.parse(line); final int exitValue = new DefaultExecutor().execute(cmdLine); - assertThat(exitValue, CoreMatchers.equalTo(0)); + assertThat(exitValue).isEqualTo(0); } } diff --git a/example-wikipedia/src/test/java/feign/example/wikipedia/WikipediaExampleIT.java b/example-wikipedia/src/test/java/feign/example/wikipedia/WikipediaExampleIT.java index 112c6e557..a7e700409 100644 --- a/example-wikipedia/src/test/java/feign/example/wikipedia/WikipediaExampleIT.java +++ b/example-wikipedia/src/test/java/feign/example/wikipedia/WikipediaExampleIT.java @@ -13,20 +13,19 @@ */ package feign.example.wikipedia; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.util.Arrays; import org.apache.commons.exec.CommandLine; import org.apache.commons.exec.DefaultExecutor; -import org.hamcrest.CoreMatchers; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Run main for {@link WikipediaExampleIT} */ -public class WikipediaExampleIT { +class WikipediaExampleIT { @Test - public void runMain() throws Exception { + void runMain() throws Exception { final String jar = Arrays.stream(new File("target").listFiles()) .filter( @@ -41,6 +40,6 @@ public void runMain() throws Exception { final CommandLine cmdLine = CommandLine.parse(line); final int exitValue = new DefaultExecutor().execute(cmdLine); - assertThat(exitValue, CoreMatchers.equalTo(0)); + assertThat(exitValue).isEqualTo(0); } } diff --git a/googlehttpclient/pom.xml b/googlehttpclient/pom.xml index f883ad507..a31391217 100644 --- a/googlehttpclient/pom.xml +++ b/googlehttpclient/pom.xml @@ -51,7 +51,7 @@ com.squareup.okhttp3 - mockwebserver + mockwebserver3-junit5 test diff --git a/googlehttpclient/src/test/java/feign/googlehttpclient/GoogleHttpClientTest.java b/googlehttpclient/src/test/java/feign/googlehttpclient/GoogleHttpClientTest.java index dfb66d360..b5f922333 100644 --- a/googlehttpclient/src/test/java/feign/googlehttpclient/GoogleHttpClientTest.java +++ b/googlehttpclient/src/test/java/feign/googlehttpclient/GoogleHttpClientTest.java @@ -14,9 +14,9 @@ package feign.googlehttpclient; import static feign.Util.UTF_8; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.entry; -import static org.junit.Assert.assertEquals; -import static org.junit.Assume.assumeFalse; +import static org.junit.jupiter.api.Assumptions.assumeFalse; import feign.Feign; import feign.Feign.Builder; @@ -25,8 +25,8 @@ import feign.assertj.MockWebServerAssertions; import feign.client.AbstractClientTest; import java.util.Collections; -import okhttp3.mockwebserver.MockResponse; -import org.junit.Test; +import mockwebserver3.MockResponse; +import org.junit.jupiter.api.Test; public class GoogleHttpClientTest extends AbstractClientTest { @Override @@ -40,7 +40,7 @@ public Builder newBuilder() { public void noResponseBodyForPatch() {} @Override - public void testPatch() {} + public void patch() {} @Override public void parsesUnauthorizedResponseBody() {} @@ -51,38 +51,38 @@ public void parsesUnauthorizedResponseBody() {} */ @Override public void canSupportGzip() throws Exception { - assumeFalse("Google HTTP client client do not support gzip compression", false); + assumeFalse(false, "Google HTTP client client do not support gzip compression"); } @Override public void canSupportGzipOnError() throws Exception { - assumeFalse("Google HTTP client client do not support gzip compression", false); + assumeFalse(false, "Google HTTP client client do not support gzip compression"); } @Override public void canSupportDeflate() throws Exception { - assumeFalse("Google HTTP client client do not support deflate compression", false); + assumeFalse(false, "Google HTTP client client do not support deflate compression"); } @Override public void canSupportDeflateOnError() throws Exception { - assumeFalse("Google HTTP client client do not support deflate compression", false); + assumeFalse(false, "Google HTTP client client do not support deflate compression"); } @Override public void canExceptCaseInsensitiveHeader() throws Exception { - assumeFalse("Google HTTP client client do not support gzip compression", false); + assumeFalse(false, "Google HTTP client client do not support gzip compression"); } @Test - public void testContentTypeHeaderGetsAddedOnce() throws Exception { + void contentTypeHeaderGetsAddedOnce() throws Exception { server.enqueue(new MockResponse().setBody("AAAAAAAA")); TestInterface api = newBuilder().target(TestInterface.class, "http://localhost:" + server.getPort()); Response response = api.postWithContentType("foo", "text/plain"); // Response length should not be null - assertEquals("AAAAAAAA", Util.toString(response.body().asReader(UTF_8))); + assertThat(Util.toString(response.body().asReader(UTF_8))).isEqualTo("AAAAAAAA"); MockWebServerAssertions.assertThat(server.takeRequest()) .hasHeaders( @@ -92,7 +92,7 @@ public void testContentTypeHeaderGetsAddedOnce() throws Exception { } @Override - public void testVeryLongResponseNullLength() { - assumeFalse("JaxRS client hang if the response doesn't have a payload", false); + public void veryLongResponseNullLength() { + assumeFalse(false, "JaxRS client hang if the response doesn't have a payload"); } } diff --git a/gson/src/test/java/feign/gson/GsonCodecTest.java b/gson/src/test/java/feign/gson/GsonCodecTest.java index 1bf6455f9..628141a3d 100644 --- a/gson/src/test/java/feign/gson/GsonCodecTest.java +++ b/gson/src/test/java/feign/gson/GsonCodecTest.java @@ -15,8 +15,7 @@ import static feign.Util.UTF_8; import static feign.assertj.FeignAssertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import com.google.gson.TypeAdapter; import com.google.gson.reflect.TypeToken; @@ -34,13 +33,13 @@ import java.util.LinkedList; import java.util.List; import java.util.Map; -import org.junit.Test; +import org.junit.jupiter.api.Test; @SuppressWarnings("deprecation") -public class GsonCodecTest { +class GsonCodecTest { @Test - public void encodesMapObjectNumericalValuesAsInteger() { + void encodesMapObjectNumericalValuesAsInteger() { Map map = new LinkedHashMap<>(); map.put("foo", 1); @@ -56,7 +55,7 @@ public void encodesMapObjectNumericalValuesAsInteger() { } @Test - public void decodesMapObjectNumericalValuesAsInteger() throws Exception { + void decodesMapObjectNumericalValuesAsInteger() throws Exception { Map map = new LinkedHashMap<>(); map.put("foo", 1); @@ -69,12 +68,13 @@ public void decodesMapObjectNumericalValuesAsInteger() throws Exception { .headers(Collections.emptyMap()) .body("{\"foo\": 1}", UTF_8) .build(); - assertEquals( - new GsonDecoder().decode(response, new TypeToken>() {}.getType()), map); + assertThat(map) + .isEqualTo( + new GsonDecoder().decode(response, new TypeToken>() {}.getType())); } @Test - public void encodesFormParams() { + void encodesFormParams() { Map form = new LinkedHashMap<>(); form.put("foo", 1); @@ -116,9 +116,9 @@ static class Zone extends LinkedHashMap { } @Test - public void decodes() throws Exception { + void decodes() throws Exception { - List zones = new LinkedList(); + List zones = new LinkedList<>(); zones.add(new Zone("denominator.io.")); zones.add(new Zone("denominator.io.", "ABCD")); @@ -131,12 +131,12 @@ public void decodes() throws Exception { Request.create(HttpMethod.GET, "/api", Collections.emptyMap(), null, Util.UTF_8)) .body(zonesJson, UTF_8) .build(); - assertEquals( - zones, new GsonDecoder().decode(response, new TypeToken>() {}.getType())); + assertThat(new GsonDecoder().decode(response, new TypeToken>() {}.getType())) + .isEqualTo(zones); } @Test - public void nullBodyDecodesToNull() throws Exception { + void nullBodyDecodesToNull() throws Exception { Response response = Response.builder() .status(204) @@ -145,11 +145,11 @@ public void nullBodyDecodesToNull() throws Exception { .request( Request.create(HttpMethod.GET, "/api", Collections.emptyMap(), null, Util.UTF_8)) .build(); - assertNull(new GsonDecoder().decode(response, String.class)); + assertThat(new GsonDecoder().decode(response, String.class)).isNull(); } @Test - public void emptyBodyDecodesToNull() throws Exception { + void emptyBodyDecodesToNull() throws Exception { Response response = Response.builder() .status(204) @@ -159,7 +159,7 @@ public void emptyBodyDecodesToNull() throws Exception { Request.create(HttpMethod.GET, "/api", Collections.emptyMap(), null, Util.UTF_8)) .body(new byte[0]) .build(); - assertNull(new GsonDecoder().decode(response, String.class)); + assertThat(new GsonDecoder().decode(response, String.class)).isNull(); } private String zonesJson = @@ -199,7 +199,7 @@ public Zone read(JsonReader in) throws IOException { }; @Test - public void customDecoder() throws Exception { + void customDecoder() throws Exception { GsonDecoder decoder = new GsonDecoder(Collections.singletonList(upperZone)); List zones = new LinkedList<>(); @@ -215,11 +215,11 @@ public void customDecoder() throws Exception { Request.create(HttpMethod.GET, "/api", Collections.emptyMap(), null, Util.UTF_8)) .body(zonesJson, UTF_8) .build(); - assertEquals(zones, decoder.decode(response, new TypeToken>() {}.getType())); + assertThat(decoder.decode(response, new TypeToken>() {}.getType())).isEqualTo(zones); } @Test - public void customEncoder() { + void customEncoder() { GsonEncoder encoder = new GsonEncoder(Collections.singletonList(upperZone)); List zones = new LinkedList<>(); @@ -245,7 +245,7 @@ public void customEncoder() { /** Enabled via {@link feign.Feign.Builder#dismiss404()} */ @Test - public void notFoundDecodesToEmpty() throws Exception { + void notFoundDecodesToEmpty() throws Exception { Response response = Response.builder() .status(404) diff --git a/hc5/pom.xml b/hc5/pom.xml index ca148fdd4..fffc91680 100644 --- a/hc5/pom.xml +++ b/hc5/pom.xml @@ -64,7 +64,7 @@ com.squareup.okhttp3 - mockwebserver + mockwebserver3-junit5 test diff --git a/hc5/src/test/java/feign/hc5/ApacheHttp5ClientTest.java b/hc5/src/test/java/feign/hc5/ApacheHttp5ClientTest.java index b412c2a69..44d7816ce 100644 --- a/hc5/src/test/java/feign/hc5/ApacheHttp5ClientTest.java +++ b/hc5/src/test/java/feign/hc5/ApacheHttp5ClientTest.java @@ -14,10 +14,9 @@ package feign.hc5; import static java.util.concurrent.TimeUnit.SECONDS; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThrows; -import static org.junit.Assume.assumeTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assumptions.assumeTrue; import feign.Feign; import feign.Feign.Builder; @@ -30,10 +29,10 @@ import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.RecordedRequest; +import mockwebserver3.MockResponse; +import mockwebserver3.RecordedRequest; import org.apache.hc.client5.http.impl.classic.HttpClientBuilder; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests client-specific behavior, such as ensuring Content-Length is sent when specified. */ public class ApacheHttp5ClientTest extends AbstractClientTest { @@ -44,25 +43,25 @@ public Builder newBuilder() { } @Test - public void queryParamsAreRespectedWhenBodyIsEmpty() throws InterruptedException { + void queryParamsAreRespectedWhenBodyIsEmpty() throws InterruptedException { final JaxRsTestInterface testInterface = buildTestInterface(); server.enqueue(new MockResponse().setBody("foo")); server.enqueue(new MockResponse().setBody("foo")); - assertEquals("foo", testInterface.withBody("foo", "bar")); + assertThat(testInterface.withBody("foo", "bar")).isEqualTo("foo"); final RecordedRequest request1 = server.takeRequest(); - assertEquals("/withBody?foo=foo", request1.getPath()); - assertEquals("bar", request1.getBody().readString(StandardCharsets.UTF_8)); + assertThat(request1.getPath()).isEqualTo("/withBody?foo=foo"); + assertThat(request1.getBody().readString(StandardCharsets.UTF_8)).isEqualTo("bar"); - assertEquals("foo", testInterface.withoutBody("foo")); + assertThat(testInterface.withoutBody("foo")).isEqualTo("foo"); final RecordedRequest request2 = server.takeRequest(); - assertEquals("/withoutBody?foo=foo", request2.getPath()); - assertEquals("", request2.getBody().readString(StandardCharsets.UTF_8)); + assertThat(request2.getPath()).isEqualTo("/withoutBody?foo=foo"); + assertThat(request2.getBody().readString(StandardCharsets.UTF_8)).isEqualTo(""); } @Test - public void followRedirectsIsTrue() throws InterruptedException { + void followRedirectsIsTrue() throws InterruptedException { final JaxRsTestInterface testInterface = buildTestInterface(); String redirectPath = getRedirectionUrl(); @@ -71,13 +70,13 @@ public void followRedirectsIsTrue() throws InterruptedException { Request.Options options = buildRequestOptions(true); Object response = testInterface.withOptions(options); - assertNotNull(response); - assertEquals("redirected", response); - assertEquals("/withRequestOptions", server.takeRequest().getPath()); + assertThat(response).isNotNull(); + assertThat(response).isEqualTo("redirected"); + assertThat(server.takeRequest().getPath()).isEqualTo("/withRequestOptions"); } @Test - public void followRedirectsIsFalse() throws InterruptedException { + void followRedirectsIsFalse() throws InterruptedException { final JaxRsTestInterface testInterface = buildTestInterface(); String redirectPath = getRedirectionUrl(); @@ -86,11 +85,10 @@ public void followRedirectsIsFalse() throws InterruptedException { FeignException feignException = assertThrows(FeignException.class, () -> testInterface.withOptions(options)); - assertEquals(302, feignException.status()); - assertEquals( - redirectPath, - feignException.responseHeaders().get("location").stream().findFirst().orElse(null)); - assertEquals("/withRequestOptions", server.takeRequest().getPath()); + assertThat(feignException.status()).isEqualTo(302); + assertThat(feignException.responseHeaders().get("location").stream().findFirst().orElse(null)) + .isEqualTo(redirectPath); + assertThat(server.takeRequest().getPath()).isEqualTo("/withRequestOptions"); } private JaxRsTestInterface buildTestInterface() { @@ -113,13 +111,13 @@ private Request.Options buildRequestOptions(boolean followRedirects) { } @Override - public void testVeryLongResponseNullLength() { - assumeTrue("HC5 client seems to hang with response size equalto Long.MAX", false); + public void veryLongResponseNullLength() { + assumeTrue(false, "HC5 client seems to hang with response size equalto Long.MAX"); } @Override - public void testContentTypeDefaultsToRequestCharset() throws Exception { - assumeTrue("this test is flaky on windows, but works fine.", false); + public void contentTypeDefaultsToRequestCharset() throws Exception { + assumeTrue(false, "this test is flaky on windows, but works fine."); } @Path("/") diff --git a/hc5/src/test/java/feign/hc5/AsyncApacheHttp5ClientTest.java b/hc5/src/test/java/feign/hc5/AsyncApacheHttp5ClientTest.java index 9d2db7cc4..f147a9ab9 100644 --- a/hc5/src/test/java/feign/hc5/AsyncApacheHttp5ClientTest.java +++ b/hc5/src/test/java/feign/hc5/AsyncApacheHttp5ClientTest.java @@ -15,20 +15,43 @@ import static feign.assertj.MockWebServerAssertions.assertThat; import static java.util.concurrent.TimeUnit.SECONDS; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; import static org.assertj.core.data.MapEntry.entry; -import static org.hamcrest.CoreMatchers.isA; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertThrows; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; -import feign.*; +import feign.AsyncClient; +import feign.AsyncFeign; +import feign.Body; +import feign.ChildPojo; +import feign.Feign; import feign.Feign.ResponseMappingDecoder; +import feign.FeignException; +import feign.HeaderMap; +import feign.Headers; +import feign.Param; +import feign.PropertyPojo; +import feign.QueryMap; +import feign.QueryMapEncoder; +import feign.Request; import feign.Request.HttpMethod; +import feign.RequestInterceptor; +import feign.RequestLine; +import feign.RequestTemplate; +import feign.Response; +import feign.ResponseMapper; +import feign.Target; import feign.Target.HardCodedTarget; -import feign.codec.*; +import feign.Util; +import feign.codec.DecodeException; +import feign.codec.Decoder; +import feign.codec.EncodeException; +import feign.codec.Encoder; +import feign.codec.ErrorDecoder; +import feign.codec.StringDecoder; import feign.querymap.BeanQueryMapEncoder; import feign.querymap.FieldQueryMapEncoder; import java.io.IOException; @@ -37,24 +60,33 @@ import java.time.Clock; import java.time.Instant; import java.time.ZoneId; -import java.util.*; -import java.util.concurrent.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.MockWebServer; +import mockwebserver3.MockResponse; +import mockwebserver3.MockWebServer; import okio.Buffer; import org.apache.hc.client5.http.protocol.HttpClientContext; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; public class AsyncApacheHttp5ClientTest { - - @Rule public final ExpectedException thrown = ExpectedException.none(); - @Rule public final MockWebServer server = new MockWebServer(); + public final MockWebServer server = new MockWebServer(); @Test - public void iterableQueryParams() throws Exception { + void iterableQueryParams() throws Exception { server.enqueue(new MockResponse().setBody("foo")); final TestInterfaceAsync api = @@ -66,7 +98,7 @@ public void iterableQueryParams() throws Exception { } @Test - public void postTemplateParamsResolve() throws Exception { + void postTemplateParamsResolve() throws Exception { server.enqueue(new MockResponse().setBody("foo")); final TestInterfaceAsync api = @@ -81,7 +113,7 @@ public void postTemplateParamsResolve() throws Exception { } @Test - public void postFormParams() throws Exception { + void postFormParams() throws Exception { server.enqueue(new MockResponse().setBody("foo")); final TestInterfaceAsync api = @@ -97,7 +129,7 @@ public void postFormParams() throws Exception { } @Test - public void postBodyParam() throws Exception { + void postBodyParam() throws Exception { server.enqueue(new MockResponse().setBody("foo")); final TestInterfaceAsync api = @@ -117,10 +149,10 @@ public void postBodyParam() throws Exception { * type. */ @Test - public void bodyTypeCorrespondsWithParameterType() throws Exception { + void bodyTypeCorrespondsWithParameterType() throws Exception { server.enqueue(new MockResponse().setBody("foo")); - final AtomicReference encodedType = new AtomicReference(); + final AtomicReference encodedType = new AtomicReference<>(); final TestInterfaceAsync api = new TestInterfaceAsyncBuilder() .encoder( @@ -142,7 +174,7 @@ public void encode(Object object, Type bodyType, RequestTemplate template) { } @Test - public void singleInterceptor() throws Exception { + void singleInterceptor() throws Exception { server.enqueue(new MockResponse().setBody("foo")); final TestInterfaceAsync api = @@ -159,7 +191,7 @@ public void singleInterceptor() throws Exception { } @Test - public void multipleInterceptor() throws Exception { + void multipleInterceptor() throws Exception { server.enqueue(new MockResponse().setBody("foo")); final TestInterfaceAsync api = @@ -179,7 +211,7 @@ public void multipleInterceptor() throws Exception { } @Test - public void customExpander() throws Exception { + void customExpander() throws Exception { server.enqueue(new MockResponse()); final TestInterfaceAsync api = @@ -193,7 +225,7 @@ public void customExpander() throws Exception { } @Test - public void customExpanderListParam() throws Exception { + void customExpanderListParam() throws Exception { server.enqueue(new MockResponse()); final TestInterfaceAsync api = @@ -208,7 +240,7 @@ public void customExpanderListParam() throws Exception { } @Test - public void customExpanderNullParam() throws Exception { + void customExpanderNullParam() throws Exception { server.enqueue(new MockResponse()); final TestInterfaceAsync api = @@ -222,13 +254,13 @@ public void customExpanderNullParam() throws Exception { } @Test - public void headerMap() throws Exception { + void headerMap() throws Exception { server.enqueue(new MockResponse()); final TestInterfaceAsync api = new TestInterfaceAsyncBuilder().target("http://localhost:" + server.getPort()); - final Map headerMap = new LinkedHashMap(); + final Map headerMap = new LinkedHashMap<>(); headerMap.put("Content-Type", "myContent"); headerMap.put("Custom-Header", "fooValue"); final CompletableFuture cf = api.headerMap(headerMap); @@ -242,13 +274,13 @@ public void headerMap() throws Exception { } @Test - public void headerMapWithHeaderAnnotations() throws Exception { + void headerMapWithHeaderAnnotations() throws Exception { server.enqueue(new MockResponse()); final TestInterfaceAsync api = new TestInterfaceAsyncBuilder().target("http://localhost:" + server.getPort()); - final Map headerMap = new LinkedHashMap(); + final Map headerMap = new LinkedHashMap<>(); headerMap.put("Custom-Header", "fooValue"); api.headerMapWithHeaderAnnotations(headerMap); @@ -276,13 +308,13 @@ public void headerMapWithHeaderAnnotations() throws Exception { } @Test - public void queryMap() throws Exception { + void queryMap() throws Exception { server.enqueue(new MockResponse()); final TestInterfaceAsync api = new TestInterfaceAsyncBuilder().target("http://localhost:" + server.getPort()); - final Map queryMap = new LinkedHashMap(); + final Map queryMap = new LinkedHashMap<>(); queryMap.put("name", "alice"); queryMap.put("fooKey", "fooValue"); final CompletableFuture cf = api.queryMap(queryMap); @@ -293,16 +325,16 @@ public void queryMap() throws Exception { } @Test - public void queryMapIterableValuesExpanded() throws Exception { + void queryMapIterableValuesExpanded() throws Exception { server.enqueue(new MockResponse()); final TestInterfaceAsync api = new TestInterfaceAsyncBuilder().target("http://localhost:" + server.getPort()); - final Map queryMap = new LinkedHashMap(); + final Map queryMap = new LinkedHashMap<>(); queryMap.put("name", Arrays.asList("Alice", "Bob")); queryMap.put("fooKey", "fooValue"); - queryMap.put("emptyListKey", new ArrayList()); + queryMap.put("emptyListKey", new ArrayList<>()); queryMap.put("emptyStringKey", ""); // empty values are ignored. final CompletableFuture cf = api.queryMap(queryMap); @@ -313,26 +345,26 @@ public void queryMapIterableValuesExpanded() throws Exception { } @Test - public void queryMapWithQueryParams() throws Exception { + void queryMapWithQueryParams() throws Exception { final TestInterfaceAsync api = new TestInterfaceAsyncBuilder().target("http://localhost:" + server.getPort()); server.enqueue(new MockResponse()); - Map queryMap = new LinkedHashMap(); + Map queryMap = new LinkedHashMap<>(); queryMap.put("fooKey", "fooValue"); api.queryMapWithQueryParams("alice", queryMap); // query map should be expanded after built-in parameters assertThat(server.takeRequest()).hasPath("/?name=alice&fooKey=fooValue"); server.enqueue(new MockResponse()); - queryMap = new LinkedHashMap(); + queryMap = new LinkedHashMap<>(); queryMap.put("name", "bob"); api.queryMapWithQueryParams("alice", queryMap); // queries are additive assertThat(server.takeRequest()).hasPath("/?name=alice&name=bob"); server.enqueue(new MockResponse()); - queryMap = new LinkedHashMap(); + queryMap = new LinkedHashMap<>(); queryMap.put("name", null); api.queryMapWithQueryParams("alice", queryMap); // null value for a query map key removes query parameter @@ -340,37 +372,37 @@ public void queryMapWithQueryParams() throws Exception { } @Test - public void queryMapValueStartingWithBrace() throws Exception { + void queryMapValueStartingWithBrace() throws Exception { final TestInterfaceAsync api = new TestInterfaceAsyncBuilder().target("http://localhost:" + server.getPort()); server.enqueue(new MockResponse()); - Map queryMap = new LinkedHashMap(); + Map queryMap = new LinkedHashMap<>(); queryMap.put("name", "{alice"); api.queryMap(queryMap); assertThat(server.takeRequest()).hasPath("/?name=%7Balice"); server.enqueue(new MockResponse()); - queryMap = new LinkedHashMap(); + queryMap = new LinkedHashMap<>(); queryMap.put("{name", "alice"); api.queryMap(queryMap); assertThat(server.takeRequest()).hasPath("/?%7Bname=alice"); server.enqueue(new MockResponse()); - queryMap = new LinkedHashMap(); + queryMap = new LinkedHashMap<>(); queryMap.put("name", "%7Balice"); api.queryMapEncoded(queryMap); assertThat(server.takeRequest()).hasPath("/?name=%7Balice"); server.enqueue(new MockResponse()); - queryMap = new LinkedHashMap(); + queryMap = new LinkedHashMap<>(); queryMap.put("%7Bname", "%7Balice"); api.queryMapEncoded(queryMap); assertThat(server.takeRequest()).hasPath("/?%7Bname=%7Balice"); } @Test - public void queryMapPojoWithFullParams() throws Exception { + void queryMapPojoWithFullParams() throws Exception { final TestInterfaceAsync api = new TestInterfaceAsyncBuilder().target("http://localhost:" + server.getPort()); @@ -383,7 +415,7 @@ public void queryMapPojoWithFullParams() throws Exception { } @Test - public void queryMapPojoWithPartialParams() throws Exception { + void queryMapPojoWithPartialParams() throws Exception { final TestInterfaceAsync api = new TestInterfaceAsyncBuilder().target("http://localhost:" + server.getPort()); @@ -397,7 +429,7 @@ public void queryMapPojoWithPartialParams() throws Exception { } @Test - public void queryMapPojoWithEmptyParams() throws Exception { + void queryMapPojoWithEmptyParams() throws Exception { final TestInterfaceAsync api = new TestInterfaceAsyncBuilder().target("http://localhost:" + server.getPort()); @@ -409,24 +441,23 @@ public void queryMapPojoWithEmptyParams() throws Exception { } @Test - public void configKeyFormatsAsExpected() throws Exception { - assertEquals( - "TestInterfaceAsync#post()", - Feign.configKey( - TestInterfaceAsync.class, TestInterfaceAsync.class.getDeclaredMethod("post"))); - assertEquals( - "TestInterfaceAsync#uriParam(String,URI,String)", - Feign.configKey( - TestInterfaceAsync.class, - TestInterfaceAsync.class.getDeclaredMethod( - "uriParam", String.class, URI.class, String.class))); + void configKeyFormatsAsExpected() throws Exception { + assertThat( + Feign.configKey( + TestInterfaceAsync.class, TestInterfaceAsync.class.getDeclaredMethod("post"))) + .isEqualTo("TestInterfaceAsync#post()"); + assertThat( + Feign.configKey( + TestInterfaceAsync.class, + TestInterfaceAsync.class.getDeclaredMethod( + "uriParam", String.class, URI.class, String.class))) + .isEqualTo("TestInterfaceAsync#uriParam(String,URI,String)"); } @Test - public void configKeyUsesChildType() throws Exception { - assertEquals( - "List#iterator()", - Feign.configKey(List.class, Iterable.class.getDeclaredMethod("iterator"))); + void configKeyUsesChildType() throws Exception { + assertThat(Feign.configKey(List.class, Iterable.class.getDeclaredMethod("iterator"))) + .isEqualTo("List#iterator()"); } private T unwrap(CompletableFuture cf) throws Throwable { @@ -438,21 +469,20 @@ private T unwrap(CompletableFuture cf) throws Throwable { } @Test - public void canOverrideErrorDecoder() throws Throwable { + void canOverrideErrorDecoder() throws Throwable { server.enqueue(new MockResponse().setResponseCode(400).setBody("foo")); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("bad zone name"); final TestInterfaceAsync api = new TestInterfaceAsyncBuilder() .errorDecoder(new IllegalArgumentExceptionOn400()) .target("http://localhost:" + server.getPort()); - unwrap(api.post()); + Throwable exception = assertThrows(IllegalArgumentException.class, () -> unwrap(api.post())); + assertThat(exception.getMessage()).contains("bad zone name"); } @Test - public void overrideTypeSpecificDecoder() throws Throwable { + void overrideTypeSpecificDecoder() throws Throwable { server.enqueue(new MockResponse().setBody("success!")); final TestInterfaceAsync api = @@ -460,14 +490,12 @@ public void overrideTypeSpecificDecoder() throws Throwable { .decoder((response, type) -> "fail") .target("http://localhost:" + server.getPort()); - assertEquals("fail", unwrap(api.post())); + assertThat(unwrap(api.post())).isEqualTo("fail"); } @Test - public void doesntRetryAfterResponseIsSent() throws Throwable { + void doesntRetryAfterResponseIsSent() throws Throwable { server.enqueue(new MockResponse().setBody("success!")); - thrown.expect(FeignException.class); - thrown.expectMessage("timeout reading POST http://"); final TestInterfaceAsync api = new TestInterfaceAsyncBuilder() @@ -479,11 +507,12 @@ public void doesntRetryAfterResponseIsSent() throws Throwable { final CompletableFuture cf = api.post(); server.takeRequest(); - unwrap(cf); + Throwable exception = assertThrows(FeignException.class, () -> unwrap(cf)); + assertThat(exception.getMessage()).contains("timeout reading POST http://"); } @Test - public void throwsFeignExceptionIncludingBody() throws Throwable { + void throwsFeignExceptionIncludingBody() throws Throwable { server.enqueue(new MockResponse().setBody("success!")); final TestInterfaceAsync api = @@ -504,11 +533,11 @@ public void throwsFeignExceptionIncludingBody() throws Throwable { assertThat(e.contentUTF8()).isEqualTo("Request body"); return; } - fail(); + fail(""); } @Test - public void throwsFeignExceptionWithoutBody() { + void throwsFeignExceptionWithoutBody() { server.enqueue(new MockResponse().setBody("success!")); final TestInterfaceAsync api = @@ -530,8 +559,8 @@ public void throwsFeignExceptionWithoutBody() { @SuppressWarnings("deprecation") @Test - public void whenReturnTypeIsResponseNoErrorHandling() throws Throwable { - final Map> headers = new LinkedHashMap>(); + void whenReturnTypeIsResponseNoErrorHandling() throws Throwable { + final Map> headers = new LinkedHashMap<>(); headers.put("Location", Arrays.asList("http://bar.com")); final Response response = Response.builder() @@ -561,9 +590,8 @@ public void whenReturnTypeIsResponseNoErrorHandling() throws Throwable { } @Test - public void okIfDecodeRootCauseHasNoMessage() throws Throwable { + void okIfDecodeRootCauseHasNoMessage() throws Throwable { server.enqueue(new MockResponse().setBody("success!")); - thrown.expect(DecodeException.class); final TestInterfaceAsync api = new TestInterfaceAsyncBuilder() @@ -573,48 +601,50 @@ public void okIfDecodeRootCauseHasNoMessage() throws Throwable { }) .target("http://localhost:" + server.getPort()); - unwrap(api.post()); + assertThrows(DecodeException.class, () -> unwrap(api.post())); } @Test - public void decodingExceptionGetWrappedInDismiss404Mode() throws Throwable { + void decodingExceptionGetWrappedInDismiss404Mode() throws Throwable { server.enqueue(new MockResponse().setResponseCode(404)); - thrown.expect(DecodeException.class); - thrown.expectCause(isA(NoSuchElementException.class)); final TestInterfaceAsync api = new TestInterfaceAsyncBuilder() .dismiss404() .decoder( (response, type) -> { - assertEquals(404, response.status()); + assertThat(response.status()).isEqualTo(404); throw new NoSuchElementException(); }) .target("http://localhost:" + server.getPort()); - unwrap(api.post()); + DecodeException exception = assertThrows(DecodeException.class, () -> unwrap(api.post())); + assertThat(exception).hasCauseInstanceOf(NoSuchElementException.class); } @Test - public void decodingDoesNotSwallow404ErrorsInDismiss404Mode() throws Throwable { - server.enqueue(new MockResponse().setResponseCode(404)); - thrown.expect(IllegalArgumentException.class); - - final TestInterfaceAsync api = - new TestInterfaceAsyncBuilder() - .dismiss404() - .errorDecoder(new IllegalArgumentExceptionOn404()) - .target("http://localhost:" + server.getPort()); - - final CompletableFuture cf = api.queryMap(Collections.emptyMap()); - server.takeRequest(); - unwrap(cf); + void decodingDoesNotSwallow404ErrorsInDismiss404Mode() throws Throwable { + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy( + () -> { + server.enqueue(new MockResponse().setResponseCode(404)); + + final TestInterfaceAsync api = + new TestInterfaceAsyncBuilder() + .dismiss404() + .errorDecoder(new IllegalArgumentExceptionOn404()) + .target("http://localhost:" + server.getPort()); + + final CompletableFuture cf = + api.queryMap(Collections.emptyMap()); + server.takeRequest(); + unwrap(cf); + }); } @Test - public void okIfEncodeRootCauseHasNoMessage() throws Throwable { + void okIfEncodeRootCauseHasNoMessage() throws Throwable { server.enqueue(new MockResponse().setBody("success!")); - thrown.expect(EncodeException.class); final TestInterfaceAsync api = new TestInterfaceAsyncBuilder() @@ -624,18 +654,17 @@ public void okIfEncodeRootCauseHasNoMessage() throws Throwable { }) .target("http://localhost:" + server.getPort()); - unwrap(api.body(Arrays.asList("foo"))); + assertThrows(EncodeException.class, () -> unwrap(api.body(Arrays.asList("foo")))); } @Test - public void equalsHashCodeAndToStringWork() { + void equalsHashCodeAndToStringWork() { final Target t1 = - new HardCodedTarget(TestInterfaceAsync.class, "http://localhost:8080"); + new HardCodedTarget<>(TestInterfaceAsync.class, "http://localhost:8080"); final Target t2 = - new HardCodedTarget(TestInterfaceAsync.class, "http://localhost:8888"); + new HardCodedTarget<>(TestInterfaceAsync.class, "http://localhost:8888"); final Target t3 = - new HardCodedTarget( - OtherTestInterfaceAsync.class, "http://localhost:8080"); + new HardCodedTarget<>(OtherTestInterfaceAsync.class, "http://localhost:8080"); final TestInterfaceAsync i1 = AsyncFeign.builder().target(t1); final TestInterfaceAsync i2 = AsyncFeign.builder().target(t1); final TestInterfaceAsync i3 = AsyncFeign.builder().target(t2); @@ -662,7 +691,7 @@ public void equalsHashCodeAndToStringWork() { @SuppressWarnings("resource") @Test - public void decodeLogicSupportsByteArray() throws Throwable { + void decodeLogicSupportsByteArray() throws Throwable { final byte[] expectedResponse = {12, 34, 56}; server.enqueue(new MockResponse().setBody(new Buffer().write(expectedResponse))); @@ -674,7 +703,7 @@ public void decodeLogicSupportsByteArray() throws Throwable { } @Test - public void encodeLogicSupportsByteArray() throws Exception { + void encodeLogicSupportsByteArray() throws Exception { final byte[] expectedRequest = {12, 34, 56}; server.enqueue(new MockResponse()); @@ -690,7 +719,7 @@ public void encodeLogicSupportsByteArray() throws Exception { } @Test - public void encodedQueryParam() throws Exception { + void encodedQueryParam() throws Exception { server.enqueue(new MockResponse()); final TestInterfaceAsync api = @@ -714,7 +743,7 @@ private void checkCFCompletedSoon(CompletableFuture cf) { } @Test - public void responseMapperIsAppliedBeforeDelegate() throws IOException { + void responseMapperIsAppliedBeforeDelegate() throws IOException { final ResponseMappingDecoder decoder = new ResponseMappingDecoder(upperCaseResponseMapper(), new StringDecoder()); final String output = (String) decoder.decode(responseWithText("response"), String.class); @@ -723,17 +752,13 @@ public void responseMapperIsAppliedBeforeDelegate() throws IOException { } private ResponseMapper upperCaseResponseMapper() { - return new ResponseMapper() { - @SuppressWarnings("deprecation") - @Override - public Response map(Response response, Type type) { - try { - return response.toBuilder() - .body(Util.toString(response.body().asReader()).toUpperCase().getBytes()) - .build(); - } catch (final IOException e) { - throw new RuntimeException(e); - } + return (response, type) -> { + try { + return response.toBuilder() + .body(Util.toString(response.body().asReader()).toUpperCase().getBytes()) + .build(); + } catch (final IOException e) { + throw new RuntimeException(e); } }; } @@ -749,7 +774,7 @@ private Response responseWithText(String text) { } @Test - public void mapAndDecodeExecutesMapFunction() throws Throwable { + void mapAndDecodeExecutesMapFunction() throws Throwable { server.enqueue(new MockResponse().setBody("response!")); final TestInterfaceAsync api = @@ -757,11 +782,11 @@ public void mapAndDecodeExecutesMapFunction() throws Throwable { .mapAndDecode(upperCaseResponseMapper(), new StringDecoder()) .target(TestInterfaceAsync.class, "http://localhost:" + server.getPort()); - assertEquals("RESPONSE!", unwrap(api.post())); + assertThat(unwrap(api.post())).isEqualTo("RESPONSE!"); } @Test - public void beanQueryMapEncoderWithPrivateGetterIgnored() throws Exception { + void beanQueryMapEncoderWithPrivateGetterIgnored() throws Exception { final TestInterfaceAsync api = new TestInterfaceAsyncBuilder() .queryMapEndcoder(new BeanQueryMapEncoder()) @@ -779,7 +804,7 @@ public void beanQueryMapEncoderWithPrivateGetterIgnored() throws Exception { } @Test - public void queryMap_with_child_pojo() throws Exception { + void queryMap_with_child_pojo() throws Exception { final TestInterfaceAsync api = new TestInterfaceAsyncBuilder() .queryMapEndcoder(new FieldQueryMapEncoder()) @@ -801,7 +826,7 @@ public void queryMap_with_child_pojo() throws Exception { } @Test - public void beanQueryMapEncoderWithNullValueIgnored() throws Exception { + void beanQueryMapEncoderWithNullValueIgnored() throws Exception { final TestInterfaceAsync api = new TestInterfaceAsyncBuilder() .queryMapEndcoder(new BeanQueryMapEncoder()) @@ -820,7 +845,7 @@ public void beanQueryMapEncoderWithNullValueIgnored() throws Exception { } @Test - public void beanQueryMapEncoderWithEmptyParams() throws Exception { + void beanQueryMapEncoderWithEmptyParams() throws Exception { final TestInterfaceAsync api = new TestInterfaceAsyncBuilder() .queryMapEndcoder(new BeanQueryMapEncoder()) @@ -836,7 +861,7 @@ public void beanQueryMapEncoderWithEmptyParams() throws Exception { } @Test - public void followRedirectsIsTrue() throws Throwable { + void followRedirectsIsTrue() throws Throwable { String redirectPath = "/redirected"; @@ -850,15 +875,15 @@ public void followRedirectsIsTrue() throws Throwable { .target("http://localhost:" + server.getPort()); Response response = unwrap(api.response()); - assertNotNull(response); - assertEquals(200, response.status()); - assertEquals("redirectedBody", Util.toString(response.body().asReader(Util.UTF_8))); - assertEquals("/", server.takeRequest().getPath()); - assertEquals("/redirected", server.takeRequest().getPath()); + assertThat(response).isNotNull(); + assertThat(response.status()).isEqualTo(200); + assertThat(Util.toString(response.body().asReader(Util.UTF_8))).isEqualTo("redirectedBody"); + assertThat(server.takeRequest().getPath()).isEqualTo("/"); + assertThat(server.takeRequest().getPath()).isEqualTo("/redirected"); } @Test - public void followRedirectsIsFalse() throws Throwable { + void followRedirectsIsFalse() throws Throwable { String redirectPath = "/redirected"; server.enqueue(buildMockResponseWithLocationHeader(redirectPath)); @@ -871,11 +896,11 @@ public void followRedirectsIsFalse() throws Throwable { Response response = unwrap(api.response()); final String path = response.headers().get("location").stream().findFirst().orElse(null); - assertNotNull(response); - assertNotNull(path); - assertEquals(302, response.status()); - assertEquals("/", server.takeRequest().getPath()); - assertTrue(path.contains("/redirected")); + assertThat(response).isNotNull(); + assertThat(path).isNotNull(); + assertThat(response.status()).isEqualTo(302); + assertThat(server.takeRequest().getPath()).isEqualTo("/"); + assertThat(path).contains("/redirected"); } private MockResponse buildMockResponseWithLocationHeader(String redirectPath) { @@ -1052,16 +1077,11 @@ static final class TestInterfaceAsyncBuilder { .client(new AsyncApacheHttp5Client()) .decoder(new Decoder.Default()) .encoder( - new Encoder() { - - @SuppressWarnings("deprecation") - @Override - public void encode(Object object, Type bodyType, RequestTemplate template) { - if (object instanceof Map) { - template.body(new Gson().toJson(object)); - } else { - template.body(object.toString()); - } + (object, bodyType, template) -> { + if (object instanceof Map) { + template.body(new Gson().toJson(object)); + } else { + template.body(object.toString()); } }); @@ -1160,4 +1180,9 @@ public Instant instant() { return Instant.ofEpochMilli(millis); } } + + @AfterEach + void afterEachTest() throws IOException { + server.close(); + } } diff --git a/hc5/src/test/java/feign/hc5/GzipHttp5ClientTest.java b/hc5/src/test/java/feign/hc5/GzipHttp5ClientTest.java index 79994988d..1f7cf2bdc 100644 --- a/hc5/src/test/java/feign/hc5/GzipHttp5ClientTest.java +++ b/hc5/src/test/java/feign/hc5/GzipHttp5ClientTest.java @@ -1,90 +1,90 @@ -/* - * Copyright 2012-2023 The Feign Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package feign.hc5; - -import static org.junit.Assume.assumeTrue; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import feign.Feign; -import feign.Feign.Builder; -import feign.RequestLine; -import feign.client.AbstractClientTest; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.zip.GZIPInputStream; -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.RecordedRequest; -import org.junit.jupiter.api.Test; - -/** Tests that 'Content-Encoding: gzip' is handled correctly */ -public class GzipHttp5ClientTest extends AbstractClientTest { - - @Override - public Builder newBuilder() { - return Feign.builder().client(new ApacheHttp5Client()); - } - - @Test - public void testWithCompressedBody() throws InterruptedException, IOException { - final TestInterface testInterface = buildTestInterface(true); - - server.enqueue(new MockResponse().setBody("foo")); - - assertEquals("foo", testInterface.withBody("bar")); - final RecordedRequest request1 = server.takeRequest(); - assertEquals("/test", request1.getPath()); - - ByteArrayInputStream bodyContentIs = - new ByteArrayInputStream(request1.getBody().readByteArray()); - byte[] uncompressed = new GZIPInputStream(bodyContentIs).readAllBytes(); - - assertEquals("bar", new String(uncompressed, StandardCharsets.UTF_8)); - } - - @Test - public void testWithUncompressedBody() throws InterruptedException, IOException { - final TestInterface testInterface = buildTestInterface(false); - - server.enqueue(new MockResponse().setBody("foo")); - - assertEquals("foo", testInterface.withBody("bar")); - final RecordedRequest request1 = server.takeRequest(); - assertEquals("/test", request1.getPath()); - - assertEquals("bar", request1.getBody().readString(StandardCharsets.UTF_8)); - } - - private TestInterface buildTestInterface(boolean compress) { - return newBuilder() - .requestInterceptor(req -> req.header("Content-Encoding", compress ? "gzip" : "")) - .target(TestInterface.class, "http://localhost:" + server.getPort()); - } - - @Override - public void testVeryLongResponseNullLength() { - assumeTrue("HC5 client seems to hang with response size equalto Long.MAX", false); - } - - @Override - public void testContentTypeDefaultsToRequestCharset() throws Exception { - assumeTrue("this test is flaky on windows, but works fine.", false); - } - - public interface TestInterface { - - @RequestLine("POST /test") - String withBody(String body); - } -} +/* + * Copyright 2012-2023 The Feign Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package feign.hc5; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +import feign.Feign; +import feign.Feign.Builder; +import feign.RequestLine; +import feign.client.AbstractClientTest; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.zip.GZIPInputStream; +import mockwebserver3.MockResponse; +import mockwebserver3.RecordedRequest; +import org.junit.jupiter.api.Test; + +/** Tests that 'Content-Encoding: gzip' is handled correctly */ +public class GzipHttp5ClientTest extends AbstractClientTest { + + @Override + public Builder newBuilder() { + return Feign.builder().client(new ApacheHttp5Client()); + } + + @Test + public void testWithCompressedBody() throws InterruptedException, IOException { + final TestInterface testInterface = buildTestInterface(true); + + server.enqueue(new MockResponse().setBody("foo")); + + assertEquals("foo", testInterface.withBody("bar")); + final RecordedRequest request1 = server.takeRequest(); + assertEquals("/test", request1.getPath()); + + ByteArrayInputStream bodyContentIs = + new ByteArrayInputStream(request1.getBody().readByteArray()); + byte[] uncompressed = new GZIPInputStream(bodyContentIs).readAllBytes(); + + assertEquals("bar", new String(uncompressed, StandardCharsets.UTF_8)); + } + + @Test + public void testWithUncompressedBody() throws InterruptedException, IOException { + final TestInterface testInterface = buildTestInterface(false); + + server.enqueue(new MockResponse().setBody("foo")); + + assertEquals("foo", testInterface.withBody("bar")); + final RecordedRequest request1 = server.takeRequest(); + assertEquals("/test", request1.getPath()); + + assertEquals("bar", request1.getBody().readString(StandardCharsets.UTF_8)); + } + + private TestInterface buildTestInterface(boolean compress) { + return newBuilder() + .requestInterceptor(req -> req.header("Content-Encoding", compress ? "gzip" : "")) + .target(TestInterface.class, "http://localhost:" + server.getPort()); + } + + @Override + public void veryLongResponseNullLength() { + assumeTrue(true, "HC5 client seems to hang with response size equalto Long.MAX"); + } + + @Override + public void contentTypeDefaultsToRequestCharset() throws Exception { + assumeTrue(true, "this test is flaky on windows, but works fine."); + } + + public interface TestInterface { + + @RequestLine("POST /test") + String withBody(String body); + } +} diff --git a/httpclient/pom.xml b/httpclient/pom.xml index de3e24d2c..ac6f18a32 100644 --- a/httpclient/pom.xml +++ b/httpclient/pom.xml @@ -71,7 +71,7 @@ com.squareup.okhttp3 - mockwebserver + mockwebserver3-junit5 test diff --git a/httpclient/src/test/java/feign/httpclient/ApacheHttpClientTest.java b/httpclient/src/test/java/feign/httpclient/ApacheHttpClientTest.java index ca1f2d138..7f371652c 100644 --- a/httpclient/src/test/java/feign/httpclient/ApacheHttpClientTest.java +++ b/httpclient/src/test/java/feign/httpclient/ApacheHttpClientTest.java @@ -14,8 +14,8 @@ package feign.httpclient; import static java.util.concurrent.TimeUnit.SECONDS; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThrows; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; import feign.Feign; import feign.Feign.Builder; @@ -28,10 +28,10 @@ import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.RecordedRequest; +import mockwebserver3.MockResponse; +import mockwebserver3.RecordedRequest; import org.apache.http.impl.client.HttpClientBuilder; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests client-specific behavior, such as ensuring Content-Length is sent when specified. */ public class ApacheHttpClientTest extends AbstractClientTest { @@ -42,25 +42,25 @@ public Builder newBuilder() { } @Test - public void queryParamsAreRespectedWhenBodyIsEmpty() throws InterruptedException { + void queryParamsAreRespectedWhenBodyIsEmpty() throws InterruptedException { final JaxRsTestInterface testInterface = buildTestInterface(); server.enqueue(new MockResponse().setBody("foo")); server.enqueue(new MockResponse().setBody("foo")); - assertEquals("foo", testInterface.withBody("foo", "bar")); + assertThat(testInterface.withBody("foo", "bar")).isEqualTo("foo"); final RecordedRequest request1 = server.takeRequest(); - assertEquals("/withBody?foo=foo", request1.getPath()); - assertEquals("bar", request1.getBody().readString(StandardCharsets.UTF_8)); + assertThat(request1.getPath()).isEqualTo("/withBody?foo=foo"); + assertThat(request1.getBody().readString(StandardCharsets.UTF_8)).isEqualTo("bar"); - assertEquals("foo", testInterface.withoutBody("foo")); + assertThat(testInterface.withoutBody("foo")).isEqualTo("foo"); final RecordedRequest request2 = server.takeRequest(); - assertEquals("/withoutBody?foo=foo", request2.getPath()); - assertEquals("", request2.getBody().readString(StandardCharsets.UTF_8)); + assertThat(request2.getPath()).isEqualTo("/withoutBody?foo=foo"); + assertThat(request2.getBody().readString(StandardCharsets.UTF_8)).isEqualTo(""); } @Test - public void followRedirectIsRespected() throws InterruptedException { + void followRedirectIsRespected() throws InterruptedException { final JaxRsTestInterface testInterface = buildTestInterface(); String redirectPath = "/redirected"; @@ -68,13 +68,13 @@ public void followRedirectIsRespected() throws InterruptedException { server.enqueue(new MockResponse().setBody("redirect")); Options options = buildRequestOptions(true); - assertEquals("redirect", testInterface.withOptions(options)); - assertEquals("/withOptions", server.takeRequest().getPath()); - assertEquals(redirectPath, server.takeRequest().getPath()); + assertThat(testInterface.withOptions(options)).isEqualTo("redirect"); + assertThat(server.takeRequest().getPath()).isEqualTo("/withOptions"); + assertThat(server.takeRequest().getPath()).isEqualTo(redirectPath); } @Test - public void notFollowRedirectIsRespected() throws InterruptedException { + void notFollowRedirectIsRespected() throws InterruptedException { final JaxRsTestInterface testInterface = buildTestInterface(); String redirectPath = "/redirected"; @@ -83,8 +83,8 @@ public void notFollowRedirectIsRespected() throws InterruptedException { FeignException feignException = assertThrows(FeignException.class, () -> testInterface.withOptions(options)); - assertEquals(302, feignException.status()); - assertEquals("/withOptions", server.takeRequest().getPath()); + assertThat(feignException.status()).isEqualTo(302); + assertThat(server.takeRequest().getPath()).isEqualTo("/withOptions"); } private JaxRsTestInterface buildTestInterface() { diff --git a/hystrix/pom.xml b/hystrix/pom.xml index 94c0ed329..4fd12b236 100644 --- a/hystrix/pom.xml +++ b/hystrix/pom.xml @@ -75,7 +75,14 @@ com.squareup.okhttp3 - mockwebserver + mockwebserver3-junit5 + test + + + + org.slf4j + slf4j-api + ${slf4j.version} test diff --git a/hystrix/src/test/java/feign/hystrix/FallbackFactoryTest.java b/hystrix/src/test/java/feign/hystrix/FallbackFactoryTest.java index 8c78a3103..c2e18090a 100644 --- a/hystrix/src/test/java/feign/hystrix/FallbackFactoryTest.java +++ b/hystrix/src/test/java/feign/hystrix/FallbackFactoryTest.java @@ -13,18 +13,18 @@ */ package feign.hystrix; -import static feign.assertj.MockWebServerAssertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import feign.FeignException; import feign.RequestLine; +import java.io.IOException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Level; import java.util.logging.Logger; -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.MockWebServer; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import mockwebserver3.MockResponse; +import mockwebserver3.MockWebServer; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; public class FallbackFactoryTest { @@ -33,11 +33,10 @@ interface TestInterface { String invoke(); } - @Rule public final ExpectedException thrown = ExpectedException.none(); - @Rule public final MockWebServer server = new MockWebServer(); + public final MockWebServer server = new MockWebServer(); @Test - public void fallbackFactory_example_lambda() { + void fallbackFactory_example_lambda() { server.enqueue(new MockResponse().setResponseCode(500)); server.enqueue(new MockResponse().setResponseCode(404)); @@ -67,7 +66,7 @@ public String invoke() { } @Test - public void fallbackFactory_example_ctor() { + void fallbackFactory_example_ctor() { server.enqueue(new MockResponse().setResponseCode(500)); // method reference @@ -78,19 +77,12 @@ public void fallbackFactory_example_ctor() { server.enqueue(new MockResponse().setResponseCode(500)); // lambda factory - api = target(throwable -> new FallbackApiWithCtor(throwable)); + api = target(FallbackApiWithCtor::new); server.enqueue(new MockResponse().setResponseCode(500)); // old school - api = - target( - new FallbackFactory() { - @Override - public TestInterface create(Throwable cause) { - return new FallbackApiWithCtor(cause); - } - }); + api = target(FallbackApiWithCtor::new); assertThat(api.invoke()).isEqualTo("foo"); } @@ -120,7 +112,7 @@ public String invoke() { } @Test - public void fallbackFactory_example_retro() { + void fallbackFactory_example_retro() { server.enqueue(new MockResponse().setResponseCode(500)); TestInterface api = target(new FallbackApiRetro()); @@ -133,7 +125,7 @@ public void fallbackFactory_example_retro() { } @Test - public void defaultFallbackFactory_delegates() { + void defaultFallbackFactory_delegates() { server.enqueue(new MockResponse().setResponseCode(500)); TestInterface api = target(new FallbackFactory.Default<>(() -> "foo")); @@ -142,7 +134,7 @@ public void defaultFallbackFactory_delegates() { } @Test - public void defaultFallbackFactory_doesntLogByDefault() { + void defaultFallbackFactory_doesntLogByDefault() { server.enqueue(new MockResponse().setResponseCode(500)); Logger logger = @@ -157,7 +149,7 @@ public void log(Level level, String msg, Throwable thrown) { } @Test - public void defaultFallbackFactory_logsAtFineLevel() { + void defaultFallbackFactory_logsAtFineLevel() { server.enqueue(new MockResponse().setResponseCode(500)); AtomicBoolean logged = new AtomicBoolean(); @@ -185,4 +177,9 @@ TestInterface target(FallbackFactory factory) { return HystrixFeign.builder() .target(TestInterface.class, "http://localhost:" + server.getPort(), factory); } + + @AfterEach + void afterEachTest() throws IOException { + server.close(); + } } diff --git a/hystrix/src/test/java/feign/hystrix/HystrixBuilderTest.java b/hystrix/src/test/java/feign/hystrix/HystrixBuilderTest.java index 7bc73a1ea..e2fd834e9 100644 --- a/hystrix/src/test/java/feign/hystrix/HystrixBuilderTest.java +++ b/hystrix/src/test/java/feign/hystrix/HystrixBuilderTest.java @@ -14,34 +14,41 @@ package feign.hystrix; import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.core.Is.isA; +import static org.junit.jupiter.api.Assertions.assertThrows; import com.netflix.hystrix.HystrixCommand; import com.netflix.hystrix.HystrixCommandGroupKey; import com.netflix.hystrix.exception.HystrixRuntimeException; -import feign.*; +import feign.FeignException; +import feign.Headers; +import feign.Param; +import feign.RequestLine; +import feign.Target; import feign.Target.HardCodedTarget; import feign.gson.GsonDecoder; -import java.util.*; -import java.util.concurrent.*; -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.MockWebServer; -import org.assertj.core.api.Assertions; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import mockwebserver3.MockResponse; +import mockwebserver3.MockWebServer; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import rx.Completable; import rx.Observable; import rx.Single; import rx.observers.TestSubscriber; public class HystrixBuilderTest { - - @Rule public final ExpectedException thrown = ExpectedException.none(); - @Rule public final MockWebServer server = new MockWebServer(); + public final MockWebServer server = new MockWebServer(); @Test - public void defaultMethodReturningHystrixCommand() { + void defaultMethodReturningHystrixCommand() { server.enqueue(new MockResponse().setBody("\"foo\"")); final TestInterface api = target(); @@ -53,7 +60,7 @@ public void defaultMethodReturningHystrixCommand() { } @Test - public void hystrixCommand() { + void hystrixCommand() { server.enqueue(new MockResponse().setBody("\"foo\"")); final TestInterface api = target(); @@ -65,7 +72,7 @@ public void hystrixCommand() { } @Test - public void hystrixCommandFallback() { + void hystrixCommandFallback() { server.enqueue(new MockResponse().setResponseCode(500)); final TestInterface api = target(); @@ -77,7 +84,7 @@ public void hystrixCommandFallback() { } @Test - public void hystrixCommandInt() { + void hystrixCommandInt() { server.enqueue(new MockResponse().setBody("1")); final TestInterface api = target(); @@ -89,7 +96,7 @@ public void hystrixCommandInt() { } @Test - public void hystrixCommandIntFallback() { + void hystrixCommandIntFallback() { server.enqueue(new MockResponse().setResponseCode(500)); final TestInterface api = target(); @@ -101,7 +108,7 @@ public void hystrixCommandIntFallback() { } @Test - public void hystrixCommandList() { + void hystrixCommandList() { server.enqueue(new MockResponse().setBody("[\"foo\",\"bar\"]")); final TestInterface api = target(); @@ -113,7 +120,7 @@ public void hystrixCommandList() { } @Test - public void hystrixCommandListFallback() { + void hystrixCommandListFallback() { server.enqueue(new MockResponse().setResponseCode(500)); final TestInterface api = target(); @@ -137,7 +144,7 @@ HystrixCommand> contributorsHystrixCommand( } @Test - public void fallbacksApplyOnError() { + void fallbacksApplyOnError() { server.enqueue(new MockResponse().setResponseCode(500)); final GitHub fallback = @@ -157,12 +164,7 @@ public void fallbacksApplyOnError() { } @Test - public void errorInFallbackHasExpectedBehavior() { - thrown.expect(HystrixRuntimeException.class); - thrown.expectMessage("GitHub#contributors(String,String) failed and fallback failed."); - thrown.expectCause( - isA(FeignException.class)); // as opposed to RuntimeException (from the fallback) - + void errorInFallbackHasExpectedBehavior() { server.enqueue(new MockResponse().setResponseCode(500)); final GitHub fallback = @@ -172,7 +174,11 @@ public void errorInFallbackHasExpectedBehavior() { final GitHub api = target(GitHub.class, "http://localhost:" + server.getPort(), fallback); - api.contributors("Netflix", "feign"); + HystrixRuntimeException exception = + assertThrows(HystrixRuntimeException.class, () -> api.contributors("Netflix", "feign")); + assertThat(exception) + .hasCauseInstanceOf(FeignException.class) + .hasMessage("GitHub#contributors(String,String) failed and fallback failed."); } protected E target(Class api, String url) { @@ -188,20 +194,21 @@ protected E target(Class api, String url, E fallback) { } @Test - public void hystrixRuntimeExceptionPropagatesOnException() { - thrown.expect(HystrixRuntimeException.class); - thrown.expectMessage("GitHub#contributors(String,String) failed and no fallback available."); - thrown.expectCause(isA(FeignException.class)); + void hystrixRuntimeExceptionPropagatesOnException() { server.enqueue(new MockResponse().setResponseCode(500)); final GitHub api = target(GitHub.class, "http://localhost:" + server.getPort()); - api.contributors("Netflix", "feign"); + HystrixRuntimeException exception = + assertThrows(HystrixRuntimeException.class, () -> api.contributors("Netflix", "feign")); + assertThat(exception) + .hasCauseInstanceOf(FeignException.class) + .hasMessage("GitHub#contributors(String,String) failed and no fallback available."); } @Test - public void rxObservable() { + void rxObservable() { server.enqueue(new MockResponse().setBody("\"foo\"")); final TestInterface api = target(); @@ -211,14 +218,14 @@ public void rxObservable() { assertThat(observable).isNotNull(); assertThat(server.getRequestCount()).isEqualTo(0); - final TestSubscriber testSubscriber = new TestSubscriber(); + final TestSubscriber testSubscriber = new TestSubscriber<>(); observable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(); - Assertions.assertThat(testSubscriber.getOnNextEvents().get(0)).isEqualTo("foo"); + assertThat(testSubscriber.getOnNextEvents().get(0)).isEqualTo("foo"); } @Test - public void rxObservableFallback() { + void rxObservableFallback() { server.enqueue(new MockResponse().setResponseCode(500)); final TestInterface api = target(); @@ -228,14 +235,14 @@ public void rxObservableFallback() { assertThat(observable).isNotNull(); assertThat(server.getRequestCount()).isEqualTo(0); - final TestSubscriber testSubscriber = new TestSubscriber(); + final TestSubscriber testSubscriber = new TestSubscriber<>(); observable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(); - Assertions.assertThat(testSubscriber.getOnNextEvents().get(0)).isEqualTo("fallback"); + assertThat(testSubscriber.getOnNextEvents().get(0)).isEqualTo("fallback"); } @Test - public void rxObservableInt() { + void rxObservableInt() { server.enqueue(new MockResponse().setBody("1")); final TestInterface api = target(); @@ -245,14 +252,14 @@ public void rxObservableInt() { assertThat(observable).isNotNull(); assertThat(server.getRequestCount()).isEqualTo(0); - final TestSubscriber testSubscriber = new TestSubscriber(); + final TestSubscriber testSubscriber = new TestSubscriber<>(); observable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(); - Assertions.assertThat(testSubscriber.getOnNextEvents().get(0)).isEqualTo(Integer.valueOf(1)); + assertThat(testSubscriber.getOnNextEvents().get(0)).isEqualTo(Integer.valueOf(1)); } @Test - public void rxObservableIntFallback() { + void rxObservableIntFallback() { server.enqueue(new MockResponse().setResponseCode(500)); final TestInterface api = target(); @@ -262,14 +269,14 @@ public void rxObservableIntFallback() { assertThat(observable).isNotNull(); assertThat(server.getRequestCount()).isEqualTo(0); - final TestSubscriber testSubscriber = new TestSubscriber(); + final TestSubscriber testSubscriber = new TestSubscriber<>(); observable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(); - Assertions.assertThat(testSubscriber.getOnNextEvents().get(0)).isEqualTo(Integer.valueOf(0)); + assertThat(testSubscriber.getOnNextEvents().get(0)).isEqualTo(Integer.valueOf(0)); } @Test - public void rxObservableList() { + void rxObservableList() { server.enqueue(new MockResponse().setBody("[\"foo\",\"bar\"]")); final TestInterface api = target(); @@ -279,14 +286,14 @@ public void rxObservableList() { assertThat(observable).isNotNull(); assertThat(server.getRequestCount()).isEqualTo(0); - final TestSubscriber> testSubscriber = new TestSubscriber>(); + final TestSubscriber> testSubscriber = new TestSubscriber<>(); observable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(); assertThat(testSubscriber.getOnNextEvents().get(0)).containsExactly("foo", "bar"); } @Test - public void rxObservableListFall() { + void rxObservableListFall() { server.enqueue(new MockResponse().setResponseCode(500)); final TestInterface api = target(); @@ -296,14 +303,14 @@ public void rxObservableListFall() { assertThat(observable).isNotNull(); assertThat(server.getRequestCount()).isEqualTo(0); - final TestSubscriber> testSubscriber = new TestSubscriber>(); + final TestSubscriber> testSubscriber = new TestSubscriber<>(); observable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(); assertThat(testSubscriber.getOnNextEvents().get(0)).containsExactly("fallback"); } @Test - public void rxObservableListFall_noFallback() { + void rxObservableListFall_noFallback() { server.enqueue(new MockResponse().setResponseCode(500)); final TestInterface api = targetWithoutFallback(); @@ -313,7 +320,7 @@ public void rxObservableListFall_noFallback() { assertThat(observable).isNotNull(); assertThat(server.getRequestCount()).isEqualTo(0); - final TestSubscriber> testSubscriber = new TestSubscriber>(); + final TestSubscriber> testSubscriber = new TestSubscriber<>(); observable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(); @@ -324,7 +331,7 @@ public void rxObservableListFall_noFallback() { } @Test - public void rxSingle() { + void rxSingle() { server.enqueue(new MockResponse().setBody("\"foo\"")); final TestInterface api = target(); @@ -334,14 +341,14 @@ public void rxSingle() { assertThat(single).isNotNull(); assertThat(server.getRequestCount()).isEqualTo(0); - final TestSubscriber testSubscriber = new TestSubscriber(); + final TestSubscriber testSubscriber = new TestSubscriber<>(); single.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(); - Assertions.assertThat(testSubscriber.getOnNextEvents().get(0)).isEqualTo("foo"); + assertThat(testSubscriber.getOnNextEvents().get(0)).isEqualTo("foo"); } @Test - public void rxSingleFallback() { + void rxSingleFallback() { server.enqueue(new MockResponse().setResponseCode(500)); final TestInterface api = target(); @@ -351,14 +358,14 @@ public void rxSingleFallback() { assertThat(single).isNotNull(); assertThat(server.getRequestCount()).isEqualTo(0); - final TestSubscriber testSubscriber = new TestSubscriber(); + final TestSubscriber testSubscriber = new TestSubscriber<>(); single.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(); - Assertions.assertThat(testSubscriber.getOnNextEvents().get(0)).isEqualTo("fallback"); + assertThat(testSubscriber.getOnNextEvents().get(0)).isEqualTo("fallback"); } @Test - public void rxSingleInt() { + void rxSingleInt() { server.enqueue(new MockResponse().setBody("1")); final TestInterface api = target(); @@ -368,14 +375,14 @@ public void rxSingleInt() { assertThat(single).isNotNull(); assertThat(server.getRequestCount()).isEqualTo(0); - final TestSubscriber testSubscriber = new TestSubscriber(); + final TestSubscriber testSubscriber = new TestSubscriber<>(); single.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(); - Assertions.assertThat(testSubscriber.getOnNextEvents().get(0)).isEqualTo(Integer.valueOf(1)); + assertThat(testSubscriber.getOnNextEvents().get(0)).isEqualTo(Integer.valueOf(1)); } @Test - public void rxSingleIntFallback() { + void rxSingleIntFallback() { server.enqueue(new MockResponse().setResponseCode(500)); final TestInterface api = target(); @@ -385,14 +392,14 @@ public void rxSingleIntFallback() { assertThat(single).isNotNull(); assertThat(server.getRequestCount()).isEqualTo(0); - final TestSubscriber testSubscriber = new TestSubscriber(); + final TestSubscriber testSubscriber = new TestSubscriber<>(); single.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(); - Assertions.assertThat(testSubscriber.getOnNextEvents().get(0)).isEqualTo(Integer.valueOf(0)); + assertThat(testSubscriber.getOnNextEvents().get(0)).isEqualTo(Integer.valueOf(0)); } @Test - public void rxSingleList() { + void rxSingleList() { server.enqueue(new MockResponse().setBody("[\"foo\",\"bar\"]")); final TestInterface api = target(); @@ -402,14 +409,14 @@ public void rxSingleList() { assertThat(single).isNotNull(); assertThat(server.getRequestCount()).isEqualTo(0); - final TestSubscriber> testSubscriber = new TestSubscriber>(); + final TestSubscriber> testSubscriber = new TestSubscriber<>(); single.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(); assertThat(testSubscriber.getOnNextEvents().get(0)).containsExactly("foo", "bar"); } @Test - public void rxSingleListFallback() { + void rxSingleListFallback() { server.enqueue(new MockResponse().setResponseCode(500)); final TestInterface api = target(); @@ -419,14 +426,14 @@ public void rxSingleListFallback() { assertThat(single).isNotNull(); assertThat(server.getRequestCount()).isEqualTo(0); - final TestSubscriber> testSubscriber = new TestSubscriber>(); + final TestSubscriber> testSubscriber = new TestSubscriber<>(); single.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(); assertThat(testSubscriber.getOnNextEvents().get(0)).containsExactly("fallback"); } @Test - public void completableFutureEmptyBody() + void completableFutureEmptyBody() throws InterruptedException, ExecutionException, TimeoutException { server.enqueue(new MockResponse()); @@ -440,7 +447,7 @@ public void completableFutureEmptyBody() } @Test - public void completableFutureWithBody() + void completableFutureWithBody() throws InterruptedException, ExecutionException, TimeoutException { server.enqueue(new MockResponse().setBody("foo")); @@ -454,7 +461,7 @@ public void completableFutureWithBody() } @Test - public void completableFutureFailWithoutFallback() throws TimeoutException, InterruptedException { + void completableFutureFailWithoutFallback() throws TimeoutException, InterruptedException { server.enqueue(new MockResponse().setResponseCode(500)); final TestInterface api = target(TestInterface.class, "http://localhost:" + server.getPort()); @@ -471,7 +478,7 @@ public void completableFutureFailWithoutFallback() throws TimeoutException, Inte } @Test - public void completableFutureFallback() + void completableFutureFallback() throws InterruptedException, ExecutionException, TimeoutException { server.enqueue(new MockResponse().setResponseCode(500)); @@ -485,7 +492,7 @@ public void completableFutureFallback() } @Test - public void rxCompletableEmptyBody() { + void rxCompletableEmptyBody() { server.enqueue(new MockResponse()); final TestInterface api = target(); @@ -495,7 +502,7 @@ public void rxCompletableEmptyBody() { assertThat(completable).isNotNull(); assertThat(server.getRequestCount()).isEqualTo(0); - final TestSubscriber testSubscriber = new TestSubscriber(); + final TestSubscriber testSubscriber = new TestSubscriber<>(); completable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(); @@ -504,7 +511,7 @@ public void rxCompletableEmptyBody() { } @Test - public void rxCompletableWithBody() { + void rxCompletableWithBody() { server.enqueue(new MockResponse().setBody("foo")); final TestInterface api = target(); @@ -514,7 +521,7 @@ public void rxCompletableWithBody() { assertThat(completable).isNotNull(); assertThat(server.getRequestCount()).isEqualTo(0); - final TestSubscriber testSubscriber = new TestSubscriber(); + final TestSubscriber testSubscriber = new TestSubscriber<>(); completable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(); @@ -523,7 +530,7 @@ public void rxCompletableWithBody() { } @Test - public void rxCompletableFailWithoutFallback() { + void rxCompletableFailWithoutFallback() { server.enqueue(new MockResponse().setResponseCode(500)); final TestInterface api = target(TestInterface.class, "http://localhost:" + server.getPort()); @@ -533,7 +540,7 @@ public void rxCompletableFailWithoutFallback() { assertThat(completable).isNotNull(); assertThat(server.getRequestCount()).isEqualTo(0); - final TestSubscriber testSubscriber = new TestSubscriber(); + final TestSubscriber testSubscriber = new TestSubscriber<>(); completable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(); @@ -541,7 +548,7 @@ public void rxCompletableFailWithoutFallback() { } @Test - public void rxCompletableFallback() { + void rxCompletableFallback() { server.enqueue(new MockResponse().setResponseCode(500)); final TestInterface api = target(); @@ -551,7 +558,7 @@ public void rxCompletableFallback() { assertThat(completable).isNotNull(); assertThat(server.getRequestCount()).isEqualTo(0); - final TestSubscriber testSubscriber = new TestSubscriber(); + final TestSubscriber testSubscriber = new TestSubscriber<>(); completable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(); @@ -559,7 +566,7 @@ public void rxCompletableFallback() { } @Test - public void plainString() { + void plainString() { server.enqueue(new MockResponse().setBody("\"foo\"")); final TestInterface api = target(); @@ -570,7 +577,7 @@ public void plainString() { } @Test - public void plainStringFallback() { + void plainStringFallback() { server.enqueue(new MockResponse().setResponseCode(500)); final TestInterface api = target(); @@ -581,7 +588,7 @@ public void plainStringFallback() { } @Test - public void plainList() { + void plainList() { server.enqueue(new MockResponse().setBody("[\"foo\",\"bar\"]")); final TestInterface api = target(); @@ -592,7 +599,7 @@ public void plainList() { } @Test - public void plainListFallback() { + void plainListFallback() { server.enqueue(new MockResponse().setResponseCode(500)); final TestInterface api = target(); @@ -603,13 +610,13 @@ public void plainListFallback() { } @Test - public void equalsHashCodeAndToStringWork() { + void equalsHashCodeAndToStringWork() { final Target t1 = - new HardCodedTarget(TestInterface.class, "http://localhost:8080"); + new HardCodedTarget<>(TestInterface.class, "http://localhost:8080"); final Target t2 = - new HardCodedTarget(TestInterface.class, "http://localhost:8888"); + new HardCodedTarget<>(TestInterface.class, "http://localhost:8888"); final Target t3 = - new HardCodedTarget(OtherTestInterface.class, "http://localhost:8080"); + new HardCodedTarget<>(OtherTestInterface.class, "http://localhost:8080"); final TestInterface i1 = target(t1); final TestInterface i2 = target(t1); final TestInterface i3 = target(t2); @@ -716,7 +723,7 @@ default HystrixCommand defaultMethodReturningCommand() { class FallbackTestInterface implements TestInterface { @Override public HystrixCommand command() { - return new HystrixCommand(HystrixCommandGroupKey.Factory.asKey("Test")) { + return new HystrixCommand<>(HystrixCommandGroupKey.Factory.asKey("Test")) { @Override protected String run() throws Exception { return "fallback"; @@ -726,10 +733,10 @@ protected String run() throws Exception { @Override public HystrixCommand> listCommand() { - return new HystrixCommand>(HystrixCommandGroupKey.Factory.asKey("Test")) { + return new HystrixCommand<>(HystrixCommandGroupKey.Factory.asKey("Test")) { @Override protected List run() throws Exception { - final List fallbackResult = new ArrayList(); + final List fallbackResult = new ArrayList<>(); fallbackResult.add("fallback"); return fallbackResult; } @@ -738,7 +745,7 @@ protected List run() throws Exception { @Override public HystrixCommand intCommand() { - return new HystrixCommand(HystrixCommandGroupKey.Factory.asKey("Test")) { + return new HystrixCommand<>(HystrixCommandGroupKey.Factory.asKey("Test")) { @Override protected Integer run() throws Exception { return 0; @@ -748,7 +755,7 @@ protected Integer run() throws Exception { @Override public Observable> listObservable() { - final List fallbackResult = new ArrayList(); + final List fallbackResult = new ArrayList<>(); fallbackResult.add("fallback"); return Observable.just(fallbackResult); } @@ -765,7 +772,7 @@ public Single intSingle() { @Override public Single> listSingle() { - final List fallbackResult = new ArrayList(); + final List fallbackResult = new ArrayList<>(); fallbackResult.add("fallback"); return Single.just(fallbackResult); } @@ -787,7 +794,7 @@ public String get() { @Override public List getList() { - final List fallbackResult = new ArrayList(); + final List fallbackResult = new ArrayList<>(); fallbackResult.add("fallback"); return fallbackResult; } @@ -802,4 +809,9 @@ public CompletableFuture completableFuture() { return CompletableFuture.completedFuture("fallback"); } } + + @AfterEach + void afterEachTest() throws IOException { + server.close(); + } } diff --git a/hystrix/src/test/java/feign/hystrix/SetterFactoryTest.java b/hystrix/src/test/java/feign/hystrix/SetterFactoryTest.java index a58cb116e..2a8138a97 100644 --- a/hystrix/src/test/java/feign/hystrix/SetterFactoryTest.java +++ b/hystrix/src/test/java/feign/hystrix/SetterFactoryTest.java @@ -13,16 +13,19 @@ */ package feign.hystrix; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + import com.netflix.hystrix.HystrixCommand; import com.netflix.hystrix.HystrixCommandGroupKey; import com.netflix.hystrix.HystrixCommandKey; import com.netflix.hystrix.exception.HystrixRuntimeException; import feign.RequestLine; -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.MockWebServer; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import java.io.IOException; +import mockwebserver3.MockResponse; +import mockwebserver3.MockWebServer; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; public class SetterFactoryTest { @@ -31,13 +34,10 @@ interface TestInterface { String invoke(); } - @Rule public final ExpectedException thrown = ExpectedException.none(); - @Rule public final MockWebServer server = new MockWebServer(); + public final MockWebServer server = new MockWebServer(); @Test - public void customSetter() { - thrown.expect(HystrixRuntimeException.class); - thrown.expectMessage("POST / failed and no fallback available."); + void customSetter() { server.enqueue(new MockResponse().setResponseCode(500)); @@ -54,6 +54,12 @@ public void customSetter() { .setterFactory(commandKeyIsRequestLine) .target(TestInterface.class, "http://localhost:" + server.getPort()); - api.invoke(); + Throwable exception = assertThrows(HystrixRuntimeException.class, () -> api.invoke()); + assertThat(exception.getMessage()).contains("POST / failed and no fallback available."); + } + + @AfterEach + void afterEachTest() throws IOException { + server.close(); } } diff --git a/jackson-jaxb/src/test/java/feign/jackson/jaxb/JacksonJaxbCodecTest.java b/jackson-jaxb/src/test/java/feign/jackson/jaxb/JacksonJaxbCodecTest.java index f88a6b87f..723882eec 100644 --- a/jackson-jaxb/src/test/java/feign/jackson/jaxb/JacksonJaxbCodecTest.java +++ b/jackson-jaxb/src/test/java/feign/jackson/jaxb/JacksonJaxbCodecTest.java @@ -15,6 +15,7 @@ import static feign.Util.UTF_8; import static feign.assertj.FeignAssertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import feign.Request; import feign.Request.HttpMethod; @@ -26,13 +27,13 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; -import org.junit.Test; +import org.junit.jupiter.api.Test; @SuppressWarnings("deprecation") -public class JacksonJaxbCodecTest { +class JacksonJaxbCodecTest { @Test - public void encodeTest() { + void encodeTest() { JacksonJaxbJsonEncoder encoder = new JacksonJaxbJsonEncoder(); RequestTemplate template = new RequestTemplate(); @@ -42,7 +43,7 @@ public void encodeTest() { } @Test - public void decodeTest() throws Exception { + void decodeTest() throws Exception { Response response = Response.builder() .status(200) @@ -59,7 +60,7 @@ public void decodeTest() throws Exception { /** Enabled via {@link feign.Feign.Builder#dismiss404()} */ @Test - public void notFoundDecodesToEmpty() throws Exception { + void notFoundDecodesToEmpty() throws Exception { Response response = Response.builder() .status(404) diff --git a/jackson-jr/src/test/java/feign/jackson/jr/JacksonCodecTest.java b/jackson-jr/src/test/java/feign/jackson/jr/JacksonCodecTest.java index 961480353..97bdb2cbb 100644 --- a/jackson-jr/src/test/java/feign/jackson/jr/JacksonCodecTest.java +++ b/jackson-jr/src/test/java/feign/jackson/jr/JacksonCodecTest.java @@ -16,7 +16,7 @@ import static feign.Util.UTF_8; import static feign.assertj.FeignAssertions.assertThat; import static java.util.Collections.singletonList; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.jr.ob.JSON; @@ -28,15 +28,23 @@ import java.io.IOException; import java.nio.charset.StandardCharsets; import java.time.LocalDate; -import java.util.*; -import org.junit.Test; - -public class JacksonCodecTest { +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import org.junit.jupiter.api.Test; + +class JacksonCodecTest { private static final String DATES_JSON = "[\"2020-01-02\",\"2021-02-03\"]"; @Test - public void encodesMapObjectNumericalValuesAsInteger() { + void encodesMapObjectNumericalValuesAsInteger() { Map map = new LinkedHashMap<>(); map.put("foo", 1); @@ -47,7 +55,7 @@ public void encodesMapObjectNumericalValuesAsInteger() { } @Test - public void encodesMapObjectNumericalValuesToByteArray() { + void encodesMapObjectNumericalValuesToByteArray() { Map map = new LinkedHashMap<>(); map.put("foo", 1); @@ -58,8 +66,8 @@ public void encodesMapObjectNumericalValuesToByteArray() { } @Test - public void encodesFormParams() { - Map form = new LinkedHashMap(); + void encodesFormParams() { + Map form = new LinkedHashMap<>(); form.put("foo", 1); form.put("bar", Arrays.asList(2, 3)); @@ -70,7 +78,7 @@ public void encodesFormParams() { } @Test - public void decodes() throws Exception { + void decodes() throws Exception { List zones = new LinkedList<>(); zones.add(new Zone("denominator.io.")); zones.add(new Zone("denominator.io.", "ABCD")); @@ -87,13 +95,13 @@ public void decodes() throws Exception { .headers(Collections.emptyMap()) .body(zonesJson, UTF_8) .build(); - assertEquals( - zones, - new JacksonJrDecoder().decode(response, new TypeReference>() {}.getType())); + assertThat( + new JacksonJrDecoder().decode(response, new TypeReference>() {}.getType())) + .isEqualTo(zones); } @Test - public void nullBodyDecodesToEmpty() throws Exception { + void nullBodyDecodesToEmpty() throws Exception { Response response = Response.builder() .status(204) @@ -106,7 +114,7 @@ public void nullBodyDecodesToEmpty() throws Exception { } @Test - public void emptyBodyDecodesToEmpty() throws Exception { + void emptyBodyDecodesToEmpty() throws Exception { Response response = Response.builder() .status(204) @@ -120,7 +128,7 @@ public void emptyBodyDecodesToEmpty() throws Exception { } @Test - public void customDecoder() throws Exception { + void customDecoder() throws Exception { JacksonJrDecoder decoder = new JacksonJrDecoder(singletonList(new JavaLocalDateExtension())); List dates = new LinkedList<>(); @@ -136,12 +144,12 @@ public void customDecoder() throws Exception { .headers(Collections.emptyMap()) .body(DATES_JSON, UTF_8) .build(); - assertEquals( - dates, decoder.decode(response, new TypeReference>() {}.getType())); + assertThat(decoder.decode(response, new TypeReference>() {}.getType())) + .isEqualTo(dates); } @Test - public void customDecoderExpressedAsMapper() throws Exception { + void customDecoderExpressedAsMapper() throws Exception { JSON mapper = JSON.builder().register(new JavaLocalDateExtension()).build(); JacksonJrDecoder decoder = new JacksonJrDecoder(mapper); @@ -158,12 +166,12 @@ public void customDecoderExpressedAsMapper() throws Exception { .headers(Collections.emptyMap()) .body(DATES_JSON, UTF_8) .build(); - assertEquals( - dates, decoder.decode(response, new TypeReference>() {}.getType())); + assertThat(decoder.decode(response, new TypeReference>() {}.getType())) + .isEqualTo(dates); } @Test - public void customEncoder() { + void customEncoder() { JacksonJrEncoder encoder = new JacksonJrEncoder(singletonList(new JavaLocalDateExtension())); List dates = new LinkedList<>(); @@ -177,10 +185,10 @@ public void customEncoder() { } @Test - public void decoderCharset() throws IOException { + void decoderCharset() throws IOException { Zone zone = new Zone("denominator.io.", "ÁÉÍÓÚÀÈÌÒÙÄËÏÖÜÑ"); - Map> headers = new HashMap>(); + Map> headers = new HashMap<>(); headers.put("Content-Type", Arrays.asList("application/json;charset=ISO-8859-1")); Response response = @@ -202,12 +210,12 @@ public void decoderCharset() throws IOException { + "}") .getBytes(StandardCharsets.ISO_8859_1)) .build(); - assertEquals( - zone.getId(), ((Zone) new JacksonJrDecoder().decode(response, Zone.class)).getId()); + assertThat(((Zone) new JacksonJrDecoder().decode(response, Zone.class)).getId()) + .isEqualTo(zone.getId()); } @Test - public void decodesToMap() throws Exception { + void decodesToMap() throws Exception { String json = "{\"name\":\"jim\",\"id\":12}"; Response response = @@ -225,8 +233,8 @@ public void decodesToMap() throws Exception { new JacksonJrDecoder() .decode(response, new TypeReference>() {}.getType()); - assertEquals(12, map.get("id")); - assertEquals("jim", map.get("name")); + assertThat(map).containsEntry("id", 12); + assertThat(map).containsEntry("name", "jim"); } public static class Zone { @@ -288,7 +296,7 @@ public String toString() { /** Enabled via {@link feign.Feign.Builder#dismiss404()} */ @Test - public void notFoundDecodesToEmpty() throws Exception { + void notFoundDecodesToEmpty() throws Exception { Response response = Response.builder() .status(404) diff --git a/jackson/src/test/java/feign/jackson/JacksonCodecTest.java b/jackson/src/test/java/feign/jackson/JacksonCodecTest.java index f1c342b55..c575e9aa1 100644 --- a/jackson/src/test/java/feign/jackson/JacksonCodecTest.java +++ b/jackson/src/test/java/feign/jackson/JacksonCodecTest.java @@ -15,9 +15,7 @@ import static feign.Util.UTF_8; import static feign.assertj.FeignAssertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; @@ -46,10 +44,10 @@ import java.util.LinkedList; import java.util.List; import java.util.Map; -import org.junit.Test; +import org.junit.jupiter.api.Test; @SuppressWarnings("deprecation") -public class JacksonCodecTest { +class JacksonCodecTest { private String zonesJson = "" // @@ -73,8 +71,8 @@ public class JacksonCodecTest { + System.lineSeparator(); @Test - public void encodesMapObjectNumericalValuesAsInteger() { - Map map = new LinkedHashMap(); + void encodesMapObjectNumericalValuesAsInteger() { + Map map = new LinkedHashMap<>(); map.put("foo", 1); RequestTemplate template = new RequestTemplate(); @@ -91,8 +89,8 @@ public void encodesMapObjectNumericalValuesAsInteger() { } @Test - public void encodesFormParams() { - Map form = new LinkedHashMap(); + void encodesFormParams() { + Map form = new LinkedHashMap<>(); form.put("foo", 1); form.put("bar", Arrays.asList(2, 3)); @@ -112,7 +110,7 @@ public void encodesFormParams() { } @Test - public void decodes() throws Exception { + void decodes() throws Exception { List zones = new LinkedList<>(); zones.add(new Zone("denominator.io.")); zones.add(new Zone("denominator.io.", "ABCD")); @@ -126,12 +124,12 @@ public void decodes() throws Exception { .headers(Collections.emptyMap()) .body(zonesJson, UTF_8) .build(); - assertEquals( - zones, new JacksonDecoder().decode(response, new TypeReference>() {}.getType())); + assertThat(new JacksonDecoder().decode(response, new TypeReference>() {}.getType())) + .isEqualTo(zones); } @Test - public void nullBodyDecodesToNull() throws Exception { + void nullBodyDecodesToNull() throws Exception { Response response = Response.builder() .status(204) @@ -140,11 +138,11 @@ public void nullBodyDecodesToNull() throws Exception { Request.create(HttpMethod.GET, "/api", Collections.emptyMap(), null, Util.UTF_8)) .headers(Collections.emptyMap()) .build(); - assertNull(new JacksonDecoder().decode(response, String.class)); + assertThat(new JacksonDecoder().decode(response, String.class)).isNull(); } @Test - public void emptyBodyDecodesToNull() throws Exception { + void emptyBodyDecodesToNull() throws Exception { Response response = Response.builder() .status(204) @@ -154,16 +152,16 @@ public void emptyBodyDecodesToNull() throws Exception { .headers(Collections.emptyMap()) .body(new byte[0]) .build(); - assertNull(new JacksonDecoder().decode(response, String.class)); + assertThat(new JacksonDecoder().decode(response, String.class)).isNull(); } @Test - public void customDecoder() throws Exception { + void customDecoder() throws Exception { JacksonDecoder decoder = new JacksonDecoder( Arrays.asList(new SimpleModule().addDeserializer(Zone.class, new ZoneDeserializer()))); - List zones = new LinkedList(); + List zones = new LinkedList<>(); zones.add(new Zone("DENOMINATOR.IO.")); zones.add(new Zone("DENOMINATOR.IO.", "ABCD")); @@ -176,16 +174,17 @@ public void customDecoder() throws Exception { .headers(Collections.emptyMap()) .body(zonesJson, UTF_8) .build(); - assertEquals(zones, decoder.decode(response, new TypeReference>() {}.getType())); + assertThat(decoder.decode(response, new TypeReference>() {}.getType())) + .isEqualTo(zones); } @Test - public void customEncoder() { + void customEncoder() { JacksonEncoder encoder = new JacksonEncoder( Arrays.asList(new SimpleModule().addSerializer(Zone.class, new ZoneSerializer()))); - List zones = new LinkedList(); + List zones = new LinkedList<>(); zones.add(new Zone("denominator.io.")); zones.add(new Zone("denominator.io.", "abcd")); @@ -209,10 +208,10 @@ public void customEncoder() { } @Test - public void decoderCharset() throws IOException { + void decoderCharset() throws IOException { Zone zone = new Zone("denominator.io.", "ÁÉÍÓÚÀÈÌÒÙÄËÏÖÜÑ"); - Map> headers = new HashMap>(); + Map> headers = new HashMap<>(); headers.put("Content-Type", Arrays.asList("application/json;charset=ISO-8859-1")); Response response = @@ -234,15 +233,14 @@ public void decoderCharset() throws IOException { + "}") .getBytes(StandardCharsets.ISO_8859_1)) .build(); - assertEquals( - zone.get("id"), - ((Zone) new JacksonDecoder().decode(response, new TypeReference() {}.getType())) - .get("id")); + assertThat( + ((Zone) new JacksonDecoder().decode(response, new TypeReference() {}.getType()))) + .containsEntry("id", zone.get("id")); } @Test - public void decodesIterator() throws Exception { - List zones = new LinkedList(); + void decodesIterator() throws Exception { + List zones = new LinkedList<>(); zones.add(new Zone("denominator.io.")); zones.add(new Zone("denominator.io.", "ABCD")); @@ -258,19 +256,21 @@ public void decodesIterator() throws Exception { Object decoded = JacksonIteratorDecoder.create() .decode(response, new TypeReference>() {}.getType()); - assertTrue(Iterator.class.isAssignableFrom(decoded.getClass())); - assertTrue(Closeable.class.isAssignableFrom(decoded.getClass())); - assertEquals(zones, asList((Iterator) decoded)); + assertThat(Iterator.class.isAssignableFrom(decoded.getClass())).isTrue(); + assertThat(Closeable.class.isAssignableFrom(decoded.getClass())).isTrue(); + assertThat(asList((Iterator) decoded)).isEqualTo(zones); } private List asList(Iterator iter) { - final List copy = new ArrayList(); - while (iter.hasNext()) copy.add(iter.next()); + final List copy = new ArrayList<>(); + while (iter.hasNext()) { + copy.add(iter.next()); + } return copy; } @Test - public void nullBodyDecodesToEmptyIterator() throws Exception { + void nullBodyDecodesToEmptyIterator() throws Exception { Response response = Response.builder() .status(204) @@ -283,7 +283,7 @@ public void nullBodyDecodesToEmptyIterator() throws Exception { } @Test - public void emptyBodyDecodesToEmptyIterator() throws Exception { + void emptyBodyDecodesToEmptyIterator() throws Exception { Response response = Response.builder() .status(204) @@ -357,7 +357,7 @@ public void serialize(Zone value, JsonGenerator jgen, SerializerProvider provide /** Enabled via {@link feign.Feign.Builder#dismiss404()} */ @Test - public void notFoundDecodesToEmpty() throws Exception { + void notFoundDecodesToEmpty() throws Exception { Response response = Response.builder() .status(404) @@ -371,7 +371,7 @@ public void notFoundDecodesToEmpty() throws Exception { /** Enabled via {@link feign.Feign.Builder#dismiss404()} */ @Test - public void notFoundDecodesToEmptyIterator() throws Exception { + void notFoundDecodesToEmptyIterator() throws Exception { Response response = Response.builder() .status(404) diff --git a/jackson/src/test/java/feign/jackson/JacksonIteratorTest.java b/jackson/src/test/java/feign/jackson/JacksonIteratorTest.java index 1145497a0..1ac885d89 100644 --- a/jackson/src/test/java/feign/jackson/JacksonIteratorTest.java +++ b/jackson/src/test/java/feign/jackson/JacksonIteratorTest.java @@ -16,7 +16,8 @@ import static feign.Util.UTF_8; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.hamcrest.core.Is.isA; +import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.junit.jupiter.api.Assertions.assertThrows; import com.fasterxml.jackson.databind.ObjectMapper; import feign.Request; @@ -32,22 +33,18 @@ import java.util.LinkedHashMap; import java.util.NoSuchElementException; import java.util.concurrent.atomic.AtomicBoolean; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; @SuppressWarnings("deprecation") -public class JacksonIteratorTest { - - @Rule public final ExpectedException thrown = ExpectedException.none(); +class JacksonIteratorTest { @Test - public void shouldDecodePrimitiveArrays() throws IOException { + void shouldDecodePrimitiveArrays() throws IOException { assertThat(iterator(Integer.class, "[0,1,2,3]")).toIterable().containsExactly(0, 1, 2, 3); } @Test - public void shouldNotSkipElementsOnHasNext() throws IOException { + void shouldNotSkipElementsOnHasNext() throws IOException { JacksonIterator iterator = iterator(Integer.class, "[0]"); assertThat(iterator.hasNext()).isTrue(); assertThat(iterator.hasNext()).isTrue(); @@ -56,14 +53,14 @@ public void shouldNotSkipElementsOnHasNext() throws IOException { } @Test - public void hasNextIsNotMandatory() throws IOException { + void hasNextIsNotMandatory() throws IOException { JacksonIterator iterator = iterator(Integer.class, "[0]"); assertThat(iterator.next()).isEqualTo(0); assertThat(iterator.hasNext()).isFalse(); } @Test - public void expectExceptionOnNoElements() throws IOException { + void expectExceptionOnNoElements() throws IOException { JacksonIterator iterator = iterator(Integer.class, "[0]"); assertThat(iterator.next()).isEqualTo(0); assertThatThrownBy(() -> iterator.next()) @@ -72,39 +69,43 @@ public void expectExceptionOnNoElements() throws IOException { } @Test - public void shouldDecodeObjects() throws IOException { + void shouldDecodeObjects() throws IOException { assertThat(iterator(User.class, "[{\"login\":\"bob\"},{\"login\":\"joe\"}]")) .toIterable() .containsExactly(new User("bob"), new User("joe")); } @Test - public void malformedObjectThrowsDecodeException() throws IOException { - thrown.expect(DecodeException.class); - thrown.expectCause(isA(IOException.class)); - - assertThat(iterator(User.class, "[{\"login\":\"bob\"},{\"login\":\"joe...")) - .toIterable() - .containsOnly(new User("bob")); + void malformedObjectThrowsDecodeException() throws IOException { + DecodeException exception = + assertThrows( + DecodeException.class, + () -> + assertThat(iterator(User.class, "[{\"login\":\"bob\"},{\"login\":\"joe...")) + .toIterable() + .containsOnly(new User("bob"))); + assertThat(exception).hasCauseInstanceOf(IOException.class); } @Test - public void emptyBodyDecodesToEmptyIterator() throws IOException { + void emptyBodyDecodesToEmptyIterator() throws IOException { assertThat(iterator(String.class, "")).toIterable().isEmpty(); } @Test - public void unmodifiable() throws IOException { - thrown.expect(UnsupportedOperationException.class); - - JacksonIterator it = iterator(String.class, "[\"test\"]"); - - assertThat(it).toIterable().containsExactly("test"); - it.remove(); + void unmodifiable() throws IOException { + assertThatExceptionOfType(UnsupportedOperationException.class) + .isThrownBy( + () -> { + JacksonIterator it = iterator(String.class, "[\"test\"]"); + + assertThat(it).toIterable().containsExactly("test"); + it.remove(); + }); } @Test - public void responseIsClosedAfterIteration() throws IOException { + void responseIsClosedAfterIteration() throws IOException { final AtomicBoolean closed = new AtomicBoolean(); byte[] jsonBytes = "[false, true]".getBytes(UTF_8); @@ -131,7 +132,7 @@ public void close() throws IOException { } @Test - public void responseIsClosedOnParseError() throws IOException { + void responseIsClosedOnParseError() throws IOException { final AtomicBoolean closed = new AtomicBoolean(); byte[] jsonBytes = "[error".getBytes(UTF_8); @@ -153,12 +154,11 @@ public void close() throws IOException { .body(inputStream, jsonBytes.length) .build(); - try { - thrown.expect(DecodeException.class); - assertThat(iterator(Boolean.class, response)).toIterable().hasSize(1); - } finally { - assertThat(closed.get()).isTrue(); - } + assertThrows( + DecodeException.class, + () -> assertThat(iterator(Boolean.class, response)).toIterable().hasSize(1)); + + assertThat(closed.get()).isTrue(); } static class User extends LinkedHashMap { @@ -188,7 +188,7 @@ JacksonIterator iterator(Class type, String json) throws IOException { } JacksonIterator iterator(Class type, Response response) throws IOException { - return new JacksonIterator( + return new JacksonIterator<>( type.getGenericSuperclass(), new ObjectMapper(), response, response.body().asReader()); } } diff --git a/jakarta/src/test/java/feign/jaxrs/JakartaContractTest.java b/jakarta/src/test/java/feign/jaxrs/JakartaContractTest.java index 7a94bf80f..7dc757324 100644 --- a/jakarta/src/test/java/feign/jaxrs/JakartaContractTest.java +++ b/jakarta/src/test/java/feign/jaxrs/JakartaContractTest.java @@ -15,12 +15,25 @@ import static feign.assertj.FeignAssertions.assertThat; import static java.util.Arrays.asList; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.data.MapEntry.entry; import feign.MethodMetadata; import feign.Response; import feign.jaxrs.JakartaContractTest.JakartaInternals.BeanParamInput; -import jakarta.ws.rs.*; +import jakarta.ws.rs.BeanParam; +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.DELETE; +import jakarta.ws.rs.FormParam; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.HeaderParam; +import jakarta.ws.rs.HttpMethod; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.PUT; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.QueryParam; import jakarta.ws.rs.container.AsyncResponse; import jakarta.ws.rs.container.Suspended; import jakarta.ws.rs.core.Context; @@ -32,16 +45,16 @@ import java.lang.annotation.Target; import java.net.URI; import java.util.List; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests interfaces defined per {@link JakartaContract} are interpreted into expected {@link feign * .RequestTemplate template} instances. */ -public class JakartaContractTest extends JAXRSContractTestSupport { +class JakartaContractTest extends JAXRSContractTestSupport { @Test - public void injectJaxrsInternals() throws Exception { + void injectJaxrsInternals() throws Exception { final MethodMetadata methodMetadata = parseAndValidateMetadata( JakartaInternals.class, "inject", AsyncResponse.class, UriInfo.class); @@ -49,7 +62,7 @@ public void injectJaxrsInternals() throws Exception { } @Test - public void injectBeanParam() throws Exception { + void injectBeanParam() throws Exception { final MethodMetadata methodMetadata = parseAndValidateMetadata(JakartaInternals.class, "beanParameters", BeanParamInput.class); assertThat(methodMetadata.template()).noRequestBody(); diff --git a/java11/pom.xml b/java11/pom.xml index f6d2239b6..a977390b5 100644 --- a/java11/pom.xml +++ b/java11/pom.xml @@ -29,10 +29,7 @@ 11 - java18 ${project.basedir}/.. - 11 - 11 @@ -47,7 +44,7 @@ com.squareup.okhttp3 - mockwebserver + mockwebserver3-junit5 test @@ -66,17 +63,4 @@ - - - - org.codehaus.mojo - animal-sniffer-maven-plugin - - - true - - - - - diff --git a/java11/src/test/java/feign/http2client/test/Http2ClientAsyncTest.java b/java11/src/test/java/feign/http2client/test/Http2ClientAsyncTest.java index 6791058da..dded87c6a 100644 --- a/java11/src/test/java/feign/http2client/test/Http2ClientAsyncTest.java +++ b/java11/src/test/java/feign/http2client/test/Http2ClientAsyncTest.java @@ -14,11 +14,12 @@ package feign.http2client.test; import static feign.assertj.MockWebServerAssertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; import static org.assertj.core.data.MapEntry.entry; -import static org.hamcrest.CoreMatchers.isA; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; @@ -76,20 +77,17 @@ import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.MockWebServer; +import mockwebserver3.MockResponse; +import mockwebserver3.MockWebServer; import okio.Buffer; -import org.assertj.core.api.Assertions; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; public class Http2ClientAsyncTest { - @Rule public final ExpectedException thrown = ExpectedException.none(); - @Rule public final MockWebServer server = new MockWebServer(); + public final MockWebServer server = new MockWebServer(); @Test - public void iterableQueryParams() throws Exception { + void iterableQueryParams() throws Exception { server.enqueue(new MockResponse().setBody("foo")); final TestInterfaceAsync api = newAsyncBuilder().target("http://localhost:" + server.getPort()); @@ -100,7 +98,7 @@ public void iterableQueryParams() throws Exception { } @Test - public void postTemplateParamsResolve() throws Exception { + void postTemplateParamsResolve() throws Exception { server.enqueue(new MockResponse().setBody("foo")); final TestInterfaceAsync api = newAsyncBuilder().target("http://localhost:" + server.getPort()); @@ -114,18 +112,18 @@ public void postTemplateParamsResolve() throws Exception { } @Test - public void responseCoercesToStringBody() throws Throwable { + void responseCoercesToStringBody() throws Throwable { server.enqueue(new MockResponse().setBody("foo")); final TestInterfaceAsync api = newAsyncBuilder().target("http://localhost:" + server.getPort()); final Response response = unwrap(api.response()); - assertTrue(response.body().isRepeatable()); - assertEquals("foo", Util.toString(response.body().asReader(StandardCharsets.UTF_8))); + assertThat(response.body().isRepeatable()).isTrue(); + assertThat(Util.toString(response.body().asReader(StandardCharsets.UTF_8))).isEqualTo("foo"); } @Test - public void postFormParams() throws Exception { + void postFormParams() throws Exception { server.enqueue(new MockResponse().setBody("foo")); final TestInterfaceAsync api = newAsyncBuilder().target("http://localhost:" + server.getPort()); @@ -140,7 +138,7 @@ public void postFormParams() throws Exception { } @Test - public void postBodyParam() throws Exception { + void postBodyParam() throws Exception { server.enqueue(new MockResponse().setBody("foo")); final TestInterfaceAsync api = newAsyncBuilder().target("http://localhost:" + server.getPort()); @@ -159,10 +157,10 @@ public void postBodyParam() throws Exception { * type. */ @Test - public void bodyTypeCorrespondsWithParameterType() throws Exception { + void bodyTypeCorrespondsWithParameterType() throws Exception { server.enqueue(new MockResponse().setBody("foo")); - final AtomicReference encodedType = new AtomicReference(); + final AtomicReference encodedType = new AtomicReference<>(); final TestInterfaceAsync api = newAsyncBuilder() .encoder( @@ -178,13 +176,13 @@ public void encode(Object object, Type bodyType, RequestTemplate template) { server.takeRequest(); - Assertions.assertThat(encodedType.get()).isEqualTo(new TypeToken>() {}.getType()); + assertThat(encodedType.get()).isEqualTo(new TypeToken>() {}.getType()); checkCFCompletedSoon(cf); } @Test - public void singleInterceptor() throws Exception { + void singleInterceptor() throws Exception { server.enqueue(new MockResponse().setBody("foo")); final TestInterfaceAsync api = @@ -201,7 +199,7 @@ public void singleInterceptor() throws Exception { } @Test - public void multipleInterceptor() throws Exception { + void multipleInterceptor() throws Exception { server.enqueue(new MockResponse().setBody("foo")); final TestInterfaceAsync api = @@ -221,7 +219,7 @@ public void multipleInterceptor() throws Exception { } @Test - public void customExpander() throws Exception { + void customExpander() throws Exception { server.enqueue(new MockResponse()); final TestInterfaceAsync api = newAsyncBuilder().target("http://localhost:" + server.getPort()); @@ -234,7 +232,7 @@ public void customExpander() throws Exception { } @Test - public void customExpanderListParam() throws Exception { + void customExpanderListParam() throws Exception { server.enqueue(new MockResponse()); final TestInterfaceAsync api = newAsyncBuilder().target("http://localhost:" + server.getPort()); @@ -248,7 +246,7 @@ public void customExpanderListParam() throws Exception { } @Test - public void customExpanderNullParam() throws Exception { + void customExpanderNullParam() throws Exception { server.enqueue(new MockResponse()); final TestInterfaceAsync api = newAsyncBuilder().target("http://localhost:" + server.getPort()); @@ -261,12 +259,12 @@ public void customExpanderNullParam() throws Exception { } @Test - public void headerMap() throws Exception { + void headerMap() throws Exception { server.enqueue(new MockResponse()); final TestInterfaceAsync api = newAsyncBuilder().target("http://localhost:" + server.getPort()); - final Map headerMap = new LinkedHashMap(); + final Map headerMap = new LinkedHashMap<>(); headerMap.put("Content-Type", "myContent"); headerMap.put("Custom-Header", "fooValue"); final CompletableFuture cf = api.headerMap(headerMap); @@ -280,12 +278,12 @@ public void headerMap() throws Exception { } @Test - public void headerMapWithHeaderAnnotations() throws Exception { + void headerMapWithHeaderAnnotations() throws Exception { server.enqueue(new MockResponse()); final TestInterfaceAsync api = newAsyncBuilder().target("http://localhost:" + server.getPort()); - final Map headerMap = new LinkedHashMap(); + final Map headerMap = new LinkedHashMap<>(); headerMap.put("Custom-Header", "fooValue"); api.headerMapWithHeaderAnnotations(headerMap); @@ -313,12 +311,12 @@ public void headerMapWithHeaderAnnotations() throws Exception { } @Test - public void queryMap() throws Exception { + void queryMap() throws Exception { server.enqueue(new MockResponse()); final TestInterfaceAsync api = newAsyncBuilder().target("http://localhost:" + server.getPort()); - final Map queryMap = new LinkedHashMap(); + final Map queryMap = new LinkedHashMap<>(); queryMap.put("name", "alice"); queryMap.put("fooKey", "fooValue"); final CompletableFuture cf = api.queryMap(queryMap); @@ -329,15 +327,15 @@ public void queryMap() throws Exception { } @Test - public void queryMapIterableValuesExpanded() throws Exception { + void queryMapIterableValuesExpanded() throws Exception { server.enqueue(new MockResponse()); final TestInterfaceAsync api = newAsyncBuilder().target("http://localhost:" + server.getPort()); - final Map queryMap = new LinkedHashMap(); + final Map queryMap = new LinkedHashMap<>(); queryMap.put("name", Arrays.asList("Alice", "Bob")); queryMap.put("fooKey", "fooValue"); - queryMap.put("emptyListKey", new ArrayList()); + queryMap.put("emptyListKey", new ArrayList<>()); queryMap.put("emptyStringKey", ""); // empty values are ignored. final CompletableFuture cf = api.queryMap(queryMap); @@ -348,25 +346,25 @@ public void queryMapIterableValuesExpanded() throws Exception { } @Test - public void queryMapWithQueryParams() throws Exception { + void queryMapWithQueryParams() throws Exception { final TestInterfaceAsync api = newAsyncBuilder().target("http://localhost:" + server.getPort()); server.enqueue(new MockResponse()); - Map queryMap = new LinkedHashMap(); + Map queryMap = new LinkedHashMap<>(); queryMap.put("fooKey", "fooValue"); api.queryMapWithQueryParams("alice", queryMap); // query map should be expanded after built-in parameters assertThat(server.takeRequest()).hasPath("/?name=alice&fooKey=fooValue"); server.enqueue(new MockResponse()); - queryMap = new LinkedHashMap(); + queryMap = new LinkedHashMap<>(); queryMap.put("name", "bob"); api.queryMapWithQueryParams("alice", queryMap); // queries are additive assertThat(server.takeRequest()).hasPath("/?name=alice&name=bob"); server.enqueue(new MockResponse()); - queryMap = new LinkedHashMap(); + queryMap = new LinkedHashMap<>(); queryMap.put("name", null); api.queryMapWithQueryParams("alice", queryMap); // null value for a query map key removes query parameter @@ -374,36 +372,36 @@ public void queryMapWithQueryParams() throws Exception { } @Test - public void queryMapValueStartingWithBrace() throws Exception { + void queryMapValueStartingWithBrace() throws Exception { final TestInterfaceAsync api = newAsyncBuilder().target("http://localhost:" + server.getPort()); server.enqueue(new MockResponse()); - Map queryMap = new LinkedHashMap(); + Map queryMap = new LinkedHashMap<>(); queryMap.put("name", "{alice"); api.queryMap(queryMap); assertThat(server.takeRequest()).hasPath("/?name=%7Balice"); server.enqueue(new MockResponse()); - queryMap = new LinkedHashMap(); + queryMap = new LinkedHashMap<>(); queryMap.put("{name", "alice"); api.queryMap(queryMap); assertThat(server.takeRequest()).hasPath("/?%7Bname=alice"); server.enqueue(new MockResponse()); - queryMap = new LinkedHashMap(); + queryMap = new LinkedHashMap<>(); queryMap.put("name", "%7Balice"); api.queryMapEncoded(queryMap); assertThat(server.takeRequest()).hasPath("/?name=%7Balice"); server.enqueue(new MockResponse()); - queryMap = new LinkedHashMap(); + queryMap = new LinkedHashMap<>(); queryMap.put("%7Bname", "%7Balice"); api.queryMapEncoded(queryMap); assertThat(server.takeRequest()).hasPath("/?%7Bname=%7Balice"); } @Test - public void queryMapPojoWithFullParams() throws Exception { + void queryMapPojoWithFullParams() throws Exception { final TestInterfaceAsync api = newAsyncBuilder().target("http://localhost:" + server.getPort()); final CustomPojo customPojo = new CustomPojo("Name", 3); @@ -415,7 +413,7 @@ public void queryMapPojoWithFullParams() throws Exception { } @Test - public void queryMapPojoWithPartialParams() throws Exception { + void queryMapPojoWithPartialParams() throws Exception { final TestInterfaceAsync api = newAsyncBuilder().target("http://localhost:" + server.getPort()); final CustomPojo customPojo = new CustomPojo("Name", null); @@ -428,7 +426,7 @@ public void queryMapPojoWithPartialParams() throws Exception { } @Test - public void queryMapPojoWithEmptyParams() throws Exception { + void queryMapPojoWithEmptyParams() throws Exception { final TestInterfaceAsync api = newAsyncBuilder().target("http://localhost:" + server.getPort()); final CustomPojo customPojo = new CustomPojo(null, null); @@ -439,24 +437,23 @@ public void queryMapPojoWithEmptyParams() throws Exception { } @Test - public void configKeyFormatsAsExpected() throws Exception { - assertEquals( - "TestInterfaceAsync#post()", - Feign.configKey( - TestInterfaceAsync.class, TestInterfaceAsync.class.getDeclaredMethod("post"))); - assertEquals( - "TestInterfaceAsync#uriParam(String,URI,String)", - Feign.configKey( - TestInterfaceAsync.class, - TestInterfaceAsync.class.getDeclaredMethod( - "uriParam", String.class, URI.class, String.class))); + void configKeyFormatsAsExpected() throws Exception { + assertThat( + Feign.configKey( + TestInterfaceAsync.class, TestInterfaceAsync.class.getDeclaredMethod("post"))) + .isEqualTo("TestInterfaceAsync#post()"); + assertThat( + Feign.configKey( + TestInterfaceAsync.class, + TestInterfaceAsync.class.getDeclaredMethod( + "uriParam", String.class, URI.class, String.class))) + .isEqualTo("TestInterfaceAsync#uriParam(String,URI,String)"); } @Test - public void configKeyUsesChildType() throws Exception { - assertEquals( - "List#iterator()", - Feign.configKey(List.class, Iterable.class.getDeclaredMethod("iterator"))); + void configKeyUsesChildType() throws Exception { + assertThat(Feign.configKey(List.class, Iterable.class.getDeclaredMethod("iterator"))) + .isEqualTo("List#iterator()"); } private T unwrap(CompletableFuture cf) throws Throwable { @@ -468,21 +465,20 @@ private T unwrap(CompletableFuture cf) throws Throwable { } @Test - public void canOverrideErrorDecoder() throws Throwable { + void canOverrideErrorDecoder() throws Throwable { server.enqueue(new MockResponse().setResponseCode(400).setBody("foo")); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("bad zone name"); final TestInterfaceAsync api = newAsyncBuilder() .errorDecoder(new IllegalArgumentExceptionOn400()) .target("http://localhost:" + server.getPort()); - unwrap(api.post()); + Throwable exception = assertThrows(IllegalArgumentException.class, () -> unwrap(api.post())); + assertThat(exception.getMessage()).contains("bad zone name"); } @Test - public void overrideTypeSpecificDecoder() throws Throwable { + void overrideTypeSpecificDecoder() throws Throwable { server.enqueue(new MockResponse().setBody("success!")); final TestInterfaceAsync api = @@ -490,14 +486,12 @@ public void overrideTypeSpecificDecoder() throws Throwable { .decoder((response, type) -> "fail") .target("http://localhost:" + server.getPort()); - assertEquals("fail", unwrap(api.post())); + assertThat(unwrap(api.post())).isEqualTo("fail"); } @Test - public void doesntRetryAfterResponseIsSent() throws Throwable { + void doesntRetryAfterResponseIsSent() throws Throwable { server.enqueue(new MockResponse().setBody("success!")); - thrown.expect(FeignException.class); - thrown.expectMessage("timeout reading POST http://"); final TestInterfaceAsync api = newAsyncBuilder() @@ -509,11 +503,12 @@ public void doesntRetryAfterResponseIsSent() throws Throwable { final CompletableFuture cf = api.post(); server.takeRequest(); - unwrap(cf); + Throwable exception = assertThrows(FeignException.class, () -> unwrap(cf)); + assertThat(exception.getMessage()).contains("timeout reading POST http://"); } @Test - public void throwsFeignExceptionIncludingBody() throws Throwable { + void throwsFeignExceptionIncludingBody() throws Throwable { server.enqueue(new MockResponse().setBody("success!")); final TestInterfaceAsync api = @@ -529,16 +524,16 @@ public void throwsFeignExceptionIncludingBody() throws Throwable { try { unwrap(cf); } catch (final FeignException e) { - Assertions.assertThat(e.getMessage()) + assertThat(e.getMessage()) .isEqualTo("timeout reading POST http://localhost:" + server.getPort() + "/"); - Assertions.assertThat(e.contentUTF8()).isEqualTo("Request body"); + assertThat(e.contentUTF8()).isEqualTo("Request body"); return; } - fail(); + fail(""); } @Test - public void throwsFeignExceptionWithoutBody() { + void throwsFeignExceptionWithoutBody() { server.enqueue(new MockResponse().setBody("success!")); final TestInterfaceAsync api = @@ -552,16 +547,16 @@ public void throwsFeignExceptionWithoutBody() { try { api.noContent(); } catch (final FeignException e) { - Assertions.assertThat(e.getMessage()) + assertThat(e.getMessage()) .isEqualTo("timeout reading POST http://localhost:" + server.getPort() + "/"); - Assertions.assertThat(e.contentUTF8()).isEqualTo(""); + assertThat(e.contentUTF8()).isEqualTo(""); } } @SuppressWarnings("deprecation") @Test - public void whenReturnTypeIsResponseNoErrorHandling() throws Throwable { - final Map> headers = new LinkedHashMap>(); + void whenReturnTypeIsResponseNoErrorHandling() throws Throwable { + final Map> headers = new LinkedHashMap<>(); headers.put("Location", Arrays.asList("http://bar.com")); final Response response = Response.builder() @@ -586,9 +581,8 @@ public void whenReturnTypeIsResponseNoErrorHandling() throws Throwable { } @Test - public void okIfDecodeRootCauseHasNoMessage() throws Throwable { + void okIfDecodeRootCauseHasNoMessage() throws Throwable { server.enqueue(new MockResponse().setBody("success!")); - thrown.expect(DecodeException.class); final TestInterfaceAsync api = newAsyncBuilder() @@ -598,14 +592,12 @@ public void okIfDecodeRootCauseHasNoMessage() throws Throwable { }) .target("http://localhost:" + server.getPort()); - unwrap(api.post()); + assertThrows(DecodeException.class, () -> unwrap(api.post())); } @Test - public void decodingExceptionGetWrappedInDismiss404Mode() throws Throwable { + void decodingExceptionGetWrappedInDismiss404Mode() throws Throwable { server.enqueue(new MockResponse().setResponseCode(404)); - thrown.expect(DecodeException.class); - thrown.expectCause(isA(NoSuchElementException.class)); final TestInterfaceAsync api = newAsyncBuilder() @@ -617,29 +609,33 @@ public void decodingExceptionGetWrappedInDismiss404Mode() throws Throwable { }) .target("http://localhost:" + server.getPort()); - unwrap(api.post()); + DecodeException exception = assertThrows(DecodeException.class, () -> unwrap(api.post())); + assertThat(exception).hasCauseInstanceOf(NoSuchElementException.class); } @Test - public void decodingDoesNotSwallow404ErrorsInDismiss404Mode() throws Throwable { - server.enqueue(new MockResponse().setResponseCode(404)); - thrown.expect(IllegalArgumentException.class); - - final TestInterfaceAsync api = - newAsyncBuilder() - .dismiss404() - .errorDecoder(new IllegalArgumentExceptionOn404()) - .target("http://localhost:" + server.getPort()); - - final CompletableFuture cf = api.queryMap(Collections.emptyMap()); - server.takeRequest(); - unwrap(cf); + void decodingDoesNotSwallow404ErrorsInDismiss404Mode() throws Throwable { + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy( + () -> { + server.enqueue(new MockResponse().setResponseCode(404)); + + final TestInterfaceAsync api = + newAsyncBuilder() + .dismiss404() + .errorDecoder(new IllegalArgumentExceptionOn404()) + .target("http://localhost:" + server.getPort()); + + final CompletableFuture cf = + api.queryMap(Collections.emptyMap()); + server.takeRequest(); + unwrap(cf); + }); } @Test - public void okIfEncodeRootCauseHasNoMessage() throws Throwable { + void okIfEncodeRootCauseHasNoMessage() throws Throwable { server.enqueue(new MockResponse().setBody("success!")); - thrown.expect(EncodeException.class); final TestInterfaceAsync api = newAsyncBuilder() @@ -649,45 +645,44 @@ public void okIfEncodeRootCauseHasNoMessage() throws Throwable { }) .target("http://localhost:" + server.getPort()); - unwrap(api.body(Arrays.asList("foo"))); + assertThrows(EncodeException.class, () -> unwrap(api.body(Arrays.asList("foo")))); } @Test - public void equalsHashCodeAndToStringWork() { + void equalsHashCodeAndToStringWork() { final Target t1 = - new HardCodedTarget(TestInterfaceAsync.class, "http://localhost:8080"); + new HardCodedTarget<>(TestInterfaceAsync.class, "http://localhost:8080"); final Target t2 = - new HardCodedTarget(TestInterfaceAsync.class, "http://localhost:8888"); + new HardCodedTarget<>(TestInterfaceAsync.class, "http://localhost:8888"); final Target t3 = - new HardCodedTarget( - OtherTestInterfaceAsync.class, "http://localhost:8080"); + new HardCodedTarget<>(OtherTestInterfaceAsync.class, "http://localhost:8080"); final TestInterfaceAsync i1 = newAsyncBuilder().target(t1); final TestInterfaceAsync i2 = newAsyncBuilder().target(t1); final TestInterfaceAsync i3 = newAsyncBuilder().target(t2); final OtherTestInterfaceAsync i4 = newAsyncBuilder().target(t3); - Assertions.assertThat(i1).isEqualTo(i2).isNotEqualTo(i3).isNotEqualTo(i4); + assertThat(i1).isEqualTo(i2).isNotEqualTo(i3).isNotEqualTo(i4); - Assertions.assertThat(i1.hashCode()) + assertThat(i1.hashCode()) .isEqualTo(i2.hashCode()) .isNotEqualTo(i3.hashCode()) .isNotEqualTo(i4.hashCode()); - Assertions.assertThat(i1.toString()) + assertThat(i1.toString()) .isEqualTo(i2.toString()) .isNotEqualTo(i3.toString()) .isNotEqualTo(i4.toString()); - Assertions.assertThat(t1).isNotEqualTo(i1); + assertThat(t1).isNotEqualTo(i1); - Assertions.assertThat(t1.hashCode()).isEqualTo(i1.hashCode()); + assertThat(t1.hashCode()).isEqualTo(i1.hashCode()); - Assertions.assertThat(t1.toString()).isEqualTo(i1.toString()); + assertThat(t1.toString()).isEqualTo(i1.toString()); } @SuppressWarnings("resource") @Test - public void decodeLogicSupportsByteArray() throws Throwable { + void decodeLogicSupportsByteArray() throws Throwable { final byte[] expectedResponse = {12, 34, 56}; server.enqueue(new MockResponse().setBody(new Buffer().write(expectedResponse))); @@ -697,11 +692,11 @@ public void decodeLogicSupportsByteArray() throws Throwable { new HardCodedTarget<>( OtherTestInterfaceAsync.class, "http://localhost:" + server.getPort())); - Assertions.assertThat(unwrap(api.binaryResponseBody())).containsExactly(expectedResponse); + assertThat(unwrap(api.binaryResponseBody())).containsExactly(expectedResponse); } @Test - public void encodeLogicSupportsByteArray() throws Exception { + void encodeLogicSupportsByteArray() throws Exception { final byte[] expectedRequest = {12, 34, 56}; server.enqueue(new MockResponse()); @@ -720,7 +715,7 @@ public void encodeLogicSupportsByteArray() throws Exception { } @Test - public void encodedQueryParam() throws Exception { + void encodedQueryParam() throws Exception { server.enqueue(new MockResponse()); final TestInterfaceAsync api = newAsyncBuilder().target("http://localhost:" + server.getPort()); @@ -743,12 +738,12 @@ private void checkCFCompletedSoon(CompletableFuture cf) { } @Test - public void responseMapperIsAppliedBeforeDelegate() throws IOException { + void responseMapperIsAppliedBeforeDelegate() throws IOException { final ResponseMappingDecoder decoder = new ResponseMappingDecoder(upperCaseResponseMapper(), new StringDecoder()); final String output = (String) decoder.decode(responseWithText("response"), String.class); - Assertions.assertThat(output).isEqualTo("RESPONSE"); + assertThat(output).isEqualTo("RESPONSE"); } private static TestInterfaceAsyncBuilder newAsyncBuilder() { @@ -756,17 +751,13 @@ private static TestInterfaceAsyncBuilder newAsyncBuilder() { } private ResponseMapper upperCaseResponseMapper() { - return new ResponseMapper() { - @SuppressWarnings("deprecation") - @Override - public Response map(Response response, Type type) { - try { - return response.toBuilder() - .body(Util.toString(response.body().asReader()).toUpperCase().getBytes()) - .build(); - } catch (final IOException e) { - throw new RuntimeException(e); - } + return (response, type) -> { + try { + return response.toBuilder() + .body(Util.toString(response.body().asReader()).toUpperCase().getBytes()) + .build(); + } catch (final IOException e) { + throw new RuntimeException(e); } }; } @@ -782,7 +773,7 @@ private Response responseWithText(String text) { } @Test - public void mapAndDecodeExecutesMapFunction() throws Throwable { + void mapAndDecodeExecutesMapFunction() throws Throwable { server.enqueue(new MockResponse().setBody("response!")); final TestInterfaceAsync api = @@ -790,11 +781,11 @@ public void mapAndDecodeExecutesMapFunction() throws Throwable { .mapAndDecode(upperCaseResponseMapper(), new StringDecoder()) .target(TestInterfaceAsync.class, "http://localhost:" + server.getPort()); - assertEquals("RESPONSE!", unwrap(api.post())); + assertThat(unwrap(api.post())).isEqualTo("RESPONSE!"); } @Test - public void beanQueryMapEncoderWithPrivateGetterIgnored() throws Exception { + void beanQueryMapEncoderWithPrivateGetterIgnored() throws Exception { final TestInterfaceAsync api = newAsyncBuilder() .queryMapEndcoder(new BeanQueryMapEncoder()) @@ -812,7 +803,7 @@ public void beanQueryMapEncoderWithPrivateGetterIgnored() throws Exception { } @Test - public void queryMap_with_child_pojo() throws Exception { + void queryMap_with_child_pojo() throws Exception { final TestInterfaceAsync api = newAsyncBuilder() .queryMapEndcoder(new FieldQueryMapEncoder()) @@ -834,7 +825,7 @@ public void queryMap_with_child_pojo() throws Exception { } @Test - public void beanQueryMapEncoderWithNullValueIgnored() throws Exception { + void beanQueryMapEncoderWithNullValueIgnored() throws Exception { final TestInterfaceAsync api = newAsyncBuilder() .queryMapEndcoder(new BeanQueryMapEncoder()) @@ -853,7 +844,7 @@ public void beanQueryMapEncoderWithNullValueIgnored() throws Exception { } @Test - public void beanQueryMapEncoderWithEmptyParams() throws Exception { + void beanQueryMapEncoderWithEmptyParams() throws Exception { final TestInterfaceAsync api = newAsyncBuilder() .queryMapEndcoder(new BeanQueryMapEncoder()) @@ -1032,16 +1023,11 @@ static final class TestInterfaceAsyncBuilder { .client(new Http2Client()) .decoder(new Decoder.Default()) .encoder( - new Encoder() { - - @SuppressWarnings("deprecation") - @Override - public void encode(Object object, Type bodyType, RequestTemplate template) { - if (object instanceof Map) { - template.body(new Gson().toJson(object)); - } else { - template.body(object.toString()); - } + (object, bodyType, template) -> { + if (object instanceof Map) { + template.body(new Gson().toJson(object)); + } else { + template.body(object.toString()); } }); @@ -1139,4 +1125,9 @@ public Instant instant() { return Instant.ofEpochMilli(millis); } } + + @AfterEach + void afterEachTest() throws IOException { + server.close(); + } } diff --git a/java11/src/test/java/feign/http2client/test/Http2ClientTest.java b/java11/src/test/java/feign/http2client/test/Http2ClientTest.java index 7c0c597b0..89c41be10 100644 --- a/java11/src/test/java/feign/http2client/test/Http2ClientTest.java +++ b/java11/src/test/java/feign/http2client/test/Http2ClientTest.java @@ -14,21 +14,27 @@ package feign.http2client.test; import static org.assertj.core.api.Assertions.assertThat; - -import feign.*; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import feign.Body; +import feign.Feign; +import feign.FeignException; +import feign.Headers; +import feign.Request; +import feign.RequestLine; +import feign.Response; +import feign.Retryer; import feign.client.AbstractClientTest; import feign.http2client.Http2Client; import java.io.IOException; import java.net.http.HttpTimeoutException; import java.util.concurrent.TimeUnit; -import okhttp3.mockwebserver.MockResponse; -import org.assertj.core.api.Assertions; -import org.hamcrest.CoreMatchers; -import org.junit.Ignore; -import org.junit.Test; +import mockwebserver3.MockResponse; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; /** Tests client-specific behavior, such as ensuring Content-Length is sent when specified. */ -@Ignore +@Disabled public class Http2ClientTest extends AbstractClientTest { public interface TestInterface { @@ -55,10 +61,10 @@ public interface TestInterface { @Override @Test - public void testPatch() throws Exception { + public void patch() throws Exception { final TestInterface api = newBuilder().target(TestInterface.class, "https://nghttp2.org/httpbin/"); - Assertions.assertThat(api.patch("")).contains("https://nghttp2.org/httpbin/patch"); + assertThat(api.patch("")).contains("https://nghttp2.org/httpbin/patch"); } @Override @@ -66,7 +72,7 @@ public void testPatch() throws Exception { public void noResponseBodyForPatch() { final TestInterface api = newBuilder().target(TestInterface.class, "https://nghttp2.org/httpbin/"); - Assertions.assertThat(api.patch()).contains("https://nghttp2.org/httpbin/patch"); + assertThat(api.patch()).contains("https://nghttp2.org/httpbin/patch"); } @Override @@ -85,7 +91,7 @@ public void reasonPhraseIsOptional() throws IOException, InterruptedException { } @Test - public void reasonPhraseInHeader() throws IOException, InterruptedException { + void reasonPhraseInHeader() throws IOException, InterruptedException { server.enqueue( new MockResponse() .addHeader("Reason-Phrase", "There is A reason") @@ -103,12 +109,12 @@ public void reasonPhraseInHeader() throws IOException, InterruptedException { @Override @Test - public void testVeryLongResponseNullLength() { + public void veryLongResponseNullLength() { // client is too smart to fall for a body that is 8 bytes long } @Test - public void timeoutTest() { + void timeoutTest() { server.enqueue(new MockResponse().setBody("foo").setBodyDelay(30, TimeUnit.SECONDS)); final TestInterface api = @@ -117,26 +123,24 @@ public void timeoutTest() { .options(new Request.Options(1, TimeUnit.SECONDS, 1, TimeUnit.SECONDS, true)) .target(TestInterface.class, server.url("/").toString()); - thrown.expect(FeignException.class); - thrown.expectCause(CoreMatchers.isA(HttpTimeoutException.class)); - - api.timeout(); + FeignException exception = assertThrows(FeignException.class, () -> api.timeout()); + assertThat(exception).hasCauseInstanceOf(HttpTimeoutException.class); } @Test - public void testGetWithRequestBody() { + void getWithRequestBody() { final TestInterface api = newBuilder().target(TestInterface.class, "https://nghttp2.org/httpbin/"); String result = api.getWithBody(); - Assertions.assertThat(result).contains("\"data\": \"some request body\""); + assertThat(result).contains("\"data\": \"some request body\""); } @Test - public void testDeleteWithRequestBody() { + void deleteWithRequestBody() { final TestInterface api = newBuilder().target(TestInterface.class, "https://nghttp2.org/httpbin/"); String result = api.deleteWithBody(); - Assertions.assertThat(result).contains("\"data\": \"some request body\""); + assertThat(result).contains("\"data\": \"some request body\""); } @Override diff --git a/jaxb-jakarta/src/test/java/feign/jaxb/JAXBCodecTest.java b/jaxb-jakarta/src/test/java/feign/jaxb/JAXBCodecTest.java index cb415e69f..216266acf 100644 --- a/jaxb-jakarta/src/test/java/feign/jaxb/JAXBCodecTest.java +++ b/jaxb-jakarta/src/test/java/feign/jaxb/JAXBCodecTest.java @@ -15,7 +15,8 @@ import static feign.Util.UTF_8; import static feign.assertj.FeignAssertions.assertThat; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; import feign.Request; import feign.Request.HttpMethod; @@ -41,18 +42,13 @@ import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; -import org.hamcrest.CoreMatchers; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; @SuppressWarnings("deprecation") -public class JAXBCodecTest { - - @Rule public final ExpectedException thrown = ExpectedException.none(); +class JAXBCodecTest { @Test - public void encodesXml() throws Exception { + void encodesXml() throws Exception { MockObject mock = new MockObject(); mock.value = "Test"; @@ -67,10 +63,7 @@ public void encodesXml() throws Exception { } @Test - public void doesntEncodeParameterizedTypes() throws Exception { - thrown.expect(UnsupportedOperationException.class); - thrown.expectMessage( - "JAXB only supports encoding raw types. Found java.util.Map"); + void doesntEncodeParameterizedTypes() throws Exception { class ParameterizedHolder { @@ -79,12 +72,19 @@ class ParameterizedHolder { Type parameterized = ParameterizedHolder.class.getDeclaredField("field").getGenericType(); RequestTemplate template = new RequestTemplate(); - new JAXBEncoder(new JAXBContextFactory.Builder().build()) - .encode(Collections.emptyMap(), parameterized, template); + Throwable exception = + assertThrows( + UnsupportedOperationException.class, + () -> + new JAXBEncoder(new JAXBContextFactory.Builder().build()) + .encode(Collections.emptyMap(), parameterized, template)); + assertThat(exception.getMessage()) + .contains( + "JAXB only supports encoding raw types. Found java.util.Map"); } @Test - public void encodesXmlWithCustomJAXBEncoding() throws Exception { + void encodesXmlWithCustomJAXBEncoding() throws Exception { JAXBContextFactory jaxbContextFactory = new JAXBContextFactory.Builder().withMarshallerJAXBEncoding("UTF-16").build(); @@ -103,7 +103,7 @@ public void encodesXmlWithCustomJAXBEncoding() throws Exception { } @Test - public void encodesXmlWithCustomJAXBSchemaLocation() throws Exception { + void encodesXmlWithCustomJAXBSchemaLocation() throws Exception { JAXBContextFactory jaxbContextFactory = new JAXBContextFactory.Builder() .withMarshallerSchemaLocation("http://apihost http://apihost/schema.xsd") @@ -126,7 +126,7 @@ public void encodesXmlWithCustomJAXBSchemaLocation() throws Exception { } @Test - public void encodesXmlWithCustomJAXBNoNamespaceSchemaLocation() throws Exception { + void encodesXmlWithCustomJAXBNoNamespaceSchemaLocation() throws Exception { JAXBContextFactory jaxbContextFactory = new JAXBContextFactory.Builder() .withMarshallerNoNamespaceSchemaLocation("http://apihost/schema.xsd") @@ -149,7 +149,7 @@ public void encodesXmlWithCustomJAXBNoNamespaceSchemaLocation() throws Exception } @Test - public void encodesXmlWithCustomJAXBFormattedOutput() { + void encodesXmlWithCustomJAXBFormattedOutput() { JAXBContextFactory jaxbContextFactory = new JAXBContextFactory.Builder().withMarshallerFormattedOutput(true).build(); @@ -177,7 +177,7 @@ public void encodesXmlWithCustomJAXBFormattedOutput() { } @Test - public void decodesXml() throws Exception { + void decodesXml() throws Exception { MockObject mock = new MockObject(); mock.value = "Test"; @@ -197,16 +197,11 @@ public void decodesXml() throws Exception { JAXBDecoder decoder = new JAXBDecoder(new JAXBContextFactory.Builder().build()); - assertEquals(mock, decoder.decode(response, MockObject.class)); + assertThat(decoder.decode(response, MockObject.class)).isEqualTo(mock); } @Test - public void doesntDecodeParameterizedTypes() throws Exception { - thrown.expect(feign.codec.DecodeException.class); - thrown.expectMessage( - "java.util.Map is an interface, and JAXB can't handle interfaces.\n" - + "\tthis problem is related to the following location:\n" - + "\t\tat java.util.Map"); + void doesntDecodeParameterizedTypes() throws Exception { class ParameterizedHolder { @@ -224,7 +219,17 @@ class ParameterizedHolder { .body("", UTF_8) .build(); - new JAXBDecoder(new JAXBContextFactory.Builder().build()).decode(response, parameterized); + Throwable exception = + assertThrows( + feign.codec.DecodeException.class, + () -> + new JAXBDecoder(new JAXBContextFactory.Builder().build()) + .decode(response, parameterized)); + assertThat(exception.getMessage()) + .contains( + "java.util.Map is an interface, and JAXB can't handle interfaces.\n" + + "\tthis problem is related to the following location:\n" + + "\t\tat java.util.Map"); } @XmlRootElement @@ -238,7 +243,7 @@ public void set(T t) { } @Test - public void decodeAnnotatedParameterizedTypes() throws Exception { + void decodeAnnotatedParameterizedTypes() throws Exception { JAXBContextFactory jaxbContextFactory = new JAXBContextFactory.Builder().withMarshallerFormattedOutput(true).build(); @@ -266,7 +271,7 @@ public void decodeAnnotatedParameterizedTypes() throws Exception { /** Enabled via {@link feign.Feign.Builder#dismiss404()} */ @Test - public void notFoundDecodesToEmpty() throws Exception { + void notFoundDecodesToEmpty() throws Exception { Response response = Response.builder() .status(404) @@ -283,10 +288,7 @@ public void notFoundDecodesToEmpty() throws Exception { } @Test - public void decodeThrowsExceptionWhenUnmarshallingFailsWithSetSchema() throws Exception { - thrown.expect(DecodeException.class); - thrown.expectCause(CoreMatchers.instanceOf(UnmarshalException.class)); - thrown.expectMessage("'Test' is not a valid value for 'integer'."); + void decodeThrowsExceptionWhenUnmarshallingFailsWithSetSchema() throws Exception { String mockXml = "" @@ -304,11 +306,17 @@ public void decodeThrowsExceptionWhenUnmarshallingFailsWithSetSchema() throws Ex JAXBContextFactory factory = new JAXBContextFactory.Builder().withUnmarshallerSchema(getMockIntObjSchema()).build(); - new JAXBDecoder(factory).decode(response, MockIntObject.class); + DecodeException exception = + assertThrows( + DecodeException.class, + () -> new JAXBDecoder(factory).decode(response, MockIntObject.class)); + assertThat(exception) + .hasCauseInstanceOf(UnmarshalException.class) + .hasMessageContaining("'Test' is not a valid value for 'integer'."); } @Test - public void decodesIgnoringErrorsWithEventHandler() throws Exception { + void decodesIgnoringErrorsWithEventHandler() throws Exception { String mockXml = "" + "Test"; @@ -328,27 +336,29 @@ public void decodesIgnoringErrorsWithEventHandler() throws Exception { .withUnmarshallerSchema(getMockIntObjSchema()) .withUnmarshallerEventHandler(event -> true) .build(); - assertEquals( - new MockIntObject(), new JAXBDecoder(factory).decode(response, MockIntObject.class)); + assertThat(new JAXBDecoder(factory).decode(response, MockIntObject.class)) + .isEqualTo(new MockIntObject()); } @Test - public void encodeThrowsExceptionWhenMarshallingFailsWithSetSchema() throws Exception { - thrown.expect(EncodeException.class); - thrown.expectCause(CoreMatchers.instanceOf(MarshalException.class)); - thrown.expectMessage("The content of element 'mockIntObject' is not complete."); - + void encodeThrowsExceptionWhenMarshallingFailsWithSetSchema() throws Exception { JAXBContextFactory jaxbContextFactory = new JAXBContextFactory.Builder().withMarshallerSchema(getMockIntObjSchema()).build(); Encoder encoder = new JAXBEncoder(jaxbContextFactory); RequestTemplate template = new RequestTemplate(); - encoder.encode(new MockIntObject(), MockIntObject.class, template); + EncodeException exception = + assertThrows( + EncodeException.class, + () -> encoder.encode(new MockIntObject(), MockIntObject.class, template)); + assertThat(exception) + .hasCauseInstanceOf(MarshalException.class) + .hasMessageContaining("The content of element 'mockIntObject' is not complete."); } @Test - public void encodesIgnoringErrorsWithEventHandler() throws Exception { + void encodesIgnoringErrorsWithEventHandler() throws Exception { JAXBContextFactory jaxbContextFactory = new JAXBContextFactory.Builder() .withMarshallerSchema(getMockIntObjSchema()) @@ -373,8 +383,12 @@ static class MockIntObject { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } MockIntObject that = (MockIntObject) o; return Objects.equals(value, that.value); } diff --git a/jaxb-jakarta/src/test/java/feign/jaxb/JAXBContextFactoryTest.java b/jaxb-jakarta/src/test/java/feign/jaxb/JAXBContextFactoryTest.java index c59186e7a..ed6a440c5 100644 --- a/jaxb-jakarta/src/test/java/feign/jaxb/JAXBContextFactoryTest.java +++ b/jaxb-jakarta/src/test/java/feign/jaxb/JAXBContextFactoryTest.java @@ -13,7 +13,7 @@ */ package feign.jaxb; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.assertThat; import feign.jaxb.mock.onepackage.AnotherMockedJAXBObject; import feign.jaxb.mock.onepackage.MockedJAXBObject; @@ -27,121 +27,119 @@ import javax.xml.XMLConstants; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class JAXBContextFactoryTest { +class JAXBContextFactoryTest { @Test - public void buildsMarshallerWithJAXBEncodingProperty() throws Exception { + void buildsMarshallerWithJAXBEncodingProperty() throws Exception { JAXBContextFactory factory = new JAXBContextFactory.Builder().withMarshallerJAXBEncoding("UTF-16").build(); Marshaller marshaller = factory.createMarshaller(Object.class); - assertEquals("UTF-16", marshaller.getProperty(Marshaller.JAXB_ENCODING)); + assertThat(marshaller.getProperty(Marshaller.JAXB_ENCODING)).isEqualTo("UTF-16"); } @Test - public void buildsMarshallerWithSchemaLocationProperty() throws Exception { + void buildsMarshallerWithSchemaLocationProperty() throws Exception { JAXBContextFactory factory = new JAXBContextFactory.Builder() .withMarshallerSchemaLocation("http://apihost http://apihost/schema.xsd") .build(); Marshaller marshaller = factory.createMarshaller(Object.class); - assertEquals( - "http://apihost http://apihost/schema.xsd", - marshaller.getProperty(Marshaller.JAXB_SCHEMA_LOCATION)); + assertThat(marshaller.getProperty(Marshaller.JAXB_SCHEMA_LOCATION)) + .isEqualTo("http://apihost http://apihost/schema.xsd"); } @Test - public void buildsMarshallerWithNoNamespaceSchemaLocationProperty() throws Exception { + void buildsMarshallerWithNoNamespaceSchemaLocationProperty() throws Exception { JAXBContextFactory factory = new JAXBContextFactory.Builder() .withMarshallerNoNamespaceSchemaLocation("http://apihost/schema.xsd") .build(); Marshaller marshaller = factory.createMarshaller(Object.class); - assertEquals( - "http://apihost/schema.xsd", - marshaller.getProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION)); + assertThat(marshaller.getProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION)) + .isEqualTo("http://apihost/schema.xsd"); } @Test - public void buildsMarshallerWithFormattedOutputProperty() throws Exception { + void buildsMarshallerWithFormattedOutputProperty() throws Exception { JAXBContextFactory factory = new JAXBContextFactory.Builder().withMarshallerFormattedOutput(true).build(); Marshaller marshaller = factory.createMarshaller(Object.class); - assertTrue((Boolean) marshaller.getProperty(Marshaller.JAXB_FORMATTED_OUTPUT)); + assertThat((Boolean) marshaller.getProperty(Marshaller.JAXB_FORMATTED_OUTPUT)).isTrue(); } @Test - public void buildsMarshallerWithFragmentProperty() throws Exception { + void buildsMarshallerWithFragmentProperty() throws Exception { JAXBContextFactory factory = new JAXBContextFactory.Builder().withMarshallerFragment(true).build(); Marshaller marshaller = factory.createMarshaller(Object.class); - assertTrue((Boolean) marshaller.getProperty(Marshaller.JAXB_FRAGMENT)); + assertThat((Boolean) marshaller.getProperty(Marshaller.JAXB_FRAGMENT)).isTrue(); } @Test - public void buildsMarshallerWithSchema() throws Exception { + void buildsMarshallerWithSchema() throws Exception { Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(); JAXBContextFactory factory = new JAXBContextFactory.Builder().withMarshallerSchema(schema).build(); Marshaller marshaller = factory.createMarshaller(Object.class); - assertSame(schema, marshaller.getSchema()); + assertThat(marshaller.getSchema()).isSameAs(schema); } @Test - public void buildsUnmarshallerWithSchema() throws Exception { + void buildsUnmarshallerWithSchema() throws Exception { Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(); JAXBContextFactory factory = new JAXBContextFactory.Builder().withUnmarshallerSchema(schema).build(); Unmarshaller unmarshaller = factory.createUnmarshaller(Object.class); - assertSame(schema, unmarshaller.getSchema()); + assertThat(unmarshaller.getSchema()).isSameAs(schema); } @Test - public void buildsMarshallerWithCustomEventHandler() throws Exception { + void buildsMarshallerWithCustomEventHandler() throws Exception { ValidationEventHandler handler = event -> false; JAXBContextFactory factory = new JAXBContextFactory.Builder().withMarshallerEventHandler(handler).build(); Marshaller marshaller = factory.createMarshaller(Object.class); - assertSame(handler, marshaller.getEventHandler()); + assertThat(marshaller.getEventHandler()).isSameAs(handler); } @Test - public void buildsMarshallerWithDefaultEventHandler() throws Exception { + void buildsMarshallerWithDefaultEventHandler() throws Exception { JAXBContextFactory factory = new JAXBContextFactory.Builder().build(); Marshaller marshaller = factory.createMarshaller(Object.class); - assertNotNull(marshaller.getEventHandler()); + assertThat(marshaller.getEventHandler()).isNotNull(); } @Test - public void buildsUnmarshallerWithCustomEventHandler() throws Exception { + void buildsUnmarshallerWithCustomEventHandler() throws Exception { ValidationEventHandler handler = event -> false; JAXBContextFactory factory = new JAXBContextFactory.Builder().withUnmarshallerEventHandler(handler).build(); Unmarshaller unmarshaller = factory.createUnmarshaller(Object.class); - assertSame(handler, unmarshaller.getEventHandler()); + assertThat(unmarshaller.getEventHandler()).isSameAs(handler); } @Test - public void buildsUnmarshallerWithDefaultEventHandler() throws Exception { + void buildsUnmarshallerWithDefaultEventHandler() throws Exception { JAXBContextFactory factory = new JAXBContextFactory.Builder().build(); Unmarshaller unmarshaller = factory.createUnmarshaller(Object.class); - assertNotNull(unmarshaller.getEventHandler()); + assertThat(unmarshaller.getEventHandler()).isNotNull(); } @Test - public void testPreloadCache() throws Exception { + void preloadCache() throws Exception { List> classes = Arrays.asList(String.class, Integer.class); JAXBContextFactory factory = new JAXBContextFactory.Builder().build(classes); @@ -149,14 +147,14 @@ public void testPreloadCache() throws Exception { Field f = factory.getClass().getDeclaredField("jaxbContexts"); // NoSuchFieldException f.setAccessible(true); Map internalCache = (Map) f.get(factory); // IllegalAccessException - assertFalse(internalCache.isEmpty()); - assertTrue(internalCache.size() == classes.size()); - assertNotNull(internalCache.get(new JAXBContextClassCacheKey(String.class))); - assertNotNull(internalCache.get(new JAXBContextClassCacheKey(Integer.class))); + assertThat(internalCache.isEmpty()).isFalse(); + assertThat(internalCache.size() == classes.size()).isTrue(); + assertThat(internalCache.get(new JAXBContextClassCacheKey(String.class))).isNotNull(); + assertThat(internalCache.get(new JAXBContextClassCacheKey(Integer.class))).isNotNull(); } @Test - public void testClassModeInstantiation() throws Exception { + void classModeInstantiation() throws Exception { List> classes = Arrays.asList(String.class, Integer.class); JAXBContextFactory factory = @@ -167,14 +165,14 @@ public void testClassModeInstantiation() throws Exception { Field f = factory.getClass().getDeclaredField("jaxbContexts"); // NoSuchFieldException f.setAccessible(true); Map internalCache = (Map) f.get(factory); // IllegalAccessException - assertFalse(internalCache.isEmpty()); - assertEquals(internalCache.size(), classes.size()); - assertNotNull(internalCache.get(new JAXBContextClassCacheKey(String.class))); - assertNotNull(internalCache.get(new JAXBContextClassCacheKey(Integer.class))); + assertThat(internalCache.isEmpty()).isFalse(); + assertThat(classes).hasSize(internalCache.size()); + assertThat(internalCache.get(new JAXBContextClassCacheKey(String.class))).isNotNull(); + assertThat(internalCache.get(new JAXBContextClassCacheKey(Integer.class))).isNotNull(); } @Test - public void testPackageModeInstantiationUsingSamePackage() throws Exception { + void packageModeInstantiationUsingSamePackage() throws Exception { JAXBContextFactory factory = new JAXBContextFactory.Builder() @@ -184,16 +182,17 @@ public void testPackageModeInstantiationUsingSamePackage() throws Exception { Field f = factory.getClass().getDeclaredField("jaxbContexts"); // NoSuchFieldException f.setAccessible(true); Map internalCache = (Map) f.get(factory); // IllegalAccessException - assertFalse(internalCache.isEmpty()); - assertEquals(1, internalCache.size()); - assertNotNull( - internalCache.get( - new JAXBContextPackageCacheKey( - "feign.jaxb.mock.onepackage", AnotherMockedJAXBObject.class.getClassLoader()))); + assertThat(internalCache.isEmpty()).isFalse(); + assertThat(internalCache).hasSize(1); + assertThat( + internalCache.get( + new JAXBContextPackageCacheKey( + "feign.jaxb.mock.onepackage", AnotherMockedJAXBObject.class.getClassLoader()))) + .isNotNull(); } @Test - public void testPackageModeInstantiationUsingMultiplePackages() throws Exception { + void packageModeInstantiationUsingMultiplePackages() throws Exception { JAXBContextFactory factory = new JAXBContextFactory.Builder() @@ -205,16 +204,18 @@ public void testPackageModeInstantiationUsingMultiplePackages() throws Exception Field f = factory.getClass().getDeclaredField("jaxbContexts"); // NoSuchFieldException f.setAccessible(true); Map internalCache = (Map) f.get(factory); // IllegalAccessException - assertFalse(internalCache.isEmpty()); - assertEquals(2, internalCache.size()); - assertNotNull( - internalCache.get( - new JAXBContextPackageCacheKey( - "feign.jaxb.mock.onepackage", MockedJAXBObject.class.getClassLoader()))); - assertNotNull( - internalCache.get( - new JAXBContextPackageCacheKey( - "feign.jaxb.mock.anotherpackage", - feign.jaxb.mock.anotherpackage.MockedJAXBObject.class.getClassLoader()))); + assertThat(internalCache.isEmpty()).isFalse(); + assertThat(internalCache).hasSize(2); + assertThat( + internalCache.get( + new JAXBContextPackageCacheKey( + "feign.jaxb.mock.onepackage", MockedJAXBObject.class.getClassLoader()))) + .isNotNull(); + assertThat( + internalCache.get( + new JAXBContextPackageCacheKey( + "feign.jaxb.mock.anotherpackage", + feign.jaxb.mock.anotherpackage.MockedJAXBObject.class.getClassLoader()))) + .isNotNull(); } } diff --git a/jaxb-jakarta/src/test/java/feign/jaxb/examples/IAMExample.java b/jaxb-jakarta/src/test/java/feign/jaxb/examples/IAMExample.java index 80e223fbd..b0fee8629 100644 --- a/jaxb-jakarta/src/test/java/feign/jaxb/examples/IAMExample.java +++ b/jaxb-jakarta/src/test/java/feign/jaxb/examples/IAMExample.java @@ -13,10 +13,18 @@ */ package feign.jaxb.examples; -import feign.*; +import feign.Feign; +import feign.Request; +import feign.RequestLine; +import feign.RequestTemplate; +import feign.Target; import feign.jaxb.JAXBContextFactory; import feign.jaxb.JAXBDecoder; -import jakarta.xml.bind.annotation.*; +import jakarta.xml.bind.annotation.XmlAccessType; +import jakarta.xml.bind.annotation.XmlAccessorType; +import jakarta.xml.bind.annotation.XmlElement; +import jakarta.xml.bind.annotation.XmlRootElement; +import jakarta.xml.bind.annotation.XmlType; public class IAMExample { diff --git a/jaxb/src/test/java/feign/jaxb/JAXBCodecTest.java b/jaxb/src/test/java/feign/jaxb/JAXBCodecTest.java index fa042cd38..5a045f9f1 100644 --- a/jaxb/src/test/java/feign/jaxb/JAXBCodecTest.java +++ b/jaxb/src/test/java/feign/jaxb/JAXBCodecTest.java @@ -15,7 +15,8 @@ import static feign.Util.UTF_8; import static feign.assertj.FeignAssertions.assertThat; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; import feign.Request; import feign.Request.HttpMethod; @@ -41,18 +42,13 @@ import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; -import org.hamcrest.CoreMatchers; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; @SuppressWarnings("deprecation") -public class JAXBCodecTest { - - @Rule public final ExpectedException thrown = ExpectedException.none(); +class JAXBCodecTest { @Test - public void encodesXml() throws Exception { + void encodesXml() throws Exception { MockObject mock = new MockObject(); mock.value = "Test"; @@ -67,10 +63,7 @@ public void encodesXml() throws Exception { } @Test - public void doesntEncodeParameterizedTypes() throws Exception { - thrown.expect(UnsupportedOperationException.class); - thrown.expectMessage( - "JAXB only supports encoding raw types. Found java.util.Map"); + void doesntEncodeParameterizedTypes() throws Exception { class ParameterizedHolder { @@ -79,12 +72,19 @@ class ParameterizedHolder { Type parameterized = ParameterizedHolder.class.getDeclaredField("field").getGenericType(); RequestTemplate template = new RequestTemplate(); - new JAXBEncoder(new JAXBContextFactory.Builder().build()) - .encode(Collections.emptyMap(), parameterized, template); + Throwable exception = + assertThrows( + UnsupportedOperationException.class, + () -> + new JAXBEncoder(new JAXBContextFactory.Builder().build()) + .encode(Collections.emptyMap(), parameterized, template)); + assertThat(exception.getMessage()) + .contains( + "JAXB only supports encoding raw types. Found java.util.Map"); } @Test - public void encodesXmlWithCustomJAXBEncoding() throws Exception { + void encodesXmlWithCustomJAXBEncoding() throws Exception { JAXBContextFactory jaxbContextFactory = new JAXBContextFactory.Builder().withMarshallerJAXBEncoding("UTF-16").build(); @@ -103,7 +103,7 @@ public void encodesXmlWithCustomJAXBEncoding() throws Exception { } @Test - public void encodesXmlWithCustomJAXBSchemaLocation() throws Exception { + void encodesXmlWithCustomJAXBSchemaLocation() throws Exception { JAXBContextFactory jaxbContextFactory = new JAXBContextFactory.Builder() .withMarshallerSchemaLocation("http://apihost http://apihost/schema.xsd") @@ -126,7 +126,7 @@ public void encodesXmlWithCustomJAXBSchemaLocation() throws Exception { } @Test - public void encodesXmlWithCustomJAXBNoNamespaceSchemaLocation() throws Exception { + void encodesXmlWithCustomJAXBNoNamespaceSchemaLocation() throws Exception { JAXBContextFactory jaxbContextFactory = new JAXBContextFactory.Builder() .withMarshallerNoNamespaceSchemaLocation("http://apihost/schema.xsd") @@ -149,7 +149,7 @@ public void encodesXmlWithCustomJAXBNoNamespaceSchemaLocation() throws Exception } @Test - public void encodesXmlWithCustomJAXBFormattedOutput() { + void encodesXmlWithCustomJAXBFormattedOutput() { JAXBContextFactory jaxbContextFactory = new JAXBContextFactory.Builder().withMarshallerFormattedOutput(true).build(); @@ -177,7 +177,7 @@ public void encodesXmlWithCustomJAXBFormattedOutput() { } @Test - public void decodesXml() throws Exception { + void decodesXml() throws Exception { MockObject mock = new MockObject(); mock.value = "Test"; @@ -197,16 +197,11 @@ public void decodesXml() throws Exception { JAXBDecoder decoder = new JAXBDecoder(new JAXBContextFactory.Builder().build()); - assertEquals(mock, decoder.decode(response, MockObject.class)); + assertThat(decoder.decode(response, MockObject.class)).isEqualTo(mock); } @Test - public void doesntDecodeParameterizedTypes() throws Exception { - thrown.expect(DecodeException.class); - thrown.expectMessage( - "java.util.Map is an interface, and JAXB can't handle interfaces.\n" - + "\tthis problem is related to the following location:\n" - + "\t\tat java.util.Map"); + void doesntDecodeParameterizedTypes() throws Exception { class ParameterizedHolder { @@ -224,7 +219,17 @@ class ParameterizedHolder { .body("", UTF_8) .build(); - new JAXBDecoder(new JAXBContextFactory.Builder().build()).decode(response, parameterized); + Throwable exception = + assertThrows( + DecodeException.class, + () -> + new JAXBDecoder(new JAXBContextFactory.Builder().build()) + .decode(response, parameterized)); + assertThat(exception.getMessage()) + .contains( + "java.util.Map is an interface, and JAXB can't handle interfaces.\n" + + "\tthis problem is related to the following location:\n" + + "\t\tat java.util.Map"); } @XmlRootElement @@ -238,7 +243,7 @@ public void set(T t) { } @Test - public void decodeAnnotatedParameterizedTypes() throws Exception { + void decodeAnnotatedParameterizedTypes() throws Exception { JAXBContextFactory jaxbContextFactory = new JAXBContextFactory.Builder().withMarshallerFormattedOutput(true).build(); @@ -266,7 +271,7 @@ public void decodeAnnotatedParameterizedTypes() throws Exception { /** Enabled via {@link feign.Feign.Builder#dismiss404()} */ @Test - public void notFoundDecodesToEmpty() throws Exception { + void notFoundDecodesToEmpty() throws Exception { Response response = Response.builder() .status(404) @@ -283,10 +288,7 @@ public void notFoundDecodesToEmpty() throws Exception { } @Test - public void decodeThrowsExceptionWhenUnmarshallingFailsWithSetSchema() throws Exception { - thrown.expect(DecodeException.class); - thrown.expectCause(CoreMatchers.instanceOf(UnmarshalException.class)); - thrown.expectMessage("'Test' is not a valid value for 'integer'."); + void decodeThrowsExceptionWhenUnmarshallingFailsWithSetSchema() throws Exception { String mockXml = "" @@ -304,11 +306,17 @@ public void decodeThrowsExceptionWhenUnmarshallingFailsWithSetSchema() throws Ex JAXBContextFactory factory = new JAXBContextFactory.Builder().withUnmarshallerSchema(getMockIntObjSchema()).build(); - new JAXBDecoder(factory).decode(response, MockIntObject.class); + DecodeException exception = + assertThrows( + DecodeException.class, + () -> new JAXBDecoder(factory).decode(response, MockIntObject.class)); + assertThat(exception) + .hasCauseInstanceOf(UnmarshalException.class) + .hasMessageContaining("'Test' is not a valid value for 'integer'."); } @Test - public void decodesIgnoringErrorsWithEventHandler() throws Exception { + void decodesIgnoringErrorsWithEventHandler() throws Exception { String mockXml = "" + "Test"; @@ -328,15 +336,12 @@ public void decodesIgnoringErrorsWithEventHandler() throws Exception { .withUnmarshallerSchema(getMockIntObjSchema()) .withUnmarshallerEventHandler(event -> true) .build(); - assertEquals( - new MockIntObject(), new JAXBDecoder(factory).decode(response, MockIntObject.class)); + assertThat(new JAXBDecoder(factory).decode(response, MockIntObject.class)) + .isEqualTo(new MockIntObject()); } @Test - public void encodeThrowsExceptionWhenMarshallingFailsWithSetSchema() throws Exception { - thrown.expect(EncodeException.class); - thrown.expectCause(CoreMatchers.instanceOf(MarshalException.class)); - thrown.expectMessage("The content of element 'mockIntObject' is not complete."); + void encodeThrowsExceptionWhenMarshallingFailsWithSetSchema() throws Exception { JAXBContextFactory jaxbContextFactory = new JAXBContextFactory.Builder().withMarshallerSchema(getMockIntObjSchema()).build(); @@ -344,11 +349,17 @@ public void encodeThrowsExceptionWhenMarshallingFailsWithSetSchema() throws Exce Encoder encoder = new JAXBEncoder(jaxbContextFactory); RequestTemplate template = new RequestTemplate(); - encoder.encode(new MockIntObject(), MockIntObject.class, template); + EncodeException exception = + assertThrows( + EncodeException.class, + () -> encoder.encode(new MockIntObject(), MockIntObject.class, template)); + assertThat(exception) + .hasCauseInstanceOf(MarshalException.class) + .hasMessageContaining("The content of element 'mockIntObject' is not complete."); } @Test - public void encodesIgnoringErrorsWithEventHandler() throws Exception { + void encodesIgnoringErrorsWithEventHandler() throws Exception { JAXBContextFactory jaxbContextFactory = new JAXBContextFactory.Builder() .withMarshallerSchema(getMockIntObjSchema()) @@ -373,8 +384,12 @@ static class MockIntObject { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } MockIntObject that = (MockIntObject) o; return Objects.equals(value, that.value); } diff --git a/jaxb/src/test/java/feign/jaxb/JAXBContextFactoryTest.java b/jaxb/src/test/java/feign/jaxb/JAXBContextFactoryTest.java index d4c3a7a97..9f242486d 100644 --- a/jaxb/src/test/java/feign/jaxb/JAXBContextFactoryTest.java +++ b/jaxb/src/test/java/feign/jaxb/JAXBContextFactoryTest.java @@ -13,7 +13,7 @@ */ package feign.jaxb; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.assertThat; import feign.jaxb.mock.onepackage.AnotherMockedJAXBObject; import feign.jaxb.mock.onepackage.MockedJAXBObject; @@ -27,121 +27,119 @@ import javax.xml.bind.ValidationEventHandler; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class JAXBContextFactoryTest { +class JAXBContextFactoryTest { @Test - public void buildsMarshallerWithJAXBEncodingProperty() throws Exception { + void buildsMarshallerWithJAXBEncodingProperty() throws Exception { JAXBContextFactory factory = new JAXBContextFactory.Builder().withMarshallerJAXBEncoding("UTF-16").build(); Marshaller marshaller = factory.createMarshaller(Object.class); - assertEquals("UTF-16", marshaller.getProperty(Marshaller.JAXB_ENCODING)); + assertThat(marshaller.getProperty(Marshaller.JAXB_ENCODING)).isEqualTo("UTF-16"); } @Test - public void buildsMarshallerWithSchemaLocationProperty() throws Exception { + void buildsMarshallerWithSchemaLocationProperty() throws Exception { JAXBContextFactory factory = new JAXBContextFactory.Builder() .withMarshallerSchemaLocation("http://apihost http://apihost/schema.xsd") .build(); Marshaller marshaller = factory.createMarshaller(Object.class); - assertEquals( - "http://apihost http://apihost/schema.xsd", - marshaller.getProperty(Marshaller.JAXB_SCHEMA_LOCATION)); + assertThat(marshaller.getProperty(Marshaller.JAXB_SCHEMA_LOCATION)) + .isEqualTo("http://apihost http://apihost/schema.xsd"); } @Test - public void buildsMarshallerWithNoNamespaceSchemaLocationProperty() throws Exception { + void buildsMarshallerWithNoNamespaceSchemaLocationProperty() throws Exception { JAXBContextFactory factory = new JAXBContextFactory.Builder() .withMarshallerNoNamespaceSchemaLocation("http://apihost/schema.xsd") .build(); Marshaller marshaller = factory.createMarshaller(Object.class); - assertEquals( - "http://apihost/schema.xsd", - marshaller.getProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION)); + assertThat(marshaller.getProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION)) + .isEqualTo("http://apihost/schema.xsd"); } @Test - public void buildsMarshallerWithFormattedOutputProperty() throws Exception { + void buildsMarshallerWithFormattedOutputProperty() throws Exception { JAXBContextFactory factory = new JAXBContextFactory.Builder().withMarshallerFormattedOutput(true).build(); Marshaller marshaller = factory.createMarshaller(Object.class); - assertTrue((Boolean) marshaller.getProperty(Marshaller.JAXB_FORMATTED_OUTPUT)); + assertThat((Boolean) marshaller.getProperty(Marshaller.JAXB_FORMATTED_OUTPUT)).isTrue(); } @Test - public void buildsMarshallerWithFragmentProperty() throws Exception { + void buildsMarshallerWithFragmentProperty() throws Exception { JAXBContextFactory factory = new JAXBContextFactory.Builder().withMarshallerFragment(true).build(); Marshaller marshaller = factory.createMarshaller(Object.class); - assertTrue((Boolean) marshaller.getProperty(Marshaller.JAXB_FRAGMENT)); + assertThat((Boolean) marshaller.getProperty(Marshaller.JAXB_FRAGMENT)).isTrue(); } @Test - public void buildsMarshallerWithSchema() throws Exception { + void buildsMarshallerWithSchema() throws Exception { Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(); JAXBContextFactory factory = new JAXBContextFactory.Builder().withMarshallerSchema(schema).build(); Marshaller marshaller = factory.createMarshaller(Object.class); - assertSame(schema, marshaller.getSchema()); + assertThat(marshaller.getSchema()).isSameAs(schema); } @Test - public void buildsUnmarshallerWithSchema() throws Exception { + void buildsUnmarshallerWithSchema() throws Exception { Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(); JAXBContextFactory factory = new JAXBContextFactory.Builder().withUnmarshallerSchema(schema).build(); Unmarshaller unmarshaller = factory.createUnmarshaller(Object.class); - assertSame(schema, unmarshaller.getSchema()); + assertThat(unmarshaller.getSchema()).isSameAs(schema); } @Test - public void buildsMarshallerWithCustomEventHandler() throws Exception { + void buildsMarshallerWithCustomEventHandler() throws Exception { ValidationEventHandler handler = event -> false; JAXBContextFactory factory = new JAXBContextFactory.Builder().withMarshallerEventHandler(handler).build(); Marshaller marshaller = factory.createMarshaller(Object.class); - assertSame(handler, marshaller.getEventHandler()); + assertThat(marshaller.getEventHandler()).isSameAs(handler); } @Test - public void buildsMarshallerWithDefaultEventHandler() throws Exception { + void buildsMarshallerWithDefaultEventHandler() throws Exception { JAXBContextFactory factory = new JAXBContextFactory.Builder().build(); Marshaller marshaller = factory.createMarshaller(Object.class); - assertNotNull(marshaller.getEventHandler()); + assertThat(marshaller.getEventHandler()).isNotNull(); } @Test - public void buildsUnmarshallerWithCustomEventHandler() throws Exception { + void buildsUnmarshallerWithCustomEventHandler() throws Exception { ValidationEventHandler handler = event -> false; JAXBContextFactory factory = new JAXBContextFactory.Builder().withUnmarshallerEventHandler(handler).build(); Unmarshaller unmarshaller = factory.createUnmarshaller(Object.class); - assertSame(handler, unmarshaller.getEventHandler()); + assertThat(unmarshaller.getEventHandler()).isSameAs(handler); } @Test - public void buildsUnmarshallerWithDefaultEventHandler() throws Exception { + void buildsUnmarshallerWithDefaultEventHandler() throws Exception { JAXBContextFactory factory = new JAXBContextFactory.Builder().build(); Unmarshaller unmarshaller = factory.createUnmarshaller(Object.class); - assertNotNull(unmarshaller.getEventHandler()); + assertThat(unmarshaller.getEventHandler()).isNotNull(); } @Test - public void testPreloadCache() throws Exception { + void preloadCache() throws Exception { List> classes = Arrays.asList(String.class, Integer.class); JAXBContextFactory factory = new JAXBContextFactory.Builder().build(classes); @@ -149,14 +147,14 @@ public void testPreloadCache() throws Exception { Field f = factory.getClass().getDeclaredField("jaxbContexts"); // NoSuchFieldException f.setAccessible(true); Map internalCache = (Map) f.get(factory); // IllegalAccessException - assertFalse(internalCache.isEmpty()); - assertTrue(internalCache.size() == classes.size()); - assertNotNull(internalCache.get(new JAXBContextClassCacheKey(String.class))); - assertNotNull(internalCache.get(new JAXBContextClassCacheKey(Integer.class))); + assertThat(internalCache.isEmpty()).isFalse(); + assertThat(internalCache.size() == classes.size()).isTrue(); + assertThat(internalCache.get(new JAXBContextClassCacheKey(String.class))).isNotNull(); + assertThat(internalCache.get(new JAXBContextClassCacheKey(Integer.class))).isNotNull(); } @Test - public void testClassModeInstantiation() throws Exception { + void classModeInstantiation() throws Exception { List> classes = Arrays.asList(String.class, Integer.class); JAXBContextFactory factory = @@ -167,14 +165,14 @@ public void testClassModeInstantiation() throws Exception { Field f = factory.getClass().getDeclaredField("jaxbContexts"); // NoSuchFieldException f.setAccessible(true); Map internalCache = (Map) f.get(factory); // IllegalAccessException - assertFalse(internalCache.isEmpty()); - assertEquals(internalCache.size(), classes.size()); - assertNotNull(internalCache.get(new JAXBContextClassCacheKey(String.class))); - assertNotNull(internalCache.get(new JAXBContextClassCacheKey(Integer.class))); + assertThat(internalCache.isEmpty()).isFalse(); + assertThat(classes).hasSize(internalCache.size()); + assertThat(internalCache.get(new JAXBContextClassCacheKey(String.class))).isNotNull(); + assertThat(internalCache.get(new JAXBContextClassCacheKey(Integer.class))).isNotNull(); } @Test - public void testPackageModeInstantiationUsingSamePackage() throws Exception { + void packageModeInstantiationUsingSamePackage() throws Exception { JAXBContextFactory factory = new JAXBContextFactory.Builder() @@ -184,16 +182,17 @@ public void testPackageModeInstantiationUsingSamePackage() throws Exception { Field f = factory.getClass().getDeclaredField("jaxbContexts"); // NoSuchFieldException f.setAccessible(true); Map internalCache = (Map) f.get(factory); // IllegalAccessException - assertFalse(internalCache.isEmpty()); - assertEquals(1, internalCache.size()); - assertNotNull( - internalCache.get( - new JAXBContextPackageCacheKey( - "feign.jaxb.mock.onepackage", AnotherMockedJAXBObject.class.getClassLoader()))); + assertThat(internalCache.isEmpty()).isFalse(); + assertThat(internalCache).hasSize(1); + assertThat( + internalCache.get( + new JAXBContextPackageCacheKey( + "feign.jaxb.mock.onepackage", AnotherMockedJAXBObject.class.getClassLoader()))) + .isNotNull(); } @Test - public void testPackageModeInstantiationUsingMultiplePackages() throws Exception { + void packageModeInstantiationUsingMultiplePackages() throws Exception { JAXBContextFactory factory = new JAXBContextFactory.Builder() @@ -205,16 +204,18 @@ public void testPackageModeInstantiationUsingMultiplePackages() throws Exception Field f = factory.getClass().getDeclaredField("jaxbContexts"); // NoSuchFieldException f.setAccessible(true); Map internalCache = (Map) f.get(factory); // IllegalAccessException - assertFalse(internalCache.isEmpty()); - assertEquals(2, internalCache.size()); - assertNotNull( - internalCache.get( - new JAXBContextPackageCacheKey( - "feign.jaxb.mock.onepackage", MockedJAXBObject.class.getClassLoader()))); - assertNotNull( - internalCache.get( - new JAXBContextPackageCacheKey( - "feign.jaxb.mock.anotherpackage", - feign.jaxb.mock.anotherpackage.MockedJAXBObject.class.getClassLoader()))); + assertThat(internalCache.isEmpty()).isFalse(); + assertThat(internalCache).hasSize(2); + assertThat( + internalCache.get( + new JAXBContextPackageCacheKey( + "feign.jaxb.mock.onepackage", MockedJAXBObject.class.getClassLoader()))) + .isNotNull(); + assertThat( + internalCache.get( + new JAXBContextPackageCacheKey( + "feign.jaxb.mock.anotherpackage", + feign.jaxb.mock.anotherpackage.MockedJAXBObject.class.getClassLoader()))) + .isNotNull(); } } diff --git a/jaxrs/src/test/java/feign/jaxrs/JAXRSContractTestSupport.java b/jaxrs/src/test/java/feign/jaxrs/JAXRSContractTestSupport.java index 98e24321e..06aa831d7 100644 --- a/jaxrs/src/test/java/feign/jaxrs/JAXRSContractTestSupport.java +++ b/jaxrs/src/test/java/feign/jaxrs/JAXRSContractTestSupport.java @@ -17,6 +17,7 @@ import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.data.MapEntry.entry; +import static org.junit.jupiter.api.Assertions.assertThrows; import feign.MethodMetadata; import java.net.URI; @@ -24,9 +25,7 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; public abstract class JAXRSContractTestSupport { @@ -37,11 +36,10 @@ protected abstract MethodMetadata parseAndValidateMetadata( protected abstract E createContract(); - @Rule public final ExpectedException thrown = ExpectedException.none(); protected E contract = createContract(); @Test - public void httpMethods() throws Exception { + void httpMethods() throws Exception { assertThat(parseAndValidateMetadata(methodsClass(), "post").template()).hasMethod("POST"); assertThat(parseAndValidateMetadata(methodsClass(), "put").template()).hasMethod("PUT"); @@ -52,14 +50,14 @@ public void httpMethods() throws Exception { } @Test - public void customMethodWithoutPath() throws Exception { + void customMethodWithoutPath() throws Exception { assertThat(parseAndValidateMetadata(customMethodClass(), "patch").template()) .hasMethod("PATCH") .hasUrl("/"); } @Test - public void queryParamsInPathExtract() throws Exception { + void queryParamsInPathExtract() throws Exception { assertThat(parseAndValidateMetadata(withQueryParamsInPathClass(), "none").template()) .hasPath("/") .hasQueries(); @@ -88,7 +86,7 @@ public void queryParamsInPathExtract() throws Exception { } @Test - public void producesAddsAcceptHeader() throws Exception { + void producesAddsAcceptHeader() throws Exception { final MethodMetadata md = parseAndValidateMetadata(producesAndConsumesClass(), "produces"); /* multiple @Produces annotations should be additive */ @@ -99,7 +97,7 @@ public void producesAddsAcceptHeader() throws Exception { } @Test - public void producesMultipleAddsAcceptHeader() throws Exception { + void producesMultipleAddsAcceptHeader() throws Exception { final MethodMetadata md = parseAndValidateMetadata(producesAndConsumesClass(), "producesMultiple"); @@ -110,23 +108,27 @@ public void producesMultipleAddsAcceptHeader() throws Exception { } @Test - public void producesNada() throws Exception { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Produces.value() was empty on ProducesAndConsumes#producesNada"); - - parseAndValidateMetadata(producesAndConsumesClass(), "producesNada"); + void producesNada() throws Exception { + Throwable exception = + assertThrows( + IllegalStateException.class, + () -> parseAndValidateMetadata(producesAndConsumesClass(), "producesNada")); + assertThat(exception.getMessage()) + .contains("Produces.value() was empty on ProducesAndConsumes#producesNada"); } @Test - public void producesEmpty() throws Exception { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Produces.value() was empty on ProducesAndConsumes#producesEmpty"); - - parseAndValidateMetadata(producesAndConsumesClass(), "producesEmpty"); + void producesEmpty() throws Exception { + Throwable exception = + assertThrows( + IllegalStateException.class, + () -> parseAndValidateMetadata(producesAndConsumesClass(), "producesEmpty")); + assertThat(exception.getMessage()) + .contains("Produces.value() was empty on ProducesAndConsumes#producesEmpty"); } @Test - public void consumesAddsContentTypeHeader() throws Exception { + void consumesAddsContentTypeHeader() throws Exception { final MethodMetadata md = parseAndValidateMetadata(producesAndConsumesClass(), "consumes"); /* multiple @Consumes annotations are additive */ @@ -136,7 +138,7 @@ public void consumesAddsContentTypeHeader() throws Exception { } @Test - public void consumesMultipleAddsContentTypeHeader() throws Exception { + void consumesMultipleAddsContentTypeHeader() throws Exception { final MethodMetadata md = parseAndValidateMetadata(producesAndConsumesClass(), "consumesMultiple"); @@ -147,23 +149,27 @@ public void consumesMultipleAddsContentTypeHeader() throws Exception { } @Test - public void consumesNada() throws Exception { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Consumes.value() was empty on ProducesAndConsumes#consumesNada"); - - parseAndValidateMetadata(producesAndConsumesClass(), "consumesNada"); + void consumesNada() throws Exception { + Throwable exception = + assertThrows( + IllegalStateException.class, + () -> parseAndValidateMetadata(producesAndConsumesClass(), "consumesNada")); + assertThat(exception.getMessage()) + .contains("Consumes.value() was empty on ProducesAndConsumes#consumesNada"); } @Test - public void consumesEmpty() throws Exception { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Consumes.value() was empty on ProducesAndConsumes#consumesEmpty"); - - parseAndValidateMetadata(producesAndConsumesClass(), "consumesEmpty"); + void consumesEmpty() throws Exception { + Throwable exception = + assertThrows( + IllegalStateException.class, + () -> parseAndValidateMetadata(producesAndConsumesClass(), "consumesEmpty")); + assertThat(exception.getMessage()) + .contains("Consumes.value() was empty on ProducesAndConsumes#consumesEmpty"); } @Test - public void producesAndConsumesOnClassAddsHeader() throws Exception { + void producesAndConsumesOnClassAddsHeader() throws Exception { final MethodMetadata md = parseAndValidateMetadata(producesAndConsumesClass(), "producesAndConsumes"); @@ -174,7 +180,7 @@ public void producesAndConsumesOnClassAddsHeader() throws Exception { } @Test - public void bodyParamIsGeneric() throws Exception { + void bodyParamIsGeneric() throws Exception { final MethodMetadata md = parseAndValidateMetadata(bodyParamsClass(), "post", List.class); assertThat(md.bodyIndex()).isEqualTo(0); @@ -183,26 +189,27 @@ public void bodyParamIsGeneric() throws Exception { } @Test - public void tooManyBodies() throws Exception { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Method has too many Body"); - - parseAndValidateMetadata(bodyParamsClass(), "tooMany", List.class, List.class); + void tooManyBodies() throws Exception { + Throwable exception = + assertThrows( + IllegalStateException.class, + () -> parseAndValidateMetadata(bodyParamsClass(), "tooMany", List.class, List.class)); + assertThat(exception.getMessage()).contains("Method has too many Body"); } @Test - public void emptyPathOnType() throws Exception { + void emptyPathOnType() throws Exception { assertThat(parseAndValidateMetadata(emptyPathOnTypeClass(), "base").template()).hasUrl("/"); } @Test - public void emptyPathOnTypeSpecific() throws Exception { + void emptyPathOnTypeSpecific() throws Exception { assertThat(parseAndValidateMetadata(emptyPathOnTypeClass(), "get").template()) .hasUrl("/specific"); } @Test - public void parsePathMethod() throws Exception { + void parsePathMethod() throws Exception { assertThat(parseAndValidateMetadata(pathOnTypeClass(), "base").template()).hasUrl("/base"); assertThat(parseAndValidateMetadata(pathOnTypeClass(), "get").template()) @@ -210,20 +217,21 @@ public void parsePathMethod() throws Exception { } @Test - public void emptyPathOnMethod() throws Exception { + void emptyPathOnMethod() throws Exception { assertThat(parseAndValidateMetadata(pathOnTypeClass(), "emptyPath").template()).hasUrl("/base"); } @Test - public void emptyPathParam() throws Exception { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("PathParam.value() was empty on parameter 0"); - - parseAndValidateMetadata(pathOnTypeClass(), "emptyPathParam", String.class); + void emptyPathParam() throws Exception { + Throwable exception = + assertThrows( + IllegalStateException.class, + () -> parseAndValidateMetadata(pathOnTypeClass(), "emptyPathParam", String.class)); + assertThat(exception.getMessage()).contains("PathParam.value() was empty on parameter 0"); } @Test - public void pathParamWithSpaces() throws Exception { + void pathParamWithSpaces() throws Exception { assertThat( parseAndValidateMetadata(pathOnTypeClass(), "pathParamWithSpaces", String.class) .template()) @@ -231,7 +239,7 @@ public void pathParamWithSpaces() throws Exception { } @Test - public void regexPathOnMethodOrType() throws Exception { + void regexPathOnMethodOrType() throws Exception { assertThat( parseAndValidateMetadata(pathOnTypeClass(), "pathParamWithRegex", String.class) .template()) @@ -254,7 +262,7 @@ public void regexPathOnMethodOrType() throws Exception { } @Test - public void withPathAndURIParams() throws Exception { + void withPathAndURIParams() throws Exception { final MethodMetadata md = parseAndValidateMetadata( withURIParamClass(), "uriParam", String.class, URI.class, String.class); @@ -269,7 +277,7 @@ public void withPathAndURIParams() throws Exception { } @Test - public void pathAndQueryParams() throws Exception { + void pathAndQueryParams() throws Exception { final MethodMetadata md = parseAndValidateMetadata( withPathAndQueryParamsClass(), @@ -287,15 +295,16 @@ public void pathAndQueryParams() throws Exception { } @Test - public void emptyQueryParam() throws Exception { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("QueryParam.value() was empty on parameter 0"); - - parseAndValidateMetadata(withPathAndQueryParamsClass(), "empty", String.class); + void emptyQueryParam() throws Exception { + Throwable exception = + assertThrows( + IllegalStateException.class, + () -> parseAndValidateMetadata(withPathAndQueryParamsClass(), "empty", String.class)); + assertThat(exception.getMessage()).contains("QueryParam.value() was empty on parameter 0"); } @Test - public void formParamsParseIntoIndexToName() throws Exception { + void formParamsParseIntoIndexToName() throws Exception { final MethodMetadata md = parseAndValidateMetadata( formParamsClass(), "login", String.class, String.class, String.class); @@ -311,7 +320,7 @@ public void formParamsParseIntoIndexToName() throws Exception { /** Body type is only for the body param. */ @Test - public void formParamsDoesNotSetBodyType() throws Exception { + void formParamsDoesNotSetBodyType() throws Exception { final MethodMetadata md = parseAndValidateMetadata( formParamsClass(), "login", String.class, String.class, String.class); @@ -320,15 +329,16 @@ public void formParamsDoesNotSetBodyType() throws Exception { } @Test - public void emptyFormParam() throws Exception { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("FormParam.value() was empty on parameter 0"); - - parseAndValidateMetadata(formParamsClass(), "emptyFormParam", String.class); + void emptyFormParam() throws Exception { + Throwable exception = + assertThrows( + IllegalStateException.class, + () -> parseAndValidateMetadata(formParamsClass(), "emptyFormParam", String.class)); + assertThat(exception.getMessage()).contains("FormParam.value() was empty on parameter 0"); } @Test - public void headerParamsParseIntoIndexToName() throws Exception { + void headerParamsParseIntoIndexToName() throws Exception { final MethodMetadata md = parseAndValidateMetadata(headerParamsClass(), "logout", String.class); assertThat(md.template()).hasHeaders(entry("Auth-Token", asList("{Auth-Token}"))); @@ -337,45 +347,46 @@ public void headerParamsParseIntoIndexToName() throws Exception { } @Test - public void emptyHeaderParam() throws Exception { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("HeaderParam.value() was empty on parameter 0"); - - parseAndValidateMetadata(headerParamsClass(), "emptyHeaderParam", String.class); + void emptyHeaderParam() throws Exception { + Throwable exception = + assertThrows( + IllegalStateException.class, + () -> parseAndValidateMetadata(headerParamsClass(), "emptyHeaderParam", String.class)); + assertThat(exception.getMessage()).contains("HeaderParam.value() was empty on parameter 0"); } @Test - public void pathsWithoutSlashesParseCorrectly() throws Exception { + void pathsWithoutSlashesParseCorrectly() throws Exception { assertThat(parseAndValidateMetadata(pathsWithoutAnySlashesClass(), "get").template()) .hasUrl("/base/specific"); } @Test - public void pathsWithSomeSlashesParseCorrectly() throws Exception { + void pathsWithSomeSlashesParseCorrectly() throws Exception { assertThat(parseAndValidateMetadata(pathsWithSomeSlashesClass(), "get").template()) .hasUrl("/base/specific"); } @Test - public void pathsWithSomeOtherSlashesParseCorrectly() throws Exception { + void pathsWithSomeOtherSlashesParseCorrectly() throws Exception { assertThat(parseAndValidateMetadata(pathsWithSomeOtherSlashesClass(), "get").template()) .hasUrl("/base/specific"); } @Test - public void classWithRootPathParsesCorrectly() throws Exception { + void classWithRootPathParsesCorrectly() throws Exception { assertThat(parseAndValidateMetadata(classRootPathClass(), "get").template()) .hasUrl("/specific"); } @Test - public void classPathWithTrailingSlashParsesCorrectly() throws Exception { + void classPathWithTrailingSlashParsesCorrectly() throws Exception { assertThat(parseAndValidateMetadata(classPathWithTrailingSlashClass(), "get").template()) .hasUrl("/base/specific"); } @Test - public void methodPathWithoutLeadingSlashParsesCorrectly() throws Exception { + void methodPathWithoutLeadingSlashParsesCorrectly() throws Exception { assertThat( parseAndValidateMetadata(methodWithFirstPathThenGetWithoutLeadingSlashClass(), "get") .template()) @@ -383,7 +394,7 @@ public void methodPathWithoutLeadingSlashParsesCorrectly() throws Exception { } @Test - public void producesWithHeaderParamContainAllHeaders() throws Exception { + void producesWithHeaderParamContainAllHeaders() throws Exception { assertThat( parseAndValidateMetadata( mixedAnnotationsClass(), diff --git a/jaxrs2/pom.xml b/jaxrs2/pom.xml index e0f37c85d..f3cde09e8 100644 --- a/jaxrs2/pom.xml +++ b/jaxrs2/pom.xml @@ -94,14 +94,10 @@ 2.41 test + com.squareup.okhttp3 - mockwebserver - test - - - org.hamcrest - hamcrest + mockwebserver3-junit5 test diff --git a/jaxrs2/src/test/java/feign/jaxrs2/JAXRS2ContractTest.java b/jaxrs2/src/test/java/feign/jaxrs2/JAXRS2ContractTest.java index c691c33d8..b03281ab7 100644 --- a/jaxrs2/src/test/java/feign/jaxrs2/JAXRS2ContractTest.java +++ b/jaxrs2/src/test/java/feign/jaxrs2/JAXRS2ContractTest.java @@ -19,18 +19,24 @@ import feign.jaxrs.JAXRSContract; import feign.jaxrs.JAXRSContractTest; import feign.jaxrs2.JAXRS2ContractTest.Jaxrs2Internals.Input; -import javax.ws.rs.*; +import javax.ws.rs.BeanParam; +import javax.ws.rs.FormParam; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.QueryParam; import javax.ws.rs.container.AsyncResponse; import javax.ws.rs.container.Suspended; import javax.ws.rs.core.Context; import javax.ws.rs.core.UriInfo; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests interfaces defined per {@link JAXRS2Contract} are interpreted into expected {@link feign * .RequestTemplate template} instances. */ -public class JAXRS2ContractTest extends JAXRSContractTest { +class JAXRS2ContractTest extends JAXRSContractTest { @Override protected JAXRSContract createContract() { @@ -38,7 +44,7 @@ protected JAXRSContract createContract() { } @Test - public void injectJaxrsInternals() throws Exception { + void injectJaxrsInternals() throws Exception { final MethodMetadata methodMetadata = parseAndValidateMetadata( Jaxrs2Internals.class, "inject", AsyncResponse.class, UriInfo.class); @@ -46,7 +52,7 @@ public void injectJaxrsInternals() throws Exception { } @Test - public void injectBeanParam() throws Exception { + void injectBeanParam() throws Exception { final MethodMetadata methodMetadata = parseAndValidateMetadata(Jaxrs2Internals.class, "beanParameters", Input.class); assertThat(methodMetadata.template()).noRequestBody(); diff --git a/jaxrs2/src/test/java/feign/jaxrs2/JAXRS2ContractWithBeanParamSupportTest.java b/jaxrs2/src/test/java/feign/jaxrs2/JAXRS2ContractWithBeanParamSupportTest.java index 4a2812d75..11a5aa930 100644 --- a/jaxrs2/src/test/java/feign/jaxrs2/JAXRS2ContractWithBeanParamSupportTest.java +++ b/jaxrs2/src/test/java/feign/jaxrs2/JAXRS2ContractWithBeanParamSupportTest.java @@ -15,24 +15,32 @@ import static feign.assertj.FeignAssertions.assertThat; import static java.util.Arrays.asList; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.data.MapEntry.entry; import feign.MethodMetadata; import feign.jaxrs.JAXRSContract; import feign.jaxrs.JAXRSContractTest; import feign.jaxrs2.JAXRS2ContractWithBeanParamSupportTest.Jaxrs2Internals.BeanParamInput; -import javax.ws.rs.*; +import javax.ws.rs.BeanParam; +import javax.ws.rs.FormParam; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.QueryParam; import javax.ws.rs.container.AsyncResponse; import javax.ws.rs.container.Suspended; import javax.ws.rs.core.Context; import javax.ws.rs.core.UriInfo; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests interfaces defined per {@link JAXRS2Contract} are interpreted into expected {@link feign * .RequestTemplate template} instances. */ -public class JAXRS2ContractWithBeanParamSupportTest extends JAXRSContractTest { +class JAXRS2ContractWithBeanParamSupportTest extends JAXRSContractTest { @Override protected JAXRSContract createContract() { @@ -40,7 +48,7 @@ protected JAXRSContract createContract() { } @Test - public void injectJaxrsInternals() throws Exception { + void injectJaxrsInternals() throws Exception { final MethodMetadata methodMetadata = parseAndValidateMetadata( Jaxrs2Internals.class, "inject", AsyncResponse.class, UriInfo.class); @@ -48,7 +56,7 @@ public void injectJaxrsInternals() throws Exception { } @Test - public void injectBeanParam() throws Exception { + void injectBeanParam() throws Exception { final MethodMetadata methodMetadata = parseAndValidateMetadata(Jaxrs2Internals.class, "beanParameters", BeanParamInput.class); assertThat(methodMetadata.template()).noRequestBody(); diff --git a/jaxrs2/src/test/java/feign/jaxrs2/JAXRSClientTest.java b/jaxrs2/src/test/java/feign/jaxrs2/JAXRSClientTest.java index 1e65ffb1f..018dd8bec 100644 --- a/jaxrs2/src/test/java/feign/jaxrs2/JAXRSClientTest.java +++ b/jaxrs2/src/test/java/feign/jaxrs2/JAXRSClientTest.java @@ -15,22 +15,29 @@ import static feign.Util.UTF_8; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assume.assumeFalse; +import static org.junit.jupiter.api.Assumptions.assumeFalse; -import feign.*; +import feign.Feign; import feign.Feign.Builder; +import feign.Headers; +import feign.RequestLine; +import feign.Response; +import feign.Util; import feign.assertj.MockWebServerAssertions; import feign.client.AbstractClientTest; import feign.jaxrs.JAXRSContract; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.Collections; -import javax.ws.rs.*; -import okhttp3.mockwebserver.MockResponse; +import javax.ws.rs.Consumes; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.ProcessingException; +import mockwebserver3.MockResponse; import org.assertj.core.data.MapEntry; -import org.junit.Assume; -import org.junit.Test; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.Test; /** Tests client-specific behavior, such as ensuring Content-Length is sent when specified. */ public class JAXRSClientTest extends AbstractClientTest { @@ -41,11 +48,11 @@ public Builder newBuilder() { } @Override - public void testPatch() throws Exception { + public void patch() throws Exception { try { - super.testPatch(); + super.patch(); } catch (final ProcessingException e) { - Assume.assumeNoException("JaxRS client do not support PATCH requests", e); + Assumptions.assumeFalse(false, "JaxRS client do not support PATCH requests"); } } @@ -54,7 +61,7 @@ public void noResponseBodyForPut() throws Exception { try { super.noResponseBodyForPut(); } catch (final IllegalStateException e) { - Assume.assumeNoException("JaxRS client do not support empty bodies on PUT", e); + Assumptions.assumeFalse(false, "JaxRS client do not support empty bodies on PUT"); } } @@ -63,10 +70,11 @@ public void noResponseBodyForPatch() { try { super.noResponseBodyForPatch(); } catch (final IllegalStateException e) { - Assume.assumeNoException("JaxRS client do not support PATCH requests", e); + Assumptions.assumeFalse(false, "JaxRS client do not support PATCH requests"); } } + @Override @Test public void reasonPhraseIsOptional() throws IOException, InterruptedException { server.enqueue(new MockResponse().setStatus("HTTP/1.1 " + 200)); @@ -81,6 +89,7 @@ public void reasonPhraseIsOptional() throws IOException, InterruptedException { // assertThat(response.reason()).isNullOrEmpty(); } + @Override @Test public void parsesRequestAndResponse() throws IOException, InterruptedException { server.enqueue(new MockResponse().setBody("foo").addHeader("Foo: Bar")); @@ -114,14 +123,14 @@ public void parsesRequestAndResponse() throws IOException, InterruptedException } @Test - public void testContentTypeWithoutCharset2() throws Exception { + void contentTypeWithoutCharset2() throws Exception { server.enqueue(new MockResponse().setBody("AAAAAAAA")); final JaxRSClientTestInterface api = newBuilder().target(JaxRSClientTestInterface.class, "http://localhost:" + server.getPort()); final Response response = api.getWithContentType(); // Response length should not be null - assertEquals("AAAAAAAA", Util.toString(response.body().asReader(UTF_8))); + assertThat(Util.toString(response.body().asReader(UTF_8))).isEqualTo("AAAAAAAA"); MockWebServerAssertions.assertThat(server.takeRequest()) .hasHeaders( @@ -131,7 +140,7 @@ public void testContentTypeWithoutCharset2() throws Exception { } @Test - public void testConsumesMultipleWithContentTypeHeaderAndBody() throws Exception { + void consumesMultipleWithContentTypeHeaderAndBody() throws Exception { server.enqueue(new MockResponse().setBody("AAAAAAAA")); final JaxRSClientTestInterfaceWithJaxRsContract api = newBuilder() @@ -142,7 +151,7 @@ public void testConsumesMultipleWithContentTypeHeaderAndBody() throws Exception final Response response = api.consumesMultipleWithContentTypeHeaderAndBody("application/json;charset=utf-8", "body"); - assertEquals("AAAAAAAA", Util.toString(response.body().asReader(UTF_8))); + assertThat(Util.toString(response.body().asReader(UTF_8))).isEqualTo("AAAAAAAA"); MockWebServerAssertions.assertThat(server.takeRequest()) .hasHeaders( @@ -156,27 +165,27 @@ public void testConsumesMultipleWithContentTypeHeaderAndBody() throws Exception */ @Override public void canSupportGzip() throws Exception { - assumeFalse("JaxRS client do not support gzip compression", false); + assumeFalse(false, "JaxRS client do not support gzip compression"); } @Override public void canSupportGzipOnError() throws Exception { - assumeFalse("JaxRS client do not support gzip compression", false); + assumeFalse(false, "JaxRS client do not support gzip compression"); } @Override public void canSupportDeflate() throws Exception { - assumeFalse("JaxRS client do not support deflate compression", false); + assumeFalse(false, "JaxRS client do not support deflate compression"); } @Override public void canSupportDeflateOnError() throws Exception { - assumeFalse("JaxRS client do not support deflate compression", false); + assumeFalse(false, "JaxRS client do not support deflate compression"); } @Override public void canExceptCaseInsensitiveHeader() throws Exception { - assumeFalse("JaxRS client do not support gzip compression", false); + assumeFalse(false, "JaxRS client do not support gzip compression"); } public interface JaxRSClientTestInterface { @@ -195,7 +204,7 @@ Response consumesMultipleWithContentTypeHeaderAndBody( } @Override - public void testVeryLongResponseNullLength() { - assumeFalse("JaxRS client hang if the response doesn't have a payload", false); + public void veryLongResponseNullLength() { + assumeFalse(false, "JaxRS client hang if the response doesn't have a payload"); } } diff --git a/json/pom.xml b/json/pom.xml index d7eec7733..effb4e502 100644 --- a/json/pom.xml +++ b/json/pom.xml @@ -40,11 +40,6 @@ org.json json - - org.hamcrest - hamcrest - test - org.mockito mockito-core diff --git a/json/src/test/java/feign/json/JsonCodecTest.java b/json/src/test/java/feign/json/JsonCodecTest.java index 2c90ee8d4..945fa48dd 100644 --- a/json/src/test/java/feign/json/JsonCodecTest.java +++ b/json/src/test/java/feign/json/JsonCodecTest.java @@ -14,11 +14,7 @@ package feign.json; import static feign.Util.toByteArray; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.hasSize; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import feign.Feign; import feign.Param; @@ -31,8 +27,8 @@ import java.io.InputStream; import org.json.JSONArray; import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; interface GitHub { @@ -44,13 +40,13 @@ JSONObject create( @Param("owner") String owner, @Param("repo") String repo, JSONObject contributor); } -public class JsonCodecTest { +class JsonCodecTest { private GitHub github; private MockClient mockClient; - @Before - public void setUp() { + @BeforeEach + void setUp() { mockClient = new MockClient(); github = Feign.builder() @@ -61,18 +57,18 @@ public void setUp() { } @Test - public void decodes() throws IOException { + void decodes() throws IOException { try (InputStream input = getClass().getResourceAsStream("/fixtures/contributors.json")) { byte[] response = toByteArray(input); mockClient.ok(HttpMethod.GET, "/repos/openfeign/feign/contributors", response); JSONArray contributors = github.contributors("openfeign", "feign"); - assertThat(contributors.toList(), hasSize(30)); + assertThat(contributors.toList()).hasSize(30); contributors.forEach(contributor -> ((JSONObject) contributor).getString("login")); } } @Test - public void encodes() { + void encodes() { JSONObject contributor = new JSONObject(); contributor.put("login", "radio-rogal"); contributor.put("contributions", 0); @@ -82,11 +78,11 @@ public void encodes() { "{\"login\":\"radio-rogal\",\"contributions\":0}"); JSONObject response = github.create("openfeign", "feign", contributor); Request request = mockClient.verifyOne(HttpMethod.POST, "/repos/openfeign/feign/contributors"); - assertNotNull(request.body()); + assertThat(request.body()).isNotNull(); String json = new String(request.body()); - assertThat(json, containsString("\"login\":\"radio-rogal\"")); - assertThat(json, containsString("\"contributions\":0")); - assertEquals("radio-rogal", response.getString("login")); - assertEquals(0, response.getInt("contributions")); + assertThat(json).contains("\"login\":\"radio-rogal\""); + assertThat(json).contains("\"contributions\":0"); + assertThat(response.getString("login")).isEqualTo("radio-rogal"); + assertThat(response.getInt("contributions")).isEqualTo(0); } } diff --git a/json/src/test/java/feign/json/JsonDecoderTest.java b/json/src/test/java/feign/json/JsonDecoderTest.java index c66d405a0..f02a24077 100644 --- a/json/src/test/java/feign/json/JsonDecoderTest.java +++ b/json/src/test/java/feign/json/JsonDecoderTest.java @@ -14,10 +14,8 @@ package feign.json; import static feign.Util.UTF_8; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -32,17 +30,17 @@ import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; -public class JsonDecoderTest { +class JsonDecoderTest { private static JSONArray jsonArray; private static JSONObject jsonObject; private static Request request; - @BeforeClass - public static void setUpClass() { + @BeforeAll + static void setUpClass() { jsonObject = new JSONObject(); jsonObject.put("a", "b"); jsonObject.put("c", 1); @@ -60,7 +58,7 @@ public static void setUpClass() { } @Test - public void decodesArray() throws IOException { + void decodesArray() throws IOException { String json = "[{\"a\":\"b\",\"c\":1},123]"; Response response = Response.builder() @@ -70,11 +68,11 @@ public void decodesArray() throws IOException { .body(json, UTF_8) .request(request) .build(); - assertTrue(jsonArray.similar(new JsonDecoder().decode(response, JSONArray.class))); + assertThat(jsonArray.similar(new JsonDecoder().decode(response, JSONArray.class))).isTrue(); } @Test - public void decodesObject() throws IOException { + void decodesObject() throws IOException { String json = "{\"a\":\"b\",\"c\":1}"; Response response = Response.builder() @@ -84,11 +82,11 @@ public void decodesObject() throws IOException { .body(json, UTF_8) .request(request) .build(); - assertTrue(jsonObject.similar(new JsonDecoder().decode(response, JSONObject.class))); + assertThat(jsonObject.similar(new JsonDecoder().decode(response, JSONObject.class))).isTrue(); } @Test - public void decodesString() throws IOException { + void decodesString() throws IOException { String json = "qwerty"; Response response = Response.builder() @@ -98,11 +96,11 @@ public void decodesString() throws IOException { .body(json, UTF_8) .request(request) .build(); - assertEquals("qwerty", new JsonDecoder().decode(response, String.class)); + assertThat(new JsonDecoder().decode(response, String.class)).isEqualTo("qwerty"); } @Test - public void notFoundDecodesToEmpty() throws IOException { + void notFoundDecodesToEmpty() throws IOException { Response response = Response.builder() .status(404) @@ -110,11 +108,12 @@ public void notFoundDecodesToEmpty() throws IOException { .headers(Collections.emptyMap()) .request(request) .build(); - assertTrue(((JSONObject) new JsonDecoder().decode(response, JSONObject.class)).isEmpty()); + assertThat(((JSONObject) new JsonDecoder().decode(response, JSONObject.class)).isEmpty()) + .isTrue(); } @Test - public void nullBodyDecodesToEmpty() throws IOException { + void nullBodyDecodesToEmpty() throws IOException { Response response = Response.builder() .status(204) @@ -122,11 +121,12 @@ public void nullBodyDecodesToEmpty() throws IOException { .headers(Collections.emptyMap()) .request(request) .build(); - assertTrue(((JSONObject) new JsonDecoder().decode(response, JSONObject.class)).isEmpty()); + assertThat(((JSONObject) new JsonDecoder().decode(response, JSONObject.class)).isEmpty()) + .isTrue(); } @Test - public void nullBodyDecodesToNullString() throws IOException { + void nullBodyDecodesToNullString() throws IOException { Response response = Response.builder() .status(204) @@ -134,11 +134,11 @@ public void nullBodyDecodesToNullString() throws IOException { .headers(Collections.emptyMap()) .request(request) .build(); - assertNull(new JsonDecoder().decode(response, String.class)); + assertThat(new JsonDecoder().decode(response, String.class)).isNull(); } @Test - public void emptyBodyDecodesToEmpty() throws IOException { + void emptyBodyDecodesToEmpty() throws IOException { Response response = Response.builder() .status(204) @@ -147,11 +147,12 @@ public void emptyBodyDecodesToEmpty() throws IOException { .body("", UTF_8) .request(request) .build(); - assertTrue(((JSONObject) new JsonDecoder().decode(response, JSONObject.class)).isEmpty()); + assertThat(((JSONObject) new JsonDecoder().decode(response, JSONObject.class)).isEmpty()) + .isTrue(); } @Test - public void unknownTypeThrowsDecodeException() throws IOException { + void unknownTypeThrowsDecodeException() throws IOException { String json = "[{\"a\":\"b\",\"c\":1},123]"; Response response = Response.builder() @@ -163,12 +164,12 @@ public void unknownTypeThrowsDecodeException() throws IOException { .build(); Exception exception = assertThrows(DecodeException.class, () -> new JsonDecoder().decode(response, Clock.class)); - assertEquals( - "class java.time.Clock is not a type supported by this decoder.", exception.getMessage()); + assertThat(exception.getMessage()) + .isEqualTo("class java.time.Clock is not a type supported by this decoder."); } @Test - public void badJsonThrowsWrappedJSONException() throws IOException { + void badJsonThrowsWrappedJSONException() throws IOException { String json = "{\"a\":\"b\",\"c\":1}"; Response response = Response.builder() @@ -181,13 +182,13 @@ public void badJsonThrowsWrappedJSONException() throws IOException { Exception exception = assertThrows( DecodeException.class, () -> new JsonDecoder().decode(response, JSONArray.class)); - assertEquals( - "A JSONArray text must start with '[' at 1 [character 2 line 1]", exception.getMessage()); - assertTrue(exception.getCause() instanceof JSONException); + assertThat(exception.getMessage()) + .isEqualTo("A JSONArray text must start with '[' at 1 [character 2 line 1]"); + assertThat(exception.getCause() instanceof JSONException).isTrue(); } @Test - public void causedByCommonException() throws IOException { + void causedByCommonException() throws IOException { Response.Body body = mock(Response.Body.class); when(body.asReader(any())) .thenThrow(new JSONException("test exception", new Exception("test cause exception"))); @@ -202,11 +203,11 @@ public void causedByCommonException() throws IOException { Exception exception = assertThrows( DecodeException.class, () -> new JsonDecoder().decode(response, JSONArray.class)); - assertEquals("test exception", exception.getMessage()); + assertThat(exception.getMessage()).isEqualTo("test exception"); } @Test - public void causedByIOException() throws IOException { + void causedByIOException() throws IOException { Response.Body body = mock(Response.Body.class); when(body.asReader(any())) .thenThrow(new JSONException("test exception", new IOException("test cause exception"))); @@ -220,11 +221,11 @@ public void causedByIOException() throws IOException { .build(); Exception exception = assertThrows(IOException.class, () -> new JsonDecoder().decode(response, JSONArray.class)); - assertEquals("test cause exception", exception.getMessage()); + assertThat(exception.getMessage()).isEqualTo("test cause exception"); } @Test - public void checkedException() throws IOException { + void checkedException() throws IOException { Response.Body body = mock(Response.Body.class); when(body.asReader(any())).thenThrow(new IOException("test exception")); Response response = @@ -237,11 +238,11 @@ public void checkedException() throws IOException { .build(); Exception exception = assertThrows(IOException.class, () -> new JsonDecoder().decode(response, JSONArray.class)); - assertEquals("test exception", exception.getMessage()); + assertThat(exception.getMessage()).isEqualTo("test exception"); } @Test - public void decodesExtendedArray() throws IOException { + void decodesExtendedArray() throws IOException { String json = "[{\"a\":\"b\",\"c\":1},123]"; Response response = Response.builder() @@ -251,11 +252,12 @@ public void decodesExtendedArray() throws IOException { .body(json, UTF_8) .request(request) .build(); - assertTrue(jsonArray.similar(new JsonDecoder().decode(response, ExtendedJSONArray.class))); + assertThat(jsonArray.similar(new JsonDecoder().decode(response, ExtendedJSONArray.class))) + .isTrue(); } @Test - public void decodeExtendedObject() throws IOException { + void decodeExtendedObject() throws IOException { String json = "{\"a\":\"b\",\"c\":1}"; Response response = Response.builder() @@ -265,7 +267,8 @@ public void decodeExtendedObject() throws IOException { .body(json, UTF_8) .request(request) .build(); - assertTrue(jsonObject.similar(new JsonDecoder().decode(response, ExtendedJSONObject.class))); + assertThat(jsonObject.similar(new JsonDecoder().decode(response, ExtendedJSONObject.class))) + .isTrue(); } static class ExtendedJSONArray extends JSONArray {} diff --git a/json/src/test/java/feign/json/JsonEncoderTest.java b/json/src/test/java/feign/json/JsonEncoderTest.java index d2847019b..ddc4d1b73 100644 --- a/json/src/test/java/feign/json/JsonEncoderTest.java +++ b/json/src/test/java/feign/json/JsonEncoderTest.java @@ -14,25 +14,26 @@ package feign.json; import static feign.Util.UTF_8; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; import feign.RequestTemplate; import feign.codec.EncodeException; import java.time.Clock; import org.json.JSONArray; import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.skyscreamer.jsonassert.JSONAssert; -public class JsonEncoderTest { +class JsonEncoderTest { private JSONArray jsonArray; private JSONObject jsonObject; private RequestTemplate requestTemplate; - @Before - public void setUp() { + @BeforeEach + void setUp() { jsonObject = new JSONObject(); jsonObject.put("a", "b"); jsonObject.put("c", 1); @@ -43,32 +44,32 @@ public void setUp() { } @Test - public void encodesArray() { + void encodesArray() { new JsonEncoder().encode(jsonArray, JSONArray.class, requestTemplate); JSONAssert.assertEquals( "[{\"a\":\"b\",\"c\":1},123]", new String(requestTemplate.body(), UTF_8), false); } @Test - public void encodesObject() { + void encodesObject() { new JsonEncoder().encode(jsonObject, JSONObject.class, requestTemplate); JSONAssert.assertEquals( "{\"a\":\"b\",\"c\":1}", new String(requestTemplate.body(), UTF_8), false); } @Test - public void encodesNull() { + void encodesNull() { new JsonEncoder().encode(null, JSONObject.class, new RequestTemplate()); - assertNull(requestTemplate.body()); + assertThat(requestTemplate.body()).isNull(); } @Test - public void unknownTypeThrowsEncodeException() { + void unknownTypeThrowsEncodeException() { Exception exception = assertThrows( EncodeException.class, () -> new JsonEncoder().encode("qwerty", Clock.class, new RequestTemplate())); - assertEquals( - "class java.time.Clock is not a type supported by this encoder.", exception.getMessage()); + assertThat(exception.getMessage()) + .isEqualTo("class java.time.Clock is not a type supported by this encoder."); } } diff --git a/micrometer/pom.xml b/micrometer/pom.xml index 95c72ba04..5ee4612d4 100644 --- a/micrometer/pom.xml +++ b/micrometer/pom.xml @@ -57,11 +57,6 @@ ${micrometer.version} test - - org.hamcrest - hamcrest - test - ${project.groupId} feign-okhttp diff --git a/micrometer/src/test/java/feign/micrometer/AbstractMetricsTestBase.java b/micrometer/src/test/java/feign/micrometer/AbstractMetricsTestBase.java index 390d31f8d..f6de84ea4 100644 --- a/micrometer/src/test/java/feign/micrometer/AbstractMetricsTestBase.java +++ b/micrometer/src/test/java/feign/micrometer/AbstractMetricsTestBase.java @@ -13,14 +13,10 @@ */ package feign.micrometer; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.aMapWithSize; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import feign.AsyncFeign; import feign.Capability; @@ -35,8 +31,8 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Collectors; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public abstract class AbstractMetricsTestBase { @@ -54,7 +50,7 @@ public interface CompletableSource { protected MR metricsRegistry; - @Before + @BeforeEach public final void initializeMetricRegistry() { this.metricsRegistry = createMetricsRegistry(); } @@ -62,7 +58,7 @@ public final void initializeMetricRegistry() { protected abstract MR createMetricsRegistry(); @Test - public final void addMetricsCapability() { + final void addMetricsCapability() { final SimpleSource source = customizeBuilder( Feign.builder() @@ -76,7 +72,7 @@ public final void addMetricsCapability() { } @Test - public final void addAsyncMetricsCapability() { + final void addAsyncMetricsCapability() { final CompletableSource source = customizeBuilder( AsyncFeign.builder() @@ -91,28 +87,28 @@ public final void addAsyncMetricsCapability() { private void assertMetricsCapability(boolean asyncClient) { Map metrics = getFeignMetrics(); - assertThat(metrics, aMapWithSize(7)); + assertThat(metrics).hasSize(7); metrics .keySet() .forEach( metricId -> - assertThat( - "Expect all metric names to include client name:" + metricId, - doesMetricIdIncludeClient(metricId))); + assertThat(doesMetricIdIncludeClient(metricId)) + .as("Expect all metric names to include client name:" + metricId) + .isTrue()); metrics .keySet() .forEach( metricId -> - assertThat( - "Expect all metric names to include method name:" + metricId, - doesMetricIncludeVerb(metricId, "get"))); + assertThat(doesMetricIncludeVerb(metricId, "get")) + .as("Expect all metric names to include method name:" + metricId) + .isTrue()); metrics .keySet() .forEach( metricId -> - assertThat( - "Expect all metric names to include host name:" + metricId, - doesMetricIncludeHost(metricId))); + assertThat(doesMetricIncludeHost(metricId)) + .as("Expect all metric names to include host name:" + metricId) + .isTrue()); final Map clientMetrics; if (asyncClient) { @@ -127,7 +123,7 @@ private void assertMetricsCapability(boolean asyncClient) { .filter(entry -> isClientMetric(entry.getKey())) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } - assertThat(clientMetrics, aMapWithSize(2)); + assertThat(clientMetrics).hasSize(2); clientMetrics.values().stream() .filter(this::doesMetricHasCounter) .forEach(metric -> assertEquals(1, getMetricCounter(metric))); @@ -137,7 +133,7 @@ private void assertMetricsCapability(boolean asyncClient) { .filter(entry -> isDecoderMetric(entry.getKey())) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); - assertThat(decoderMetrics, aMapWithSize(2)); + assertThat(decoderMetrics).hasSize(2); decoderMetrics.values().stream() .filter(this::doesMetricHasCounter) .forEach(metric -> assertEquals(1, getMetricCounter(metric))); @@ -154,7 +150,7 @@ private void assertMetricsCapability(boolean asyncClient) { protected abstract Map getFeignMetrics(); @Test - public void clientPropagatesUncheckedException() { + void clientPropagatesUncheckedException() { final AtomicReference notFound = new AtomicReference<>(); final SimpleSource source = @@ -172,25 +168,25 @@ public void clientPropagatesUncheckedException() { source.get("0x3456789"); fail("Should throw NotFound exception"); } catch (FeignException.NotFound e) { - assertSame(notFound.get(), e); + assertThat(e).isSameAs(notFound.get()); } assertThat( - getMetric( - "http_response_code", - "http_status", - "404", - "status_group", - "4xx", - "http_method", - "GET"), - notNullValue()); + getMetric( + "http_response_code", + "http_status", + "404", + "status_group", + "4xx", + "http_method", + "GET")) + .isNotNull(); } protected abstract METRIC getMetric(String suffix, String... tags); @Test - public void decoderPropagatesUncheckedException() { + void decoderPropagatesUncheckedException() { final AtomicReference notFound = new AtomicReference<>(); final SimpleSource source = @@ -208,11 +204,11 @@ public void decoderPropagatesUncheckedException() { FeignException.NotFound thrown = assertThrows(FeignException.NotFound.class, () -> source.get("0x3456789")); - assertSame(notFound.get(), thrown); + assertThat(thrown).isSameAs(notFound.get()); } @Test - public void shouldMetricCollectionWithCustomException() { + void shouldMetricCollectionWithCustomException() { final SimpleSource source = customizeBuilder( Feign.builder() @@ -224,22 +220,22 @@ public void shouldMetricCollectionWithCustomException() { .target(new MockTarget<>(MicrometerCapabilityTest.SimpleSource.class)); RuntimeException thrown = assertThrows(RuntimeException.class, () -> source.get("0x3456789")); - assertThat(thrown.getMessage(), equalTo("Test error")); + assertThat(thrown.getMessage()).isEqualTo("Test error"); assertThat( - getMetric( - "exception", - "exception_name", - "RuntimeException", - "method", - "get", - "root_cause_name", - "RuntimeException"), - notNullValue()); + getMetric( + "exception", + "exception_name", + "RuntimeException", + "method", + "get", + "root_cause_name", + "RuntimeException")) + .isNotNull(); } @Test - public void clientMetricsHaveUriLabel() { + void clientMetricsHaveUriLabel() { final SimpleSource source = customizeBuilder( Feign.builder() @@ -258,9 +254,9 @@ public void clientMetricsHaveUriLabel() { .keySet() .forEach( metricId -> - assertThat( - "Expect all Client metric names to include uri:" + metricId, - doesMetricIncludeUri(metricId, "/get"))); + assertThat(doesMetricIncludeUri(metricId, "/get")) + .as("Expect all Client metric names to include uri:" + metricId) + .isTrue()); } public interface SourceWithPathExpressions { @@ -270,7 +266,7 @@ public interface SourceWithPathExpressions { } @Test - public void clientMetricsHaveUriLabelWithPathExpression() { + void clientMetricsHaveUriLabelWithPathExpression() { final SourceWithPathExpressions source = customizeBuilder( Feign.builder() @@ -289,14 +285,16 @@ public void clientMetricsHaveUriLabelWithPathExpression() { .keySet() .forEach( metricId -> - assertThat( - "Expect all Client metric names to include uri as aggregated path expression:" - + metricId, - doesMetricIncludeUri(metricId, "/get/{id}"))); + assertThat(doesMetricIncludeUri(metricId, "/get/{id}")) + .as( + "Expect all Client metric names to include uri as aggregated path" + + " expression:" + + metricId) + .isTrue()); } @Test - public void decoderExceptionCounterHasUriLabelWithPathExpression() { + void decoderExceptionCounterHasUriLabelWithPathExpression() { final AtomicReference notFound = new AtomicReference<>(); final SourceWithPathExpressions source = @@ -314,7 +312,7 @@ public void decoderExceptionCounterHasUriLabelWithPathExpression() { FeignException.NotFound thrown = assertThrows(FeignException.NotFound.class, () -> source.get("123", "0x3456789")); - assertSame(notFound.get(), thrown); + assertThat(thrown).isSameAs(notFound.get()); final Map decoderMetrics = getFeignMetrics().entrySet().stream() @@ -325,10 +323,12 @@ public void decoderExceptionCounterHasUriLabelWithPathExpression() { .keySet() .forEach( metricId -> - assertThat( - "Expect all Decoder metric names to include uri as aggregated path expression:" - + metricId, - doesMetricIncludeUri(metricId, "/get/{id}"))); + assertThat(doesMetricIncludeUri(metricId, "/get/{id}")) + .as( + "Expect all Decoder metric names to include uri as aggregated path" + + " expression:" + + metricId) + .isTrue()); } protected abstract boolean isClientMetric(METRIC_ID metricId); diff --git a/micrometer/src/test/java/feign/micrometer/MicrometerCapabilityTest.java b/micrometer/src/test/java/feign/micrometer/MicrometerCapabilityTest.java index b7faaee8e..554dafa60 100644 --- a/micrometer/src/test/java/feign/micrometer/MicrometerCapabilityTest.java +++ b/micrometer/src/test/java/feign/micrometer/MicrometerCapabilityTest.java @@ -13,9 +13,6 @@ */ package feign.micrometer; -import static org.hamcrest.Matchers.allOf; -import static org.hamcrest.Matchers.containsString; - import feign.Capability; import feign.Util; import io.micrometer.core.instrument.Measurement; @@ -31,7 +28,6 @@ import java.util.Map.Entry; import java.util.function.Function; import java.util.stream.Collectors; -import org.hamcrest.Matcher; public class MicrometerCapabilityTest extends AbstractMetricsTestBase { @@ -57,9 +53,7 @@ protected Map getFeignMetrics() { @Override protected boolean doesMetricIdIncludeClient(Id metricId) { String tag = metricId.getTag("client"); - Matcher containsBase = containsString("feign.micrometer.AbstractMetricsTestBase$"); - Matcher containsSource = containsString("Source"); - return allOf(containsBase, containsSource).matches(tag); + return tag.contains("feign.micrometer.AbstractMetricsTestBase$") && tag.contains("Source"); } @Override diff --git a/micrometer/src/test/java/feign/micrometer/MicrometerObservationRegistryCapabilityTest.java b/micrometer/src/test/java/feign/micrometer/MicrometerObservationRegistryCapabilityTest.java index 533add96e..48bf257eb 100644 --- a/micrometer/src/test/java/feign/micrometer/MicrometerObservationRegistryCapabilityTest.java +++ b/micrometer/src/test/java/feign/micrometer/MicrometerObservationRegistryCapabilityTest.java @@ -17,14 +17,14 @@ import feign.Feign; import io.micrometer.core.instrument.observation.DefaultMeterObservationHandler; import io.micrometer.observation.ObservationRegistry; -import org.junit.Before; +import org.junit.jupiter.api.BeforeEach; -public class MicrometerObservationRegistryCapabilityTest extends MicrometerCapabilityTest { +class MicrometerObservationRegistryCapabilityTest extends MicrometerCapabilityTest { ObservationRegistry observationRegistry = ObservationRegistry.create(); - @Before - public void setupRegistry() { + @BeforeEach + void setupRegistry() { observationRegistry .observationConfig() .observationHandler(new DefaultMeterObservationHandler(metricsRegistry)); diff --git a/mock/pom.xml b/mock/pom.xml index 2ea54c9e4..0d8fd1ad6 100644 --- a/mock/pom.xml +++ b/mock/pom.xml @@ -42,11 +42,6 @@ feign-gson test - - org.hamcrest - hamcrest - test - diff --git a/mock/src/test/java/feign/mock/HttpProtocolVersionTest.java b/mock/src/test/java/feign/mock/HttpProtocolVersionTest.java index f6916210f..8c624157f 100644 --- a/mock/src/test/java/feign/mock/HttpProtocolVersionTest.java +++ b/mock/src/test/java/feign/mock/HttpProtocolVersionTest.java @@ -13,14 +13,14 @@ */ package feign.mock; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.assertThat; import feign.Feign; import feign.RequestLine; import feign.Response; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class HttpProtocolVersionTest { +class HttpProtocolVersionTest { interface Remote { @@ -29,7 +29,7 @@ interface Remote { } @Test - public void testMockProtocolVersion() { + void mockProtocolVersion() { Remote remote = Feign.builder() .client(new MockClient().ok(HttpMethod.GET, "/test")) @@ -37,7 +37,7 @@ public void testMockProtocolVersion() { Response response = remote.test(); - assertNotNull(response.protocolVersion()); - assertEquals("MOCK", response.protocolVersion().toString()); + assertThat(response.protocolVersion()).isNotNull(); + assertThat(response.protocolVersion().toString()).isEqualTo("MOCK"); } } diff --git a/mock/src/test/java/feign/mock/MockClientSequentialTest.java b/mock/src/test/java/feign/mock/MockClientSequentialTest.java index 229923380..9d8255585 100644 --- a/mock/src/test/java/feign/mock/MockClientSequentialTest.java +++ b/mock/src/test/java/feign/mock/MockClientSequentialTest.java @@ -14,12 +14,8 @@ package feign.mock; import static feign.Util.toByteArray; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import feign.Body; import feign.Feign; @@ -35,12 +31,12 @@ import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Type; +import java.net.HttpURLConnection; import java.util.List; -import javax.net.ssl.HttpsURLConnection; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class MockClientSequentialTest { +class MockClientSequentialTest { interface GitHub { @@ -84,7 +80,7 @@ public AssertionDecoder(Decoder delegate) { @Override public Object decode(Response response, Type type) throws IOException, DecodeException, FeignException { - assertThat(response.request(), notNullValue()); + assertThat(response.request()).isNotNull(); return delegate.decode(response, type); } @@ -93,8 +89,8 @@ public Object decode(Response response, Type type) private GitHub githubSequential; private MockClient mockClientSequential; - @Before - public void setup() throws IOException { + @BeforeEach + void setup() throws IOException { try (InputStream input = getClass().getResourceAsStream("/fixtures/contributors.json")) { byte[] data = toByteArray(input); RequestHeaders headers = RequestHeaders.builder().add("Name", "netflix").build(); @@ -108,22 +104,22 @@ public void setup() throws IOException { RequestKey.builder(HttpMethod.GET, "/repos/netflix/feign/contributors") .headers(headers) .build(), - HttpsURLConnection.HTTP_OK, + HttpURLConnection.HTTP_OK, data) .add( HttpMethod.GET, "/repos/netflix/feign/contributors?client_id=55", - HttpsURLConnection.HTTP_NOT_FOUND) + HttpURLConnection.HTTP_NOT_FOUND) .add( HttpMethod.GET, "/repos/netflix/feign/contributors?client_id=7 7", - HttpsURLConnection.HTTP_INTERNAL_ERROR, + HttpURLConnection.HTTP_INTERNAL_ERROR, new ByteArrayInputStream(data)) .add( HttpMethod.GET, "/repos/netflix/feign/contributors", Response.builder() - .status(HttpsURLConnection.HTTP_OK) + .status(HttpURLConnection.HTTP_OK) .headers(RequestHeaders.EMPTY) .body(data))) .target(new MockTarget<>(GitHub.class)); @@ -131,19 +127,19 @@ public void setup() throws IOException { } @Test - public void sequentialRequests() throws Exception { + void sequentialRequests() throws Exception { githubSequential.contributors("netflix", "feign"); try { githubSequential.contributors("55", "netflix", "feign"); - fail(); + fail(""); } catch (FeignException e) { - assertThat(e.status(), equalTo(HttpsURLConnection.HTTP_NOT_FOUND)); + assertThat(e.status()).isEqualTo(HttpURLConnection.HTTP_NOT_FOUND); } try { githubSequential.contributors("7 7", "netflix", "feign"); - fail(); + fail(""); } catch (FeignException e) { - assertThat(e.status(), equalTo(HttpsURLConnection.HTTP_INTERNAL_ERROR)); + assertThat(e.status()).isEqualTo(HttpURLConnection.HTTP_INTERNAL_ERROR); } githubSequential.contributors("netflix", "feign"); @@ -151,35 +147,35 @@ public void sequentialRequests() throws Exception { } @Test - public void sequentialRequestsCalledTooLess() throws Exception { + void sequentialRequestsCalledTooLess() throws Exception { githubSequential.contributors("netflix", "feign"); try { mockClientSequential.verifyStatus(); - fail(); + fail(""); } catch (VerificationAssertionError e) { - assertThat(e.getMessage(), startsWith("More executions")); + assertThat(e.getMessage()).startsWith("More executions"); } } @Test - public void sequentialRequestsCalledTooMany() throws Exception { + void sequentialRequestsCalledTooMany() throws Exception { sequentialRequests(); try { githubSequential.contributors("netflix", "feign"); - fail(); + fail(""); } catch (VerificationAssertionError e) { - assertThat(e.getMessage(), containsString("excessive")); + assertThat(e.getMessage()).contains("excessive"); } } @Test - public void sequentialRequestsInWrongOrder() throws Exception { + void sequentialRequestsInWrongOrder() throws Exception { try { githubSequential.contributors("7 7", "netflix", "feign"); - fail(); + fail(""); } catch (VerificationAssertionError e) { - assertThat(e.getMessage(), startsWith("Expected: \nRequest [")); + assertThat(e.getMessage()).startsWith("Expected: \nRequest ["); } } } diff --git a/mock/src/test/java/feign/mock/MockClientTest.java b/mock/src/test/java/feign/mock/MockClientTest.java index ff7366fee..55e99fc14 100644 --- a/mock/src/test/java/feign/mock/MockClientTest.java +++ b/mock/src/test/java/feign/mock/MockClientTest.java @@ -15,14 +15,17 @@ import static feign.Util.UTF_8; import static feign.Util.toByteArray; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.fail; - -import feign.*; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; + +import feign.Body; +import feign.Feign; +import feign.FeignException; +import feign.Headers; +import feign.Param; +import feign.Request; +import feign.RequestLine; +import feign.Response; import feign.codec.DecodeException; import feign.codec.Decoder; import feign.gson.GsonDecoder; @@ -30,13 +33,12 @@ import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Type; +import java.net.HttpURLConnection; import java.util.List; -import javax.net.ssl.HttpsURLConnection; -import org.hamcrest.Matchers; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class MockClientTest { +class MockClientTest { interface GitHub { @@ -80,7 +82,7 @@ public AssertionDecoder(Decoder delegate) { @Override public Object decode(Response response, Type type) throws IOException, DecodeException, FeignException { - assertThat(response.request(), notNullValue()); + assertThat(response.request()).isNotNull(); return delegate.decode(response, type); } @@ -89,8 +91,8 @@ public Object decode(Response response, Type type) private GitHub github; private MockClient mockClient; - @Before - public void setup() throws IOException { + @BeforeEach + void setup() throws IOException { try (InputStream input = getClass().getResourceAsStream("/fixtures/contributors.json")) { byte[] data = toByteArray(input); RequestKey postContributorKey = @@ -120,62 +122,62 @@ public void setup() throws IOException { .add( HttpMethod.GET, "/repos/netflix/feign/contributors?client_id=1234567890", - HttpsURLConnection.HTTP_NOT_FOUND) + HttpURLConnection.HTTP_NOT_FOUND) .add( HttpMethod.GET, "/repos/netflix/feign/contributors?client_id=123456789", - HttpsURLConnection.HTTP_INTERNAL_ERROR, + HttpURLConnection.HTTP_INTERNAL_ERROR, new ByteArrayInputStream(data)) .add( HttpMethod.GET, "/repos/netflix/feign/contributors?client_id=123456789", - HttpsURLConnection.HTTP_INTERNAL_ERROR, + HttpURLConnection.HTTP_INTERNAL_ERROR, "") .add( HttpMethod.GET, "/repos/netflix/feign/contributors?client_id=123456789", - HttpsURLConnection.HTTP_INTERNAL_ERROR, + HttpURLConnection.HTTP_INTERNAL_ERROR, data)) .target(new MockTarget<>(GitHub.class)); } } @Test - public void hitMock() { + void hitMock() { List contributors = github.contributors("netflix", "feign"); - assertThat(contributors, hasSize(30)); + assertThat(contributors).hasSize(30); mockClient.verifyStatus(); } @Test - public void missMock() { + void missMock() { try { github.contributors("velo", "feign-mock"); - fail(); + fail(""); } catch (FeignException e) { - assertThat(e.getMessage(), Matchers.containsString("404")); + assertThat(e.getMessage()).contains("404"); } } @Test - public void missHttpMethod() { + void missHttpMethod() { try { github.patchContributors("netflix", "feign"); - fail(); + fail(""); } catch (FeignException e) { - assertThat(e.getMessage(), Matchers.containsString("404")); + assertThat(e.getMessage()).contains("404"); } } @Test - public void paramsEncoding() { + void paramsEncoding() { List contributors = github.contributors("7 7", "netflix", "feign"); - assertThat(contributors, hasSize(30)); + assertThat(contributors).hasSize(30); mockClient.verifyStatus(); } @Test - public void verifyInvocation() { + void verifyInvocation() { RequestKey testRequestKey = RequestKey.builder(HttpMethod.POST, "/repos/netflix/feign/contributors") .headers( @@ -189,29 +191,29 @@ public void verifyInvocation() { Contributor contribution = github.create("netflix", "feign", "velo_at_github", "preposterous hacker"); // making sure it received a proper response - assertThat(contribution, notNullValue()); - assertThat(contribution.login, equalTo("velo")); - assertThat(contribution.contributions, equalTo(0)); + assertThat(contribution).isNotNull(); + assertThat(contribution.login).isEqualTo("velo"); + assertThat(contribution.contributions).isEqualTo(0); List results = mockClient.verifyTimes(HttpMethod.POST, "/repos/netflix/feign/contributors", 1); - assertThat(results, hasSize(1)); + assertThat(results).hasSize(1); results = mockClient.verifyTimes(testRequestKey, 1); - assertThat(results, hasSize(1)); + assertThat(results).hasSize(1); - assertThat(mockClient.verifyOne(testRequestKey).body(), notNullValue()); + assertThat(mockClient.verifyOne(testRequestKey).body()).isNotNull(); byte[] body = mockClient.verifyOne(HttpMethod.POST, "/repos/netflix/feign/contributors").body(); - assertThat(body, notNullValue()); + assertThat(body).isNotNull(); String message = new String(body); - assertThat(message, containsString("velo_at_github")); - assertThat(message, containsString("preposterous hacker")); + assertThat(message).contains("velo_at_github"); + assertThat(message).contains("preposterous hacker"); mockClient.verifyStatus(); } @Test - public void verifyNone() { + void verifyNone() { RequestKey testRequestKey; github.create("netflix", "feign", "velo_at_github", "preposterous hacker"); mockClient.verifyTimes(HttpMethod.POST, "/repos/netflix/feign/contributors", 1); @@ -229,11 +231,11 @@ public void verifyNone() { .build(); try { mockClient.verifyOne(testRequestKey); - fail(); + fail(""); } catch (VerificationAssertionError e) { - assertThat(e.getMessage(), containsString("Wanted")); - assertThat(e.getMessage(), containsString("POST")); - assertThat(e.getMessage(), containsString("/repos/netflix/feign/contributors")); + assertThat(e.getMessage()).contains("Wanted"); + assertThat(e.getMessage()).contains("POST"); + assertThat(e.getMessage()).contains("/repos/netflix/feign/contributors"); } mockClient.verifyNever(testRequestKey); @@ -251,89 +253,89 @@ public void verifyNone() { .build(); try { mockClient.verifyOne(testRequestKey); - fail(); + fail(""); } catch (VerificationAssertionError e) { - assertThat(e.getMessage(), containsString("Wanted")); - assertThat(e.getMessage(), containsString("POST")); - assertThat(e.getMessage(), containsString("/repos/netflix/feign/contributors")); + assertThat(e.getMessage()).contains("Wanted"); + assertThat(e.getMessage()).contains("POST"); + assertThat(e.getMessage()).contains("/repos/netflix/feign/contributors"); } mockClient.verifyNever(testRequestKey); try { mockClient.verifyTimes(HttpMethod.POST, "/repos/netflix/feign/contributors", 0); - fail(); + fail(""); } catch (VerificationAssertionError e) { - assertThat(e.getMessage(), containsString("Do not wanted")); - assertThat(e.getMessage(), containsString("POST")); - assertThat(e.getMessage(), containsString("/repos/netflix/feign/contributors")); + assertThat(e.getMessage()).contains("Do not wanted"); + assertThat(e.getMessage()).contains("POST"); + assertThat(e.getMessage()).contains("/repos/netflix/feign/contributors"); } try { mockClient.verifyTimes(HttpMethod.POST, "/repos/netflix/feign/contributors", 3); - fail(); + fail(""); } catch (VerificationAssertionError e) { - assertThat(e.getMessage(), containsString("Wanted")); - assertThat(e.getMessage(), containsString("POST")); - assertThat(e.getMessage(), containsString("/repos/netflix/feign/contributors")); - assertThat(e.getMessage(), containsString("'3'")); - assertThat(e.getMessage(), containsString("'1'")); + assertThat(e.getMessage()).contains("Wanted"); + assertThat(e.getMessage()).contains("POST"); + assertThat(e.getMessage()).contains("/repos/netflix/feign/contributors"); + assertThat(e.getMessage()).contains("'3'"); + assertThat(e.getMessage()).contains("'1'"); } } @Test - public void verifyNotInvoked() { + void verifyNotInvoked() { mockClient.verifyNever(HttpMethod.POST, "/repos/netflix/feign/contributors"); List results = mockClient.verifyTimes(HttpMethod.POST, "/repos/netflix/feign/contributors", 0); - assertThat(results, hasSize(0)); + assertThat(results).hasSize(0); try { mockClient.verifyOne(HttpMethod.POST, "/repos/netflix/feign/contributors"); - fail(); + fail(""); } catch (VerificationAssertionError e) { - assertThat(e.getMessage(), containsString("Wanted")); - assertThat(e.getMessage(), containsString("POST")); - assertThat(e.getMessage(), containsString("/repos/netflix/feign/contributors")); - assertThat(e.getMessage(), containsString("never invoked")); + assertThat(e.getMessage()).contains("Wanted"); + assertThat(e.getMessage()).contains("POST"); + assertThat(e.getMessage()).contains("/repos/netflix/feign/contributors"); + assertThat(e.getMessage()).contains("never invoked"); } } @Test - public void verifyNegative() { + void verifyNegative() { try { mockClient.verifyTimes(HttpMethod.POST, "/repos/netflix/feign/contributors", -1); - fail(); + fail(""); } catch (IllegalArgumentException e) { - assertThat(e.getMessage(), containsString("non negative")); + assertThat(e.getMessage()).contains("non negative"); } } @Test - public void verifyMultipleRequests() { + void verifyMultipleRequests() { mockClient.verifyNever(HttpMethod.POST, "/repos/netflix/feign/contributors"); github.create("netflix", "feign", "velo_at_github", "preposterous hacker"); Request result = mockClient.verifyOne(HttpMethod.POST, "/repos/netflix/feign/contributors"); - assertThat(result, notNullValue()); + assertThat(result).isNotNull(); github.create("netflix", "feign", "velo_at_github", "preposterous hacker"); List results = mockClient.verifyTimes(HttpMethod.POST, "/repos/netflix/feign/contributors", 2); - assertThat(results, hasSize(2)); + assertThat(results).hasSize(2); github.create("netflix", "feign", "velo_at_github", "preposterous hacker"); results = mockClient.verifyTimes(HttpMethod.POST, "/repos/netflix/feign/contributors", 3); - assertThat(results, hasSize(3)); + assertThat(results).hasSize(3); mockClient.verifyStatus(); } @Test - public void resetRequests() { + void resetRequests() { mockClient.verifyNever(HttpMethod.POST, "/repos/netflix/feign/contributors"); github.create("netflix", "feign", "velo_at_github", "preposterous hacker"); Request result = mockClient.verifyOne(HttpMethod.POST, "/repos/netflix/feign/contributors"); - assertThat(result, notNullValue()); + assertThat(result).isNotNull(); mockClient.resetRequests(); diff --git a/mock/src/test/java/feign/mock/MockTargetTest.java b/mock/src/test/java/feign/mock/MockTargetTest.java index b563f8129..7076ad94e 100644 --- a/mock/src/test/java/feign/mock/MockTargetTest.java +++ b/mock/src/test/java/feign/mock/MockTargetTest.java @@ -13,23 +13,22 @@ */ package feign.mock; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; +import static org.assertj.core.api.Assertions.assertThat; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class MockTargetTest { +class MockTargetTest { private MockTarget target; - @Before - public void setup() { + @BeforeEach + void setup() { target = new MockTarget<>(MockTargetTest.class); } @Test - public void test() { - assertThat(target.name(), equalTo("MockTargetTest")); + void test() { + assertThat(target.name()).isEqualTo("MockTargetTest"); } } diff --git a/mock/src/test/java/feign/mock/RequestHeadersTest.java b/mock/src/test/java/feign/mock/RequestHeadersTest.java index c36b39857..d7b49b5f0 100644 --- a/mock/src/test/java/feign/mock/RequestHeadersTest.java +++ b/mock/src/test/java/feign/mock/RequestHeadersTest.java @@ -19,24 +19,24 @@ import java.util.Collection; import java.util.HashMap; import java.util.Map; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class RequestHeadersTest { +class RequestHeadersTest { @Test - public void shouldCreateEmptyRequestHeaders() { + void shouldCreateEmptyRequestHeaders() { RequestHeaders headers = RequestHeaders.builder().build(); assertThat(headers.size()).isEqualTo(0); } @Test - public void shouldReturnZeroSizeForUnknownKey() { + void shouldReturnZeroSizeForUnknownKey() { RequestHeaders headers = RequestHeaders.builder().build(); assertThat(headers.sizeOf("unknown")).isEqualTo(0); } @Test - public void shouldCreateRequestHeadersFromSingleValue() { + void shouldCreateRequestHeadersFromSingleValue() { RequestHeaders headers = RequestHeaders.builder().add("header", "val").add("other header", "val2").build(); @@ -47,7 +47,7 @@ public void shouldCreateRequestHeadersFromSingleValue() { } @Test - public void shouldCreateRequestHeadersFromSingleValueAndCollection() { + void shouldCreateRequestHeadersFromSingleValueAndCollection() { RequestHeaders headers = RequestHeaders.builder() .add("header", "val") @@ -62,15 +62,15 @@ public void shouldCreateRequestHeadersFromSingleValueAndCollection() { } @Test - public void shouldCreateRequestHeadersFromHeadersMap() { - Map> map = new HashMap>(); + void shouldCreateRequestHeadersFromHeadersMap() { + Map> map = new HashMap<>(); map.put("header", Arrays.asList("val", "val2")); RequestHeaders headers = RequestHeaders.of(map); assertThat(headers.size()).isEqualTo(1); } @Test - public void shouldPrintHeaders() { + void shouldPrintHeaders() { RequestHeaders headers = RequestHeaders.builder() .add("header", "val") diff --git a/mock/src/test/java/feign/mock/RequestKeyTest.java b/mock/src/test/java/feign/mock/RequestKeyTest.java index f45c1ea10..3072fa332 100644 --- a/mock/src/test/java/feign/mock/RequestKeyTest.java +++ b/mock/src/test/java/feign/mock/RequestKeyTest.java @@ -13,13 +13,7 @@ */ package feign.mock; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.both; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.startsWith; +import static org.assertj.core.api.Assertions.assertThat; import feign.Request; import java.nio.charset.StandardCharsets; @@ -27,15 +21,15 @@ import java.util.Collection; import java.util.HashMap; import java.util.Map; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class RequestKeyTest { +class RequestKeyTest { private RequestKey requestKey; - @Before - public void setUp() { + @BeforeEach + void setUp() { RequestHeaders headers = RequestHeaders.builder().add("my-header", "val").build(); requestKey = RequestKey.builder(HttpMethod.GET, "a") @@ -46,20 +40,18 @@ public void setUp() { } @Test - public void builder() throws Exception { - assertThat(requestKey.getMethod(), equalTo(HttpMethod.GET)); - assertThat(requestKey.getUrl(), equalTo("a")); - assertThat(requestKey.getHeaders().size(), is(1)); - assertThat( - requestKey.getHeaders().fetch("my-header"), - equalTo((Collection) Arrays.asList("val"))); - assertThat(requestKey.getCharset(), equalTo(StandardCharsets.UTF_16)); + void builder() throws Exception { + assertThat(requestKey.getMethod()).isEqualTo(HttpMethod.GET); + assertThat(requestKey.getUrl()).isEqualTo("a"); + assertThat(requestKey.getHeaders().size()).isEqualTo(1); + assertThat(requestKey.getHeaders().fetch("my-header")).isEqualTo(Arrays.asList("val")); + assertThat(requestKey.getCharset()).isEqualTo(StandardCharsets.UTF_16); } @SuppressWarnings("deprecation") @Test - public void create() throws Exception { - Map> map = new HashMap>(); + void create() throws Exception { + Map> map = new HashMap<>(); map.put("my-header", Arrays.asList("val")); Request request = Request.create( @@ -70,60 +62,58 @@ public void create() throws Exception { StandardCharsets.UTF_16); requestKey = RequestKey.create(request); - assertThat(requestKey.getMethod(), equalTo(HttpMethod.GET)); - assertThat(requestKey.getUrl(), equalTo("a")); - assertThat(requestKey.getHeaders().size(), is(1)); - assertThat( - requestKey.getHeaders().fetch("my-header"), - equalTo((Collection) Arrays.asList("val"))); - assertThat(requestKey.getCharset(), equalTo(StandardCharsets.UTF_16)); - assertThat(requestKey.getBody(), equalTo("content".getBytes(StandardCharsets.UTF_8))); + assertThat(requestKey.getMethod()).isEqualTo(HttpMethod.GET); + assertThat(requestKey.getUrl()).isEqualTo("a"); + assertThat(requestKey.getHeaders().size()).isEqualTo(1); + assertThat(requestKey.getHeaders().fetch("my-header")).isEqualTo(Arrays.asList("val")); + assertThat(requestKey.getCharset()).isEqualTo(StandardCharsets.UTF_16); + assertThat(requestKey.getBody()).isEqualTo("content".getBytes(StandardCharsets.UTF_8)); } @Test - public void checkHashes() { + void checkHashes() { RequestKey requestKey1 = RequestKey.builder(HttpMethod.GET, "a").build(); RequestKey requestKey2 = RequestKey.builder(HttpMethod.GET, "b").build(); - assertThat(requestKey1.hashCode(), not(equalTo(requestKey2.hashCode()))); - assertThat(requestKey1, not(equalTo(requestKey2))); + assertThat(requestKey1.hashCode()).isNotEqualTo(requestKey2.hashCode()); + assertThat(requestKey1).isNotEqualTo(requestKey2); } @Test - public void equalObject() { - assertThat(requestKey, not(equalTo(new Object()))); + void equalObject() { + assertThat(requestKey).isNotEqualTo(new Object()); } @Test - public void equalNull() { - assertThat(requestKey, not(equalTo(null))); + void equalNull() { + assertThat(requestKey).isNotEqualTo(null); } @Test - public void equalPost() { + void equalPost() { RequestKey requestKey1 = RequestKey.builder(HttpMethod.GET, "a").build(); RequestKey requestKey2 = RequestKey.builder(HttpMethod.POST, "a").build(); - assertThat(requestKey1.hashCode(), not(equalTo(requestKey2.hashCode()))); - assertThat(requestKey1, not(equalTo(requestKey2))); + assertThat(requestKey1.hashCode()).isNotEqualTo(requestKey2.hashCode()); + assertThat(requestKey1).isNotEqualTo(requestKey2); } @Test - public void equalSelf() { - assertThat(requestKey.hashCode(), equalTo(requestKey.hashCode())); - assertThat(requestKey, equalTo(requestKey)); + void equalSelf() { + assertThat(requestKey.hashCode()).isEqualTo(requestKey.hashCode()); + assertThat(requestKey).isEqualTo(requestKey); } @Test - public void equalMinimum() { + void equalMinimum() { RequestKey requestKey2 = RequestKey.builder(HttpMethod.GET, "a").build(); - assertThat(requestKey.hashCode(), equalTo(requestKey2.hashCode())); - assertThat(requestKey, equalTo(requestKey2)); + assertThat(requestKey.hashCode()).isEqualTo(requestKey2.hashCode()); + assertThat(requestKey).isEqualTo(requestKey2); } @Test - public void equalExtra() { + void equalExtra() { RequestHeaders headers = RequestHeaders.builder().add("my-other-header", "other value").build(); RequestKey requestKey2 = RequestKey.builder(HttpMethod.GET, "a") @@ -131,20 +121,20 @@ public void equalExtra() { .charset(StandardCharsets.ISO_8859_1) .build(); - assertThat(requestKey.hashCode(), equalTo(requestKey2.hashCode())); - assertThat(requestKey, equalTo(requestKey2)); + assertThat(requestKey.hashCode()).isEqualTo(requestKey2.hashCode()); + assertThat(requestKey).isEqualTo(requestKey2); } @Test - public void equalsExtended() { + void equalsExtended() { RequestKey requestKey2 = RequestKey.builder(HttpMethod.GET, "a").build(); - assertThat(requestKey.hashCode(), equalTo(requestKey2.hashCode())); - assertThat(requestKey.equalsExtended(requestKey2), equalTo(true)); + assertThat(requestKey.hashCode()).isEqualTo(requestKey2.hashCode()); + assertThat(requestKey.equalsExtended(requestKey2)).isEqualTo(true); } @Test - public void equalsExtendedExtra() { + void equalsExtendedExtra() { RequestHeaders headers = RequestHeaders.builder().add("my-other-header", "other value").build(); RequestKey requestKey2 = RequestKey.builder(HttpMethod.GET, "a") @@ -152,26 +142,22 @@ public void equalsExtendedExtra() { .charset(StandardCharsets.ISO_8859_1) .build(); - assertThat(requestKey.hashCode(), equalTo(requestKey2.hashCode())); - assertThat(requestKey.equalsExtended(requestKey2), equalTo(false)); + assertThat(requestKey.hashCode()).isEqualTo(requestKey2.hashCode()); + assertThat(requestKey.equalsExtended(requestKey2)).isEqualTo(false); } @Test - public void testToString() throws Exception { - assertThat(requestKey.toString(), startsWith("Request [GET a: ")); - assertThat( - requestKey.toString(), - both(containsString(" with my-header=[val] ")).and(containsString(" UTF-16]"))); + void testToString() throws Exception { + assertThat(requestKey.toString()).startsWith("Request [GET a: "); + assertThat(requestKey.toString()).contains(" with my-header=[val] ", " UTF-16]"); } @Test - public void testToStringSimple() throws Exception { + void toStringSimple() throws Exception { requestKey = RequestKey.builder(HttpMethod.GET, "a").build(); - assertThat(requestKey.toString(), startsWith("Request [GET a: ")); - assertThat( - requestKey.toString(), - both(containsString(" without ")).and(containsString(" no charset"))); + assertThat(requestKey.toString()).startsWith("Request [GET a: "); + assertThat(requestKey.toString()).contains(" without ", " no charset"); } } // diff --git a/moshi/src/test/java/feign/moshi/MoshiDecoderTest.java b/moshi/src/test/java/feign/moshi/MoshiDecoderTest.java index d2ba59ed3..d930e1615 100644 --- a/moshi/src/test/java/feign/moshi/MoshiDecoderTest.java +++ b/moshi/src/test/java/feign/moshi/MoshiDecoderTest.java @@ -14,9 +14,7 @@ package feign.moshi; import static feign.Util.UTF_8; -import static feign.assertj.FeignAssertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import com.squareup.moshi.JsonAdapter; import com.squareup.moshi.Moshi; @@ -27,12 +25,12 @@ import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class MoshiDecoderTest { +class MoshiDecoderTest { @Test - public void decodes() throws Exception { + void decodes() throws Exception { class Zone extends LinkedHashMap { @@ -65,7 +63,7 @@ class Zone extends LinkedHashMap { .body(zonesJson, UTF_8) .build(); - assertEquals(zones, new MoshiDecoder().decode(response, List.class)); + assertThat(new MoshiDecoder().decode(response, List.class)).isEqualTo(zones); } private String zonesJson = @@ -90,7 +88,7 @@ class Zone extends LinkedHashMap { + "}"; @Test - public void nullBodyDecodesToNull() throws Exception { + void nullBodyDecodesToNull() throws Exception { Response response = Response.builder() .status(204) @@ -100,11 +98,11 @@ public void nullBodyDecodesToNull() throws Exception { Request.create( Request.HttpMethod.GET, "/api", Collections.emptyMap(), null, Util.UTF_8)) .build(); - assertNull(new MoshiDecoder().decode(response, String.class)); + assertThat(new MoshiDecoder().decode(response, String.class)).isNull(); } @Test - public void emptyBodyDecodesToNull() throws Exception { + void emptyBodyDecodesToNull() throws Exception { Response response = Response.builder() .status(204) @@ -115,12 +113,12 @@ public void emptyBodyDecodesToNull() throws Exception { Request.HttpMethod.GET, "/api", Collections.emptyMap(), null, Util.UTF_8)) .body(new byte[0]) .build(); - assertNull(new MoshiDecoder().decode(response, String.class)); + assertThat(new MoshiDecoder().decode(response, String.class)).isNull(); } /** Enabled via {@link feign.Feign.Builder#dismiss404()} */ @Test - public void notFoundDecodesToEmpty() throws Exception { + void notFoundDecodesToEmpty() throws Exception { Response response = Response.builder() .status(404) @@ -134,7 +132,7 @@ public void notFoundDecodesToEmpty() throws Exception { } @Test - public void customDecoder() throws Exception { + void customDecoder() throws Exception { final UpperZoneJSONAdapter upperZoneAdapter = new UpperZoneJSONAdapter(); MoshiDecoder decoder = new MoshiDecoder(Collections.singleton(upperZoneAdapter)); @@ -154,11 +152,11 @@ public void customDecoder() throws Exception { .body(zonesJson, UTF_8) .build(); - assertEquals(zones, decoder.decode(response, UpperZoneJSONAdapter.class)); + assertThat(decoder.decode(response, UpperZoneJSONAdapter.class)).isEqualTo(zones); } @Test - public void customObjectDecoder() throws Exception { + void customObjectDecoder() throws Exception { final JsonAdapter videoGameJsonAdapter = new Moshi.Builder().build().adapter(VideoGame.class); diff --git a/moshi/src/test/java/feign/moshi/MoshiEncoderTest.java b/moshi/src/test/java/feign/moshi/MoshiEncoderTest.java index fe927caf4..893c6e73f 100644 --- a/moshi/src/test/java/feign/moshi/MoshiEncoderTest.java +++ b/moshi/src/test/java/feign/moshi/MoshiEncoderTest.java @@ -18,13 +18,18 @@ import com.squareup.moshi.JsonAdapter; import com.squareup.moshi.Moshi; import feign.RequestTemplate; -import java.util.*; -import org.junit.Test; +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; -public class MoshiEncoderTest { +class MoshiEncoderTest { @Test - public void encodesMapObjectNumericalValuesAsInteger() { + void encodesMapObjectNumericalValuesAsInteger() { Map map = new LinkedHashMap<>(); map.put("foo", 1); @@ -39,7 +44,7 @@ public void encodesMapObjectNumericalValuesAsInteger() { } @Test - public void encodesFormParams() { + void encodesFormParams() { Map form = new LinkedHashMap<>(); form.put("foo", 1); @@ -61,7 +66,7 @@ public void encodesFormParams() { } @Test - public void customEncoder() { + void customEncoder() { final UpperZoneJSONAdapter upperZoneAdapter = new UpperZoneJSONAdapter(); MoshiEncoder encoder = new MoshiEncoder(Collections.singleton(upperZoneAdapter)); @@ -88,7 +93,7 @@ public void customEncoder() { } @Test - public void customObjectEncoder() { + void customObjectEncoder() { final JsonAdapter videoGameJsonAdapter = new Moshi.Builder().build().adapter(VideoGame.class); MoshiEncoder encoder = new MoshiEncoder(Collections.singleton(videoGameJsonAdapter)); diff --git a/moshi/src/test/java/feign/moshi/UpperZoneJSONAdapter.java b/moshi/src/test/java/feign/moshi/UpperZoneJSONAdapter.java index fae5c9f4f..c0da0092e 100644 --- a/moshi/src/test/java/feign/moshi/UpperZoneJSONAdapter.java +++ b/moshi/src/test/java/feign/moshi/UpperZoneJSONAdapter.java @@ -13,13 +13,18 @@ */ package feign.moshi; -import com.squareup.moshi.*; +import com.squareup.moshi.FromJson; +import com.squareup.moshi.JsonAdapter; +import com.squareup.moshi.JsonReader; +import com.squareup.moshi.JsonWriter; +import com.squareup.moshi.ToJson; import java.io.IOException; import java.util.LinkedList; import java.util.Map; class UpperZoneJSONAdapter extends JsonAdapter> { + @Override @ToJson public void toJson(JsonWriter out, LinkedList value) throws IOException { out.beginArray(); @@ -33,6 +38,7 @@ public void toJson(JsonWriter out, LinkedList value) throws IOException { out.endArray(); } + @Override @FromJson public LinkedList fromJson(JsonReader in) throws IOException { LinkedList zones = new LinkedList<>(); diff --git a/okhttp/pom.xml b/okhttp/pom.xml index 81aa7cb74..150135e5a 100644 --- a/okhttp/pom.xml +++ b/okhttp/pom.xml @@ -53,7 +53,7 @@ com.squareup.okhttp3 - mockwebserver + mockwebserver3-junit5 test diff --git a/okhttp/src/test/java/feign/okhttp/OkHttpClientAsyncTest.java b/okhttp/src/test/java/feign/okhttp/OkHttpClientAsyncTest.java index c6ccf5a36..d16729801 100644 --- a/okhttp/src/test/java/feign/okhttp/OkHttpClientAsyncTest.java +++ b/okhttp/src/test/java/feign/okhttp/OkHttpClientAsyncTest.java @@ -14,11 +14,12 @@ package feign.okhttp; import static feign.assertj.MockWebServerAssertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; import static org.assertj.core.data.MapEntry.entry; -import static org.hamcrest.CoreMatchers.isA; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; @@ -75,20 +76,17 @@ import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.MockWebServer; +import mockwebserver3.MockResponse; +import mockwebserver3.MockWebServer; import okio.Buffer; -import org.assertj.core.api.Assertions; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; public class OkHttpClientAsyncTest { - @Rule public final ExpectedException thrown = ExpectedException.none(); - @Rule public final MockWebServer server = new MockWebServer(); + public final MockWebServer server = new MockWebServer(); @Test - public void iterableQueryParams() throws Exception { + void iterableQueryParams() throws Exception { server.enqueue(new MockResponse().setBody("foo")); final TestInterfaceAsync api = newAsyncBuilder().target("http://localhost:" + server.getPort()); @@ -99,7 +97,7 @@ public void iterableQueryParams() throws Exception { } @Test - public void postTemplateParamsResolve() throws Exception { + void postTemplateParamsResolve() throws Exception { server.enqueue(new MockResponse().setBody("foo")); final TestInterfaceAsync api = newAsyncBuilder().target("http://localhost:" + server.getPort()); @@ -113,18 +111,18 @@ public void postTemplateParamsResolve() throws Exception { } @Test - public void responseCoercesToStringBody() throws Throwable { + void responseCoercesToStringBody() throws Throwable { server.enqueue(new MockResponse().setBody("foo")); final TestInterfaceAsync api = newAsyncBuilder().target("http://localhost:" + server.getPort()); final Response response = unwrap(api.response()); - assertTrue(response.body().isRepeatable()); - assertEquals("foo", Util.toString(response.body().asReader(StandardCharsets.UTF_8))); + assertThat(response.body().isRepeatable()).isTrue(); + assertThat(Util.toString(response.body().asReader(StandardCharsets.UTF_8))).isEqualTo("foo"); } @Test - public void postFormParams() throws Exception { + void postFormParams() throws Exception { server.enqueue(new MockResponse().setBody("foo")); final TestInterfaceAsync api = newAsyncBuilder().target("http://localhost:" + server.getPort()); @@ -139,7 +137,7 @@ public void postFormParams() throws Exception { } @Test - public void postBodyParam() throws Exception { + void postBodyParam() throws Exception { server.enqueue(new MockResponse().setBody("foo")); final TestInterfaceAsync api = newAsyncBuilder().target("http://localhost:" + server.getPort()); @@ -158,10 +156,10 @@ public void postBodyParam() throws Exception { * type. */ @Test - public void bodyTypeCorrespondsWithParameterType() throws Exception { + void bodyTypeCorrespondsWithParameterType() throws Exception { server.enqueue(new MockResponse().setBody("foo")); - final AtomicReference encodedType = new AtomicReference(); + final AtomicReference encodedType = new AtomicReference<>(); final TestInterfaceAsync api = newAsyncBuilder() .encoder( @@ -177,13 +175,13 @@ public void encode(Object object, Type bodyType, RequestTemplate template) { server.takeRequest(); - Assertions.assertThat(encodedType.get()).isEqualTo(new TypeToken>() {}.getType()); + assertThat(encodedType.get()).isEqualTo(new TypeToken>() {}.getType()); checkCFCompletedSoon(cf); } @Test - public void singleInterceptor() throws Exception { + void singleInterceptor() throws Exception { server.enqueue(new MockResponse().setBody("foo")); final TestInterfaceAsync api = @@ -200,7 +198,7 @@ public void singleInterceptor() throws Exception { } @Test - public void multipleInterceptor() throws Exception { + void multipleInterceptor() throws Exception { server.enqueue(new MockResponse().setBody("foo")); final TestInterfaceAsync api = @@ -220,7 +218,7 @@ public void multipleInterceptor() throws Exception { } @Test - public void customExpander() throws Exception { + void customExpander() throws Exception { server.enqueue(new MockResponse()); final TestInterfaceAsync api = newAsyncBuilder().target("http://localhost:" + server.getPort()); @@ -233,7 +231,7 @@ public void customExpander() throws Exception { } @Test - public void customExpanderListParam() throws Exception { + void customExpanderListParam() throws Exception { server.enqueue(new MockResponse()); final TestInterfaceAsync api = newAsyncBuilder().target("http://localhost:" + server.getPort()); @@ -247,7 +245,7 @@ public void customExpanderListParam() throws Exception { } @Test - public void customExpanderNullParam() throws Exception { + void customExpanderNullParam() throws Exception { server.enqueue(new MockResponse()); final TestInterfaceAsync api = newAsyncBuilder().target("http://localhost:" + server.getPort()); @@ -260,12 +258,12 @@ public void customExpanderNullParam() throws Exception { } @Test - public void headerMap() throws Exception { + void headerMap() throws Exception { server.enqueue(new MockResponse()); final TestInterfaceAsync api = newAsyncBuilder().target("http://localhost:" + server.getPort()); - final Map headerMap = new LinkedHashMap(); + final Map headerMap = new LinkedHashMap<>(); headerMap.put("Content-Type", "myContent"); headerMap.put("Custom-Header", "fooValue"); final CompletableFuture cf = api.headerMap(headerMap); @@ -279,12 +277,12 @@ public void headerMap() throws Exception { } @Test - public void headerMapWithHeaderAnnotations() throws Exception { + void headerMapWithHeaderAnnotations() throws Exception { server.enqueue(new MockResponse()); final TestInterfaceAsync api = newAsyncBuilder().target("http://localhost:" + server.getPort()); - final Map headerMap = new LinkedHashMap(); + final Map headerMap = new LinkedHashMap<>(); headerMap.put("Custom-Header", "fooValue"); api.headerMapWithHeaderAnnotations(headerMap); @@ -312,12 +310,12 @@ public void headerMapWithHeaderAnnotations() throws Exception { } @Test - public void queryMap() throws Exception { + void queryMap() throws Exception { server.enqueue(new MockResponse()); final TestInterfaceAsync api = newAsyncBuilder().target("http://localhost:" + server.getPort()); - final Map queryMap = new LinkedHashMap(); + final Map queryMap = new LinkedHashMap<>(); queryMap.put("name", "alice"); queryMap.put("fooKey", "fooValue"); final CompletableFuture cf = api.queryMap(queryMap); @@ -328,15 +326,15 @@ public void queryMap() throws Exception { } @Test - public void queryMapIterableValuesExpanded() throws Exception { + void queryMapIterableValuesExpanded() throws Exception { server.enqueue(new MockResponse()); final TestInterfaceAsync api = newAsyncBuilder().target("http://localhost:" + server.getPort()); - final Map queryMap = new LinkedHashMap(); + final Map queryMap = new LinkedHashMap<>(); queryMap.put("name", Arrays.asList("Alice", "Bob")); queryMap.put("fooKey", "fooValue"); - queryMap.put("emptyListKey", new ArrayList()); + queryMap.put("emptyListKey", new ArrayList<>()); queryMap.put("emptyStringKey", ""); // empty values are ignored. final CompletableFuture cf = api.queryMap(queryMap); @@ -347,25 +345,25 @@ public void queryMapIterableValuesExpanded() throws Exception { } @Test - public void queryMapWithQueryParams() throws Exception { + void queryMapWithQueryParams() throws Exception { final TestInterfaceAsync api = newAsyncBuilder().target("http://localhost:" + server.getPort()); server.enqueue(new MockResponse()); - Map queryMap = new LinkedHashMap(); + Map queryMap = new LinkedHashMap<>(); queryMap.put("fooKey", "fooValue"); api.queryMapWithQueryParams("alice", queryMap); // query map should be expanded after built-in parameters assertThat(server.takeRequest()).hasPath("/?name=alice&fooKey=fooValue"); server.enqueue(new MockResponse()); - queryMap = new LinkedHashMap(); + queryMap = new LinkedHashMap<>(); queryMap.put("name", "bob"); api.queryMapWithQueryParams("alice", queryMap); // queries are additive assertThat(server.takeRequest()).hasPath("/?name=alice&name=bob"); server.enqueue(new MockResponse()); - queryMap = new LinkedHashMap(); + queryMap = new LinkedHashMap<>(); queryMap.put("name", null); api.queryMapWithQueryParams("alice", queryMap); // null value for a query map key removes query parameter @@ -373,36 +371,36 @@ public void queryMapWithQueryParams() throws Exception { } @Test - public void queryMapValueStartingWithBrace() throws Exception { + void queryMapValueStartingWithBrace() throws Exception { final TestInterfaceAsync api = newAsyncBuilder().target("http://localhost:" + server.getPort()); server.enqueue(new MockResponse()); - Map queryMap = new LinkedHashMap(); + Map queryMap = new LinkedHashMap<>(); queryMap.put("name", "{alice"); api.queryMap(queryMap); assertThat(server.takeRequest()).hasPath("/?name=%7Balice"); server.enqueue(new MockResponse()); - queryMap = new LinkedHashMap(); + queryMap = new LinkedHashMap<>(); queryMap.put("{name", "alice"); api.queryMap(queryMap); assertThat(server.takeRequest()).hasPath("/?%7Bname=alice"); server.enqueue(new MockResponse()); - queryMap = new LinkedHashMap(); + queryMap = new LinkedHashMap<>(); queryMap.put("name", "%7Balice"); api.queryMapEncoded(queryMap); assertThat(server.takeRequest()).hasPath("/?name=%7Balice"); server.enqueue(new MockResponse()); - queryMap = new LinkedHashMap(); + queryMap = new LinkedHashMap<>(); queryMap.put("%7Bname", "%7Balice"); api.queryMapEncoded(queryMap); assertThat(server.takeRequest()).hasPath("/?%7Bname=%7Balice"); } @Test - public void queryMapPojoWithFullParams() throws Exception { + void queryMapPojoWithFullParams() throws Exception { final TestInterfaceAsync api = newAsyncBuilder().target("http://localhost:" + server.getPort()); final CustomPojo customPojo = new CustomPojo("Name", 3); @@ -414,7 +412,7 @@ public void queryMapPojoWithFullParams() throws Exception { } @Test - public void queryMapPojoWithPartialParams() throws Exception { + void queryMapPojoWithPartialParams() throws Exception { final TestInterfaceAsync api = newAsyncBuilder().target("http://localhost:" + server.getPort()); final CustomPojo customPojo = new CustomPojo("Name", null); @@ -427,7 +425,7 @@ public void queryMapPojoWithPartialParams() throws Exception { } @Test - public void queryMapPojoWithEmptyParams() throws Exception { + void queryMapPojoWithEmptyParams() throws Exception { final TestInterfaceAsync api = newAsyncBuilder().target("http://localhost:" + server.getPort()); final CustomPojo customPojo = new CustomPojo(null, null); @@ -438,24 +436,23 @@ public void queryMapPojoWithEmptyParams() throws Exception { } @Test - public void configKeyFormatsAsExpected() throws Exception { - assertEquals( - "TestInterfaceAsync#post()", - Feign.configKey( - TestInterfaceAsync.class, TestInterfaceAsync.class.getDeclaredMethod("post"))); - assertEquals( - "TestInterfaceAsync#uriParam(String,URI,String)", - Feign.configKey( - TestInterfaceAsync.class, - TestInterfaceAsync.class.getDeclaredMethod( - "uriParam", String.class, URI.class, String.class))); + void configKeyFormatsAsExpected() throws Exception { + assertThat( + Feign.configKey( + TestInterfaceAsync.class, TestInterfaceAsync.class.getDeclaredMethod("post"))) + .isEqualTo("TestInterfaceAsync#post()"); + assertThat( + Feign.configKey( + TestInterfaceAsync.class, + TestInterfaceAsync.class.getDeclaredMethod( + "uriParam", String.class, URI.class, String.class))) + .isEqualTo("TestInterfaceAsync#uriParam(String,URI,String)"); } @Test - public void configKeyUsesChildType() throws Exception { - assertEquals( - "List#iterator()", - Feign.configKey(List.class, Iterable.class.getDeclaredMethod("iterator"))); + void configKeyUsesChildType() throws Exception { + assertThat(Feign.configKey(List.class, Iterable.class.getDeclaredMethod("iterator"))) + .isEqualTo("List#iterator()"); } private T unwrap(CompletableFuture cf) throws Throwable { @@ -467,21 +464,20 @@ private T unwrap(CompletableFuture cf) throws Throwable { } @Test - public void canOverrideErrorDecoder() throws Throwable { + void canOverrideErrorDecoder() throws Throwable { server.enqueue(new MockResponse().setResponseCode(400).setBody("foo")); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("bad zone name"); final TestInterfaceAsync api = newAsyncBuilder() .errorDecoder(new IllegalArgumentExceptionOn400()) .target("http://localhost:" + server.getPort()); - unwrap(api.post()); + Throwable exception = assertThrows(IllegalArgumentException.class, () -> unwrap(api.post())); + assertThat(exception.getMessage()).contains("bad zone name"); } @Test - public void overrideTypeSpecificDecoder() throws Throwable { + void overrideTypeSpecificDecoder() throws Throwable { server.enqueue(new MockResponse().setBody("success!")); final TestInterfaceAsync api = @@ -489,14 +485,12 @@ public void overrideTypeSpecificDecoder() throws Throwable { .decoder((response, type) -> "fail") .target("http://localhost:" + server.getPort()); - assertEquals("fail", unwrap(api.post())); + assertThat(unwrap(api.post())).isEqualTo("fail"); } @Test - public void doesntRetryAfterResponseIsSent() throws Throwable { + void doesntRetryAfterResponseIsSent() throws Throwable { server.enqueue(new MockResponse().setBody("success!")); - thrown.expect(FeignException.class); - thrown.expectMessage("timeout reading POST http://"); final TestInterfaceAsync api = newAsyncBuilder() @@ -508,11 +502,12 @@ public void doesntRetryAfterResponseIsSent() throws Throwable { final CompletableFuture cf = api.post(); server.takeRequest(); - unwrap(cf); + Throwable exception = assertThrows(FeignException.class, () -> unwrap(cf)); + assertThat(exception.getMessage()).contains("timeout reading POST http://"); } @Test - public void throwsFeignExceptionIncludingBody() throws Throwable { + void throwsFeignExceptionIncludingBody() throws Throwable { server.enqueue(new MockResponse().setBody("success!")); final TestInterfaceAsync api = @@ -528,16 +523,16 @@ public void throwsFeignExceptionIncludingBody() throws Throwable { try { unwrap(cf); } catch (final FeignException e) { - Assertions.assertThat(e.getMessage()) + assertThat(e.getMessage()) .isEqualTo("timeout reading POST http://localhost:" + server.getPort() + "/"); - Assertions.assertThat(e.contentUTF8()).isEqualTo("Request body"); + assertThat(e.contentUTF8()).isEqualTo("Request body"); return; } - fail(); + fail(""); } @Test - public void throwsFeignExceptionWithoutBody() { + void throwsFeignExceptionWithoutBody() { server.enqueue(new MockResponse().setBody("success!")); final TestInterfaceAsync api = @@ -551,16 +546,16 @@ public void throwsFeignExceptionWithoutBody() { try { api.noContent(); } catch (final FeignException e) { - Assertions.assertThat(e.getMessage()) + assertThat(e.getMessage()) .isEqualTo("timeout reading POST http://localhost:" + server.getPort() + "/"); - Assertions.assertThat(e.contentUTF8()).isEqualTo(""); + assertThat(e.contentUTF8()).isEqualTo(""); } } @SuppressWarnings("deprecation") @Test - public void whenReturnTypeIsResponseNoErrorHandling() throws Throwable { - final Map> headers = new LinkedHashMap>(); + void whenReturnTypeIsResponseNoErrorHandling() throws Throwable { + final Map> headers = new LinkedHashMap<>(); headers.put("Location", Arrays.asList("http://bar.com")); final Response response = Response.builder() @@ -585,9 +580,8 @@ public void whenReturnTypeIsResponseNoErrorHandling() throws Throwable { } @Test - public void okIfDecodeRootCauseHasNoMessage() throws Throwable { + void okIfDecodeRootCauseHasNoMessage() throws Throwable { server.enqueue(new MockResponse().setBody("success!")); - thrown.expect(DecodeException.class); final TestInterfaceAsync api = newAsyncBuilder() @@ -597,14 +591,12 @@ public void okIfDecodeRootCauseHasNoMessage() throws Throwable { }) .target("http://localhost:" + server.getPort()); - unwrap(api.post()); + assertThrows(DecodeException.class, () -> unwrap(api.post())); } @Test - public void decodingExceptionGetWrappedInDismiss404Mode() throws Throwable { + void decodingExceptionGetWrappedInDismiss404Mode() throws Throwable { server.enqueue(new MockResponse().setResponseCode(404)); - thrown.expect(DecodeException.class); - thrown.expectCause(isA(NoSuchElementException.class)); final TestInterfaceAsync api = newAsyncBuilder() @@ -616,29 +608,33 @@ public void decodingExceptionGetWrappedInDismiss404Mode() throws Throwable { }) .target("http://localhost:" + server.getPort()); - unwrap(api.post()); + DecodeException exception = assertThrows(DecodeException.class, () -> unwrap(api.post())); + assertThat(exception).hasCauseInstanceOf(NoSuchElementException.class); } @Test - public void decodingDoesNotSwallow404ErrorsInDismiss404Mode() throws Throwable { - server.enqueue(new MockResponse().setResponseCode(404)); - thrown.expect(IllegalArgumentException.class); - - final TestInterfaceAsync api = - newAsyncBuilder() - .dismiss404() - .errorDecoder(new IllegalArgumentExceptionOn404()) - .target("http://localhost:" + server.getPort()); - - final CompletableFuture cf = api.queryMap(Collections.emptyMap()); - server.takeRequest(); - unwrap(cf); + void decodingDoesNotSwallow404ErrorsInDismiss404Mode() throws Throwable { + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy( + () -> { + server.enqueue(new MockResponse().setResponseCode(404)); + + final TestInterfaceAsync api = + newAsyncBuilder() + .dismiss404() + .errorDecoder(new IllegalArgumentExceptionOn404()) + .target("http://localhost:" + server.getPort()); + + final CompletableFuture cf = + api.queryMap(Collections.emptyMap()); + server.takeRequest(); + unwrap(cf); + }); } @Test - public void okIfEncodeRootCauseHasNoMessage() throws Throwable { + void okIfEncodeRootCauseHasNoMessage() throws Throwable { server.enqueue(new MockResponse().setBody("success!")); - thrown.expect(EncodeException.class); final TestInterfaceAsync api = newAsyncBuilder() @@ -648,45 +644,44 @@ public void okIfEncodeRootCauseHasNoMessage() throws Throwable { }) .target("http://localhost:" + server.getPort()); - unwrap(api.body(Arrays.asList("foo"))); + assertThrows(EncodeException.class, () -> unwrap(api.body(Arrays.asList("foo")))); } @Test - public void equalsHashCodeAndToStringWork() { + void equalsHashCodeAndToStringWork() { final Target t1 = - new HardCodedTarget(TestInterfaceAsync.class, "http://localhost:8080"); + new HardCodedTarget<>(TestInterfaceAsync.class, "http://localhost:8080"); final Target t2 = - new HardCodedTarget(TestInterfaceAsync.class, "http://localhost:8888"); + new HardCodedTarget<>(TestInterfaceAsync.class, "http://localhost:8888"); final Target t3 = - new HardCodedTarget( - OtherTestInterfaceAsync.class, "http://localhost:8080"); + new HardCodedTarget<>(OtherTestInterfaceAsync.class, "http://localhost:8080"); final TestInterfaceAsync i1 = newAsyncBuilder().target(t1); final TestInterfaceAsync i2 = newAsyncBuilder().target(t1); final TestInterfaceAsync i3 = newAsyncBuilder().target(t2); final OtherTestInterfaceAsync i4 = newAsyncBuilder().target(t3); - Assertions.assertThat(i1).isEqualTo(i2).isNotEqualTo(i3).isNotEqualTo(i4); + assertThat(i1).isEqualTo(i2).isNotEqualTo(i3).isNotEqualTo(i4); - Assertions.assertThat(i1.hashCode()) + assertThat(i1.hashCode()) .isEqualTo(i2.hashCode()) .isNotEqualTo(i3.hashCode()) .isNotEqualTo(i4.hashCode()); - Assertions.assertThat(i1.toString()) + assertThat(i1.toString()) .isEqualTo(i2.toString()) .isNotEqualTo(i3.toString()) .isNotEqualTo(i4.toString()); - Assertions.assertThat(t1).isNotEqualTo(i1); + assertThat(t1).isNotEqualTo(i1); - Assertions.assertThat(t1.hashCode()).isEqualTo(i1.hashCode()); + assertThat(t1.hashCode()).isEqualTo(i1.hashCode()); - Assertions.assertThat(t1.toString()).isEqualTo(i1.toString()); + assertThat(t1.toString()).isEqualTo(i1.toString()); } @SuppressWarnings("resource") @Test - public void decodeLogicSupportsByteArray() throws Throwable { + void decodeLogicSupportsByteArray() throws Throwable { final byte[] expectedResponse = {12, 34, 56}; server.enqueue(new MockResponse().setBody(new Buffer().write(expectedResponse))); @@ -696,11 +691,11 @@ public void decodeLogicSupportsByteArray() throws Throwable { new HardCodedTarget<>( OtherTestInterfaceAsync.class, "http://localhost:" + server.getPort())); - Assertions.assertThat(unwrap(api.binaryResponseBody())).containsExactly(expectedResponse); + assertThat(unwrap(api.binaryResponseBody())).containsExactly(expectedResponse); } @Test - public void encodeLogicSupportsByteArray() throws Exception { + void encodeLogicSupportsByteArray() throws Exception { final byte[] expectedRequest = {12, 34, 56}; server.enqueue(new MockResponse()); @@ -719,7 +714,7 @@ public void encodeLogicSupportsByteArray() throws Exception { } @Test - public void encodedQueryParam() throws Exception { + void encodedQueryParam() throws Exception { server.enqueue(new MockResponse()); final TestInterfaceAsync api = newAsyncBuilder().target("http://localhost:" + server.getPort()); @@ -742,12 +737,12 @@ private void checkCFCompletedSoon(CompletableFuture cf) { } @Test - public void responseMapperIsAppliedBeforeDelegate() throws IOException { + void responseMapperIsAppliedBeforeDelegate() throws IOException { final ResponseMappingDecoder decoder = new ResponseMappingDecoder(upperCaseResponseMapper(), new StringDecoder()); final String output = (String) decoder.decode(responseWithText("response"), String.class); - Assertions.assertThat(output).isEqualTo("RESPONSE"); + assertThat(output).isEqualTo("RESPONSE"); } private static TestInterfaceAsyncBuilder newAsyncBuilder() { @@ -755,17 +750,13 @@ private static TestInterfaceAsyncBuilder newAsyncBuilder() { } private ResponseMapper upperCaseResponseMapper() { - return new ResponseMapper() { - @SuppressWarnings("deprecation") - @Override - public Response map(Response response, Type type) { - try { - return response.toBuilder() - .body(Util.toString(response.body().asReader()).toUpperCase().getBytes()) - .build(); - } catch (final IOException e) { - throw new RuntimeException(e); - } + return (response, type) -> { + try { + return response.toBuilder() + .body(Util.toString(response.body().asReader()).toUpperCase().getBytes()) + .build(); + } catch (final IOException e) { + throw new RuntimeException(e); } }; } @@ -781,7 +772,7 @@ private Response responseWithText(String text) { } @Test - public void mapAndDecodeExecutesMapFunction() throws Throwable { + void mapAndDecodeExecutesMapFunction() throws Throwable { server.enqueue(new MockResponse().setBody("response!")); final TestInterfaceAsync api = @@ -789,11 +780,11 @@ public void mapAndDecodeExecutesMapFunction() throws Throwable { .mapAndDecode(upperCaseResponseMapper(), new StringDecoder()) .target(TestInterfaceAsync.class, "http://localhost:" + server.getPort()); - assertEquals("RESPONSE!", unwrap(api.post())); + assertThat(unwrap(api.post())).isEqualTo("RESPONSE!"); } @Test - public void beanQueryMapEncoderWithPrivateGetterIgnored() throws Exception { + void beanQueryMapEncoderWithPrivateGetterIgnored() throws Exception { final TestInterfaceAsync api = newAsyncBuilder() .queryMapEndcoder(new BeanQueryMapEncoder()) @@ -811,7 +802,7 @@ public void beanQueryMapEncoderWithPrivateGetterIgnored() throws Exception { } @Test - public void queryMap_with_child_pojo() throws Exception { + void queryMap_with_child_pojo() throws Exception { final TestInterfaceAsync api = newAsyncBuilder() .queryMapEndcoder(new FieldQueryMapEncoder()) @@ -833,7 +824,7 @@ public void queryMap_with_child_pojo() throws Exception { } @Test - public void beanQueryMapEncoderWithNullValueIgnored() throws Exception { + void beanQueryMapEncoderWithNullValueIgnored() throws Exception { final TestInterfaceAsync api = newAsyncBuilder() .queryMapEndcoder(new BeanQueryMapEncoder()) @@ -852,7 +843,7 @@ public void beanQueryMapEncoderWithNullValueIgnored() throws Exception { } @Test - public void beanQueryMapEncoderWithEmptyParams() throws Exception { + void beanQueryMapEncoderWithEmptyParams() throws Exception { final TestInterfaceAsync api = newAsyncBuilder() .queryMapEndcoder(new BeanQueryMapEncoder()) @@ -1103,4 +1094,9 @@ public Instant instant() { return Instant.ofEpochMilli(millis); } } + + @AfterEach + void afterEachTest() throws IOException { + server.close(); + } } diff --git a/okhttp/src/test/java/feign/okhttp/OkHttpClientTest.java b/okhttp/src/test/java/feign/okhttp/OkHttpClientTest.java index 8f60216a1..f0ca0b6c7 100644 --- a/okhttp/src/test/java/feign/okhttp/OkHttpClientTest.java +++ b/okhttp/src/test/java/feign/okhttp/OkHttpClientTest.java @@ -13,8 +13,8 @@ */ package feign.okhttp; -import static org.junit.Assert.assertEquals; -import static org.junit.Assume.assumeFalse; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assumptions.assumeFalse; import feign.Feign; import feign.Feign.Builder; @@ -28,9 +28,9 @@ import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.concurrent.TimeUnit; -import okhttp3.mockwebserver.MockResponse; +import mockwebserver3.MockResponse; import org.assertj.core.data.MapEntry; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** Tests client-specific behavior, such as ensuring Content-Length is sent when specified. */ public class OkHttpClientTest extends AbstractClientTest { @@ -49,7 +49,7 @@ public void testContentTypeWithoutCharset() throws Exception { Response response = api.getWithContentType(); // Response length should not be null - assertEquals("AAAAAAAA", Util.toString(response.body().asReader(Util.UTF_8))); + assertThat(Util.toString(response.body().asReader(Util.UTF_8))).isEqualTo("AAAAAAAA"); MockWebServerAssertions.assertThat(server.takeRequest()) .hasHeaders( @@ -59,7 +59,7 @@ public void testContentTypeWithoutCharset() throws Exception { } @Test - public void testNoFollowRedirect() throws Exception { + void noFollowRedirect() throws Exception { server.enqueue( new MockResponse().setResponseCode(302).addHeader("Location", server.url("redirect"))); // Enqueue a response to fail fast if the redirect is followed, instead of waiting for the @@ -76,13 +76,13 @@ public void testNoFollowRedirect() throws Exception { Response response = api.get(); // Response length should not be null - assertEquals(302, response.status()); - assertEquals( - server.url("redirect").toString(), response.headers().get("Location").iterator().next()); + assertThat(response.status()).isEqualTo(302); + assertThat(response.headers().get("Location").iterator().next()) + .isEqualTo(server.url("redirect").toString()); } @Test - public void testFollowRedirect() throws Exception { + void followRedirect() throws Exception { String expectedBody = "Hello"; server.enqueue( @@ -99,9 +99,9 @@ public void testFollowRedirect() throws Exception { Response response = api.get(); // Response length should not be null - assertEquals(200, response.status()); + assertThat(response.status()).isEqualTo(200); String payload = Util.toString(response.body().asReader(StandardCharsets.UTF_8)); - assertEquals(expectedBody, payload); + assertThat(payload).isEqualTo(expectedBody); } /* @@ -112,27 +112,27 @@ public void testFollowRedirect() throws Exception { */ @Override public void canSupportGzip() throws Exception { - assumeFalse("OkHTTP client do not support gzip compression", false); + assumeFalse(false, "OkHTTP client do not support gzip compression"); } @Override public void canSupportGzipOnError() throws Exception { - assumeFalse("OkHTTP client do not support gzip compression", false); + assumeFalse(false, "OkHTTP client do not support gzip compression"); } @Override public void canSupportDeflate() throws Exception { - assumeFalse("OkHTTP client do not support deflate compression", false); + assumeFalse(false, "OkHTTP client do not support deflate compression"); } @Override public void canSupportDeflateOnError() throws Exception { - assumeFalse("OkHTTP client do not support deflate compression", false); + assumeFalse(false, "OkHTTP client do not support deflate compression"); } @Override public void canExceptCaseInsensitiveHeader() throws Exception { - assumeFalse("OkHTTP client do not support gzip compression", false); + assumeFalse(false, "OkHTTP client do not support gzip compression"); } public interface OkHttpClientTestInterface { diff --git a/pom.xml b/pom.xml index 5bf090f2f..c77b78ead 100644 --- a/pom.xml +++ b/pom.xml @@ -83,7 +83,7 @@ ${project.basedir} - 4.12.0 + 5.0.0-alpha.11 32.1.3-jre 1.43.3 2.10.1 @@ -91,11 +91,9 @@ 2.0.9 20231013 - 4.13.2 5.10.1 2.16.0 3.24.2 - 2.2 5.8.0 3.11.0 @@ -287,11 +285,6 @@ test - - junit - junit - ${junit.version} - org.junit junit-bom @@ -300,12 +293,6 @@ import - - org.hamcrest - hamcrest - ${hamcrest.version} - - com.google.code.gson gson @@ -391,14 +378,13 @@ - junit - junit + org.junit.jupiter + junit-jupiter-api test - org.junit.jupiter - junit-jupiter-params + junit-jupiter test diff --git a/reactive/pom.xml b/reactive/pom.xml index 47edffb69..559303001 100644 --- a/reactive/pom.xml +++ b/reactive/pom.xml @@ -37,7 +37,6 @@ io.github.openfeign feign-core - ${project.version} org.reactivestreams @@ -64,10 +63,15 @@ ${mockito.version} test + + org.mockito + mockito-junit-jupiter + ${mockito.version} + test + io.github.openfeign feign-jackson - ${project.version} test @@ -79,18 +83,16 @@ io.github.openfeign feign-okhttp - ${project.version} test io.github.openfeign feign-jaxrs - ${project.version} test com.squareup.okhttp3 - mockwebserver + mockwebserver3-junit5 test diff --git a/reactive/src/test/java/feign/reactive/ReactiveDelegatingContractTest.java b/reactive/src/test/java/feign/reactive/ReactiveDelegatingContractTest.java index d6e47f5dd..77be7dea7 100644 --- a/reactive/src/test/java/feign/reactive/ReactiveDelegatingContractTest.java +++ b/reactive/src/test/java/feign/reactive/ReactiveDelegatingContractTest.java @@ -13,45 +13,49 @@ */ package feign.reactive; +import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; + import feign.Contract; import feign.Param; import feign.RequestLine; import io.reactivex.Flowable; import java.util.stream.Stream; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; -public class ReactiveDelegatingContractTest { - - @Rule public ExpectedException thrown = ExpectedException.none(); +class ReactiveDelegatingContractTest { @Test - public void onlyReactiveReturnTypesSupported() { - this.thrown.expect(IllegalArgumentException.class); - Contract contract = new ReactiveDelegatingContract(new Contract.Default()); - contract.parseAndValidateMetadata(TestSynchronousService.class); + void onlyReactiveReturnTypesSupported() { + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy( + () -> { + Contract contract = new ReactiveDelegatingContract(new Contract.Default()); + contract.parseAndValidateMetadata(TestSynchronousService.class); + }); } @Test - public void reactorTypes() { + void reactorTypes() { Contract contract = new ReactiveDelegatingContract(new Contract.Default()); contract.parseAndValidateMetadata(TestReactorService.class); } @Test - public void reactivexTypes() { + void reactivexTypes() { Contract contract = new ReactiveDelegatingContract(new Contract.Default()); contract.parseAndValidateMetadata(TestReactiveXService.class); } @Test - public void streamsAreNotSupported() { - this.thrown.expect(IllegalArgumentException.class); - Contract contract = new ReactiveDelegatingContract(new Contract.Default()); - contract.parseAndValidateMetadata(StreamsService.class); + void streamsAreNotSupported() { + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy( + () -> { + Contract contract = new ReactiveDelegatingContract(new Contract.Default()); + contract.parseAndValidateMetadata(StreamsService.class); + }); } public interface TestSynchronousService { diff --git a/reactive/src/test/java/feign/reactive/ReactiveFeignIntegrationTest.java b/reactive/src/test/java/feign/reactive/ReactiveFeignIntegrationTest.java index cfc46c6cc..0cbf0ad10 100644 --- a/reactive/src/test/java/feign/reactive/ReactiveFeignIntegrationTest.java +++ b/reactive/src/test/java/feign/reactive/ReactiveFeignIntegrationTest.java @@ -14,6 +14,8 @@ package feign.reactive; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; @@ -23,15 +25,29 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import feign.*; +import feign.Client; +import feign.FeignIgnore; +import feign.Logger; import feign.Logger.Level; +import feign.Param; +import feign.QueryMap; +import feign.QueryMapEncoder; +import feign.Request; import feign.Request.Options; +import feign.RequestInterceptor; +import feign.RequestLine; +import feign.RequestTemplate; +import feign.Response; +import feign.ResponseMapper; +import feign.RetryableException; +import feign.Retryer; import feign.codec.Decoder; import feign.codec.ErrorDecoder; import feign.jackson.JacksonDecoder; import feign.jackson.JacksonEncoder; import feign.jaxrs.JAXRSContract; import io.reactivex.Flowable; +import java.io.IOException; import java.lang.reflect.Type; import java.nio.charset.Charset; import java.util.Arrays; @@ -39,12 +55,10 @@ import java.util.List; import javax.ws.rs.GET; import javax.ws.rs.Path; -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.MockWebServer; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import mockwebserver3.MockResponse; +import mockwebserver3.MockWebServer; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.mockito.AdditionalAnswers; import org.mockito.stubbing.Answer; import reactor.core.publisher.Flux; @@ -53,22 +67,20 @@ public class ReactiveFeignIntegrationTest { - @Rule public ExpectedException thrown = ExpectedException.none(); - - @Rule public final MockWebServer webServer = new MockWebServer(); + public final MockWebServer webServer = new MockWebServer(); private String getServerUrl() { return "http://localhost:" + this.webServer.getPort(); } @Test - public void testCallIgnoredMethod() throws Exception { + void callIgnoredMethod() throws Exception { TestReactorService service = ReactorFeign.builder().target(TestReactorService.class, this.getServerUrl()); try { service.ignore().subscribe(); - Assert.fail("No exception thrown"); + fail("No exception thrown"); } catch (Exception e) { assertThat(e.getClass()).isEqualTo(UnsupportedOperationException.class); assertThat(e.getMessage()).isEqualTo("Method \"ignore\" should not be called"); @@ -76,7 +88,7 @@ public void testCallIgnoredMethod() throws Exception { } @Test - public void testDefaultMethodsNotProxied() { + void defaultMethodsNotProxied() { TestReactorService service = ReactorFeign.builder().target(TestReactorService.class, this.getServerUrl()); assertThat(service).isEqualTo(service); @@ -85,7 +97,7 @@ public void testDefaultMethodsNotProxied() { } @Test - public void testReactorTargetFull() throws Exception { + void reactorTargetFull() throws Exception { this.webServer.enqueue(new MockResponse().setBody("1.0")); this.webServer.enqueue(new MockResponse().setBody("{ \"username\": \"test\" }")); this.webServer.enqueue(new MockResponse().setBody("[{ \"username\": \"test\" }]")); @@ -127,7 +139,7 @@ public void testReactorTargetFull() throws Exception { } @Test - public void testRxJavaTarget() throws Exception { + void rxJavaTarget() throws Exception { this.webServer.enqueue(new MockResponse().setBody("1.0")); this.webServer.enqueue(new MockResponse().setBody("{ \"username\": \"test\" }")); this.webServer.enqueue(new MockResponse().setBody("[{ \"username\": \"test\" }]")); @@ -160,23 +172,29 @@ public void testRxJavaTarget() throws Exception { } @Test - public void invocationFactoryIsNotSupported() { - this.thrown.expect(UnsupportedOperationException.class); - ReactorFeign.builder() - .invocationHandlerFactory((target, dispatch) -> null) - .target(TestReactiveXService.class, "http://localhost"); + void invocationFactoryIsNotSupported() { + assertThatExceptionOfType(UnsupportedOperationException.class) + .isThrownBy( + () -> { + ReactorFeign.builder() + .invocationHandlerFactory((target, dispatch) -> null) + .target(TestReactiveXService.class, "http://localhost"); + }); } @Test - public void doNotCloseUnsupported() { - this.thrown.expect(UnsupportedOperationException.class); - ReactorFeign.builder() - .doNotCloseAfterDecode() - .target(TestReactiveXService.class, "http://localhost"); + void doNotCloseUnsupported() { + assertThatExceptionOfType(UnsupportedOperationException.class) + .isThrownBy( + () -> { + ReactorFeign.builder() + .doNotCloseAfterDecode() + .target(TestReactiveXService.class, "http://localhost"); + }); } @Test - public void testRequestInterceptor() { + void requestInterceptor() { this.webServer.enqueue(new MockResponse().setBody("1.0")); RequestInterceptor mockInterceptor = mock(RequestInterceptor.class); @@ -190,7 +208,7 @@ public void testRequestInterceptor() { } @Test - public void testRequestInterceptors() { + void requestInterceptors() { this.webServer.enqueue(new MockResponse().setBody("1.0")); RequestInterceptor mockInterceptor = mock(RequestInterceptor.class); @@ -204,7 +222,7 @@ public void testRequestInterceptors() { } @Test - public void testResponseMappers() throws Exception { + void responseMappers() throws Exception { this.webServer.enqueue(new MockResponse().setBody("1.0")); ResponseMapper responseMapper = mock(ResponseMapper.class); @@ -223,7 +241,7 @@ public void testResponseMappers() throws Exception { } @Test - public void testQueryMapEncoders() { + void queryMapEncoders() { this.webServer.enqueue(new MockResponse().setBody("No Results Found")); QueryMapEncoder encoder = mock(QueryMapEncoder.class); @@ -242,7 +260,7 @@ public void testQueryMapEncoders() { @SuppressWarnings({"ThrowableNotThrown"}) @Test - public void testErrorDecoder() { + void errorDecoder() { this.webServer.enqueue(new MockResponse().setBody("Bad Request").setResponseCode(400)); ErrorDecoder errorDecoder = mock(ErrorDecoder.class); @@ -262,7 +280,7 @@ public void testErrorDecoder() { } @Test - public void testRetryer() { + void retryer() { this.webServer.enqueue(new MockResponse().setBody("Not Available").setResponseCode(-1)); this.webServer.enqueue(new MockResponse().setBody("1.0")); @@ -279,7 +297,7 @@ public void testRetryer() { } @Test - public void testClient() throws Exception { + void client() throws Exception { Client client = mock(Client.class); given(client.execute(any(Request.class), any(Options.class))) .willAnswer( @@ -302,7 +320,7 @@ public void testClient() throws Exception { } @Test - public void testDifferentContract() throws Exception { + void differentContract() throws Exception { this.webServer.enqueue(new MockResponse().setBody("1.0")); TestJaxRSReactorService service = @@ -382,4 +400,9 @@ protected void log(String configKey, String format, Object... args) { System.out.println(String.format(methodTag(configKey) + format, args)); } } + + @AfterEach + void afterEachTest() throws IOException { + webServer.close(); + } } diff --git a/reactive/src/test/java/feign/reactive/ReactiveInvocationHandlerTest.java b/reactive/src/test/java/feign/reactive/ReactiveInvocationHandlerTest.java index 54321674c..1578399e0 100644 --- a/reactive/src/test/java/feign/reactive/ReactiveInvocationHandlerTest.java +++ b/reactive/src/test/java/feign/reactive/ReactiveInvocationHandlerTest.java @@ -27,17 +27,17 @@ import java.io.IOException; import java.lang.reflect.Method; import java.util.Collections; -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 reactor.core.publisher.Mono; import reactor.core.scheduler.Schedulers; import reactor.test.StepVerifier; -@RunWith(MockitoJUnitRunner.class) -public class ReactiveInvocationHandlerTest { +@ExtendWith(MockitoExtension.class) +class ReactiveInvocationHandlerTest { @Mock private Target target; @@ -45,14 +45,14 @@ public class ReactiveInvocationHandlerTest { private Method method; - @Before - public void setUp() throws NoSuchMethodException { + @BeforeEach + void setUp() throws NoSuchMethodException { method = TestReactorService.class.getMethod("version"); } @SuppressWarnings("unchecked") @Test - public void invokeOnSubscribeReactor() throws Throwable { + void invokeOnSubscribeReactor() throws Throwable { given(this.methodHandler.invoke(any())).willReturn("Result"); ReactorInvocationHandler handler = new ReactorInvocationHandler( @@ -70,7 +70,7 @@ public void invokeOnSubscribeReactor() throws Throwable { } @Test - public void invokeOnSubscribeEmptyReactor() throws Throwable { + void invokeOnSubscribeEmptyReactor() throws Throwable { given(this.methodHandler.invoke(any())).willReturn(null); ReactorInvocationHandler handler = new ReactorInvocationHandler( @@ -88,7 +88,7 @@ public void invokeOnSubscribeEmptyReactor() throws Throwable { } @Test - public void invokeFailureReactor() throws Throwable { + void invokeFailureReactor() throws Throwable { given(this.methodHandler.invoke(any())).willThrow(new IOException("Could Not Decode")); ReactorInvocationHandler handler = new ReactorInvocationHandler( @@ -107,7 +107,7 @@ public void invokeFailureReactor() throws Throwable { @SuppressWarnings("unchecked") @Test - public void invokeOnSubscribeRxJava() throws Throwable { + void invokeOnSubscribeRxJava() throws Throwable { given(this.methodHandler.invoke(any())).willReturn("Result"); RxJavaInvocationHandler handler = new RxJavaInvocationHandler( @@ -125,7 +125,7 @@ public void invokeOnSubscribeRxJava() throws Throwable { } @Test - public void invokeOnSubscribeEmptyRxJava() throws Throwable { + void invokeOnSubscribeEmptyRxJava() throws Throwable { given(this.methodHandler.invoke(any())).willReturn(null); RxJavaInvocationHandler handler = new RxJavaInvocationHandler( @@ -143,7 +143,7 @@ public void invokeOnSubscribeEmptyRxJava() throws Throwable { } @Test - public void invokeFailureRxJava() throws Throwable { + void invokeFailureRxJava() throws Throwable { given(this.methodHandler.invoke(any())).willThrow(new IOException("Could Not Decode")); RxJavaInvocationHandler handler = new RxJavaInvocationHandler( diff --git a/ribbon/pom.xml b/ribbon/pom.xml index d4c9b9fe2..3635c43d8 100644 --- a/ribbon/pom.xml +++ b/ribbon/pom.xml @@ -77,7 +77,7 @@ com.squareup.okhttp3 - mockwebserver + mockwebserver3-junit5 test diff --git a/ribbon/src/test/java/feign/ribbon/LBClientFactoryTest.java b/ribbon/src/test/java/feign/ribbon/LBClientFactoryTest.java index c4c55643d..18682fe8f 100644 --- a/ribbon/src/test/java/feign/ribbon/LBClientFactoryTest.java +++ b/ribbon/src/test/java/feign/ribbon/LBClientFactoryTest.java @@ -13,18 +13,19 @@ */ package feign.ribbon; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import com.netflix.client.ClientFactory; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class LBClientFactoryTest { +class LBClientFactoryTest { @Test - public void testCreateLBClient() { + void createLBClient() { LBClientFactory.Default lbClientFactory = new LBClientFactory.Default(); LBClient client = lbClientFactory.create("clientName"); - assertEquals("clientName", client.getClientName()); - assertEquals(ClientFactory.getNamedLoadBalancer("clientName"), client.getLoadBalancer()); + assertThat(client.getClientName()).isEqualTo("clientName"); + assertThat(client.getLoadBalancer()) + .isEqualTo(ClientFactory.getNamedLoadBalancer("clientName")); } } diff --git a/ribbon/src/test/java/feign/ribbon/LBClientTest.java b/ribbon/src/test/java/feign/ribbon/LBClientTest.java index 12424f896..9d1dc94b9 100644 --- a/ribbon/src/test/java/feign/ribbon/LBClientTest.java +++ b/ribbon/src/test/java/feign/ribbon/LBClientTest.java @@ -24,13 +24,13 @@ import java.util.Collection; import java.util.LinkedHashMap; import java.util.Map; -import org.junit.Test; +import org.junit.jupiter.api.Test; @SuppressWarnings("deprecation") -public class LBClientTest { +class LBClientTest { @Test - public void testParseCodes() { + void parseCodes() { assertThat(LBClient.parseStatusCodes("")).isEmpty(); assertThat(LBClient.parseStatusCodes(null)).isEmpty(); assertThat(LBClient.parseStatusCodes("504")).contains(504); @@ -38,13 +38,13 @@ public void testParseCodes() { } @Test - public void testRibbonRequest() throws URISyntaxException { + void ribbonRequest() throws URISyntaxException { // test for RibbonRequest.toRequest() // the url has a query whose value is an encoded json string String urlWithEncodedJson = "http://test.feign.com/p?q=%7b%22a%22%3a1%7d"; HttpMethod method = HttpMethod.GET; URI uri = new URI(urlWithEncodedJson); - Map> headers = new LinkedHashMap>(); + Map> headers = new LinkedHashMap<>(); // create a Request for recreating another Request by toRequest() Request requestOrigin = Request.create(method, uri.toASCIIString(), headers, null, Charset.forName("utf-8")); diff --git a/ribbon/src/test/java/feign/ribbon/LoadBalancingTargetTest.java b/ribbon/src/test/java/feign/ribbon/LoadBalancingTargetTest.java index 4fff8e5c2..61b3179df 100644 --- a/ribbon/src/test/java/feign/ribbon/LoadBalancingTargetTest.java +++ b/ribbon/src/test/java/feign/ribbon/LoadBalancingTargetTest.java @@ -14,21 +14,21 @@ package feign.ribbon; import static com.netflix.config.ConfigurationManager.getConfigInstance; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import feign.Feign; import feign.RequestLine; import java.io.IOException; import java.net.URL; -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.MockWebServer; -import org.junit.Rule; -import org.junit.Test; +import mockwebserver3.MockResponse; +import mockwebserver3.MockWebServer; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; public class LoadBalancingTargetTest { - @Rule public final MockWebServer server1 = new MockWebServer(); - @Rule public final MockWebServer server2 = new MockWebServer(); + public final MockWebServer server1 = new MockWebServer(); + public final MockWebServer server2 = new MockWebServer(); static String hostAndPort(URL url) { // our build slaves have underscores in their hostnames which aren't permitted by ribbon @@ -36,7 +36,7 @@ static String hostAndPort(URL url) { } @Test - public void loadBalancingDefaultPolicyRoundRobin() throws IOException, InterruptedException { + void loadBalancingDefaultPolicyRoundRobin() throws IOException, InterruptedException { String name = "LoadBalancingTargetTest-loadBalancingDefaultPolicyRoundRobin"; String serverListKey = name + ".ribbon.listOfServers"; @@ -56,8 +56,8 @@ public void loadBalancingDefaultPolicyRoundRobin() throws IOException, Interrupt api.post(); api.post(); - assertEquals(1, server1.getRequestCount()); - assertEquals(1, server2.getRequestCount()); + assertThat(server1.getRequestCount()).isEqualTo(1); + assertThat(server2.getRequestCount()).isEqualTo(1); // TODO: verify ribbon stats match // assertEquals(target.lb().getLoadBalancerStats().getSingleServerStat()) } finally { @@ -66,7 +66,7 @@ public void loadBalancingDefaultPolicyRoundRobin() throws IOException, Interrupt } @Test - public void loadBalancingTargetPath() throws InterruptedException { + void loadBalancingTargetPath() throws InterruptedException { String name = "LoadBalancingTargetTest-loadBalancingDefaultPolicyRoundRobin"; String serverListKey = name + ".ribbon.listOfServers"; @@ -81,8 +81,8 @@ public void loadBalancingTargetPath() throws InterruptedException { api.get(); - assertEquals("http:///context-path", target.url()); - assertEquals("/context-path/servers", server1.takeRequest().getPath()); + assertThat(target.url()).isEqualTo("http:///context-path"); + assertThat(server1.takeRequest().getPath()).isEqualTo("/context-path/servers"); } finally { getConfigInstance().clearProperty(serverListKey); } @@ -96,4 +96,9 @@ interface TestInterface { @RequestLine("GET /servers") void get(); } + + @AfterEach + void afterEachTest() throws IOException { + server2.close(); + } } diff --git a/ribbon/src/test/java/feign/ribbon/PropagateFirstIOExceptionTest.java b/ribbon/src/test/java/feign/ribbon/PropagateFirstIOExceptionTest.java index d58adc52e..1993e5faa 100644 --- a/ribbon/src/test/java/feign/ribbon/PropagateFirstIOExceptionTest.java +++ b/ribbon/src/test/java/feign/ribbon/PropagateFirstIOExceptionTest.java @@ -13,32 +13,35 @@ */ package feign.ribbon; -import static org.hamcrest.CoreMatchers.isA; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.junit.jupiter.api.Assertions.assertThrows; import com.netflix.client.ClientException; import java.io.IOException; import java.net.ConnectException; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; -public class PropagateFirstIOExceptionTest { - - @Rule public ExpectedException thrown = ExpectedException.none(); +class PropagateFirstIOExceptionTest { @Test - public void propagatesNestedIOE() throws IOException { - thrown.expect(IOException.class); - - RibbonClient.propagateFirstIOException(new ClientException(new IOException())); + void propagatesNestedIOE() throws IOException { + assertThatExceptionOfType(IOException.class) + .isThrownBy( + () -> { + RibbonClient.propagateFirstIOException(new ClientException(new IOException())); + }); } @Test - public void propagatesFirstNestedIOE() throws IOException { - thrown.expect(IOException.class); - thrown.expectCause(isA(IOException.class)); - - RibbonClient.propagateFirstIOException(new ClientException(new IOException(new IOException()))); + void propagatesFirstNestedIOE() throws IOException { + IOException exception = + assertThrows( + IOException.class, + () -> + RibbonClient.propagateFirstIOException( + new ClientException(new IOException(new IOException())))); + assertThat(exception).hasCauseInstanceOf(IOException.class); } /** @@ -46,15 +49,17 @@ public void propagatesFirstNestedIOE() throws IOException { * exception */ @Test - public void propagatesDoubleNestedIOE() throws IOException { - thrown.expect(ConnectException.class); - - RibbonClient.propagateFirstIOException( - new ClientException(new RuntimeException(new ConnectException()))); + void propagatesDoubleNestedIOE() throws IOException { + assertThatExceptionOfType(ConnectException.class) + .isThrownBy( + () -> { + RibbonClient.propagateFirstIOException( + new ClientException(new RuntimeException(new ConnectException()))); + }); } @Test - public void doesntPropagateWhenNotIOE() throws IOException { + void doesntPropagateWhenNotIOE() throws IOException { RibbonClient.propagateFirstIOException(new ClientException(new RuntimeException())); } } diff --git a/ribbon/src/test/java/feign/ribbon/RibbonClientTest.java b/ribbon/src/test/java/feign/ribbon/RibbonClientTest.java index 63659cd50..da7a9f842 100644 --- a/ribbon/src/test/java/feign/ribbon/RibbonClientTest.java +++ b/ribbon/src/test/java/feign/ribbon/RibbonClientTest.java @@ -15,13 +15,7 @@ import static com.netflix.config.ConfigurationManager.getConfigInstance; import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.core.IsEqual.equalTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.fail; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.IClientConfig; @@ -35,42 +29,44 @@ import feign.Retryer; import feign.client.TrustingSSLSocketFactory; import java.io.IOException; +import java.lang.reflect.Method; import java.net.URI; import java.net.URL; import java.util.Collection; +import java.util.Optional; import java.util.concurrent.TimeUnit; -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.MockWebServer; -import okhttp3.mockwebserver.SocketPolicy; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TestName; - -@Ignore("inconsistent, deprecated toolset") +import mockwebserver3.MockResponse; +import mockwebserver3.MockWebServer; +import mockwebserver3.SocketPolicy; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInfo; + +@Disabled("inconsistent, deprecated toolset") public class RibbonClientTest { - @Rule public final TestName testName = new TestName(); - @Rule public final MockWebServer server1 = new MockWebServer(); - @Rule public final MockWebServer server2 = new MockWebServer(); + public String testName; + public final MockWebServer server1 = new MockWebServer(); + public final MockWebServer server2 = new MockWebServer(); private static String oldRetryConfig = null; private static final String SUN_RETRY_PROPERTY = "sun.net.http.retryPost"; - @BeforeClass - public static void disableSunRetry() throws Exception { + @BeforeAll + static void disableSunRetry() throws Exception { // The Sun HTTP Client retries all requests once on an IOException, which makes testing retry // code harder than would // be ideal. We can only disable it for post, so lets at least do that. oldRetryConfig = System.setProperty(SUN_RETRY_PROPERTY, "false"); } - @AfterClass - public static void resetSunRetry() throws Exception { + @AfterAll + static void resetSunRetry() throws Exception { if (oldRetryConfig == null) { System.clearProperty(SUN_RETRY_PROPERTY); } else { @@ -84,7 +80,7 @@ static String hostAndPort(URL url) { } @Test - public void loadBalancingDefaultPolicyRoundRobin() throws IOException, InterruptedException { + void loadBalancingDefaultPolicyRoundRobin() throws IOException, InterruptedException { server1.enqueue(new MockResponse().setBody("success!")); server2.enqueue(new MockResponse().setBody("success!")); @@ -101,14 +97,14 @@ public void loadBalancingDefaultPolicyRoundRobin() throws IOException, Interrupt api.post(); api.post(); - assertEquals(1, server1.getRequestCount()); - assertEquals(1, server2.getRequestCount()); + assertThat(server1.getRequestCount()).isEqualTo(1); + assertThat(server2.getRequestCount()).isEqualTo(1); // TODO: verify ribbon stats match // assertEquals(target.lb().getLoadBalancerStats().getSingleServerStat()) } @Test - public void ioExceptionRetry() throws IOException, InterruptedException { + void ioExceptionRetry() throws IOException, InterruptedException { server1.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_START)); server1.enqueue(new MockResponse().setBody("success!")); @@ -121,13 +117,13 @@ public void ioExceptionRetry() throws IOException, InterruptedException { api.post(); - assertEquals(2, server1.getRequestCount()); + assertThat(server1.getRequestCount()).isEqualTo(2); // TODO: verify ribbon stats match // assertEquals(target.lb().getLoadBalancerStats().getSingleServerStat()) } @Test - public void ioExceptionFailsAfterTooManyFailures() throws IOException, InterruptedException { + void ioExceptionFailsAfterTooManyFailures() throws IOException, InterruptedException { server1.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_START)); getConfigInstance().setProperty(serverListKey(), hostAndPort(server1.url("").url())); @@ -151,7 +147,7 @@ public void ioExceptionFailsAfterTooManyFailures() throws IOException, Interrupt } @Test - public void ribbonRetryConfigurationOnSameServer() throws IOException, InterruptedException { + void ribbonRetryConfigurationOnSameServer() throws IOException, InterruptedException { server1.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_START)); server1.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_START)); server2.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_START)); @@ -175,14 +171,14 @@ public void ribbonRetryConfigurationOnSameServer() throws IOException, Interrupt } catch (RetryableException ignored) { } - assertTrue(server1.getRequestCount() >= 2 || server2.getRequestCount() >= 2); + assertThat(server1.getRequestCount() >= 2 || server2.getRequestCount() >= 2).isTrue(); assertThat(server1.getRequestCount() + server2.getRequestCount()).isGreaterThanOrEqualTo(2); // TODO: verify ribbon stats match // assertEquals(target.lb().getLoadBalancerStats().getSingleServerStat()) } @Test - public void ribbonRetryConfigurationOnMultipleServers() throws IOException, InterruptedException { + void ribbonRetryConfigurationOnMultipleServers() throws IOException, InterruptedException { server1.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_START)); server1.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_START)); server2.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_START)); @@ -219,7 +215,7 @@ public void ribbonRetryConfigurationOnMultipleServers() throws IOException, Inte * contained invalid characters (ex. space). */ @Test - public void urlEncodeQueryStringParameters() throws IOException, InterruptedException { + void urlEncodeQueryStringParameters() throws IOException, InterruptedException { String queryStringValue = "some string with space"; /* values must be pct encoded, see RFC 6750 */ @@ -239,15 +235,15 @@ public void urlEncodeQueryStringParameters() throws IOException, InterruptedExce final String recordedRequestLine = server1.takeRequest().getRequestLine(); - assertEquals(recordedRequestLine, expectedRequestLine); + assertThat(expectedRequestLine).isEqualTo(recordedRequestLine); } @Test - public void testHTTPSViaRibbon() { + void hTTPSViaRibbon() { Client trustSSLSockets = new Client.Default(TrustingSSLSocketFactory.get(), null); - server1.useHttps(TrustingSSLSocketFactory.get("localhost"), false); + server1.useHttps(TrustingSSLSocketFactory.get("localhost")); server1.enqueue(new MockResponse().setBody("success!")); getConfigInstance().setProperty(serverListKey(), hostAndPort(server1.url("").url())); @@ -257,11 +253,11 @@ public void testHTTPSViaRibbon() { .client(RibbonClient.builder().delegate(trustSSLSockets).build()) .target(TestInterface.class, "https://" + client()); api.post(); - assertEquals(1, server1.getRequestCount()); + assertThat(server1.getRequestCount()).isEqualTo(1); } @Test - public void ioExceptionRetryWithBuilder() throws IOException, InterruptedException { + void ioExceptionRetryWithBuilder() throws IOException, InterruptedException { server1.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_START)); server1.enqueue(new MockResponse().setBody("success!")); @@ -274,13 +270,13 @@ public void ioExceptionRetryWithBuilder() throws IOException, InterruptedExcepti api.post(); - assertEquals(server1.getRequestCount(), 2); + assertThat(2).isEqualTo(server1.getRequestCount()); // TODO: verify ribbon stats match // assertEquals(target.lb().getLoadBalancerStats().getSingleServerStat()) } @Test - public void ribbonRetryOnStatusCodes() throws IOException, InterruptedException { + void ribbonRetryOnStatusCodes() throws IOException, InterruptedException { server1.enqueue(new MockResponse().setResponseCode(502)); server2.enqueue(new MockResponse().setResponseCode(503)); @@ -303,12 +299,12 @@ public void ribbonRetryOnStatusCodes() throws IOException, InterruptedException } catch (Exception ignored) { } - assertEquals(1, server1.getRequestCount()); - assertEquals(1, server2.getRequestCount()); + assertThat(server1.getRequestCount()).isEqualTo(1); + assertThat(server2.getRequestCount()).isEqualTo(1); } @Test - public void testFeignOptionsFollowRedirect() { + void feignOptionsFollowRedirect() { String expectedLocation = server2.url("").url().toString(); server1.enqueue( new MockResponse().setResponseCode(302).setHeader("Location", expectedLocation)); @@ -326,11 +322,11 @@ public void testFeignOptionsFollowRedirect() { try { Response response = api.get(); - assertEquals(302, response.status()); + assertThat(response.status()).isEqualTo(302); Collection location = response.headers().get("Location"); - assertNotNull(location); - assertFalse(location.isEmpty()); - assertEquals(expectedLocation, location.iterator().next()); + assertThat(location).isNotNull(); + assertThat(location).isNotEmpty(); + assertThat(location.iterator().next()).isEqualTo(expectedLocation); } catch (Exception ignored) { ignored.printStackTrace(); fail("Shouldn't throw "); @@ -338,7 +334,7 @@ public void testFeignOptionsFollowRedirect() { } @Test - public void testFeignOptionsNoFollowRedirect() { + void feignOptionsNoFollowRedirect() { // 302 will say go to server 2 server1.enqueue( new MockResponse() @@ -363,8 +359,8 @@ public void testFeignOptionsNoFollowRedirect() { try { Response response = api.get(); - assertEquals(200, response.status()); - assertEquals("Hello", response.body().toString()); + assertThat(response.status()).isEqualTo(200); + assertThat(response.body().toString()).isEqualTo("Hello"); } catch (Exception ignored) { ignored.printStackTrace(); fail("Shouldn't throw "); @@ -372,41 +368,43 @@ public void testFeignOptionsNoFollowRedirect() { } @Test - public void testFeignOptionsClientConfig() { + void feignOptionsClientConfig() { Request.Options options = new Request.Options(1111, TimeUnit.MILLISECONDS, 22222, TimeUnit.MILLISECONDS, true); IClientConfig config = new RibbonClient.FeignOptionsClientConfig(options); - assertThat( - config.get(CommonClientConfigKey.ConnectTimeout), equalTo(options.connectTimeoutMillis())); - assertThat(config.get(CommonClientConfigKey.ReadTimeout), equalTo(options.readTimeoutMillis())); - assertThat( - config.get(CommonClientConfigKey.FollowRedirects), equalTo(options.isFollowRedirects())); - assertEquals(3, config.getProperties().size()); + assertThat(config.get(CommonClientConfigKey.ConnectTimeout)) + .isEqualTo(options.connectTimeoutMillis()); + assertThat(config.get(CommonClientConfigKey.ReadTimeout)) + .isEqualTo(options.readTimeoutMillis()); + assertThat(config.get(CommonClientConfigKey.FollowRedirects)) + .isEqualTo(options.isFollowRedirects()); + assertThat(config.getProperties()).hasSize(3); } @Test - public void testCleanUrlWithMatchingHostAndPart() throws IOException { + void cleanUrlWithMatchingHostAndPart() throws IOException { URI uri = RibbonClient.cleanUrl("http://questions/questions/answer/123", "questions"); - assertEquals("http:///questions/answer/123", uri.toString()); + assertThat(uri.toString()).isEqualTo("http:///questions/answer/123"); } @Test - public void testCleanUrl() throws IOException { + void cleanUrl() throws IOException { URI uri = RibbonClient.cleanUrl("http://myservice/questions/answer/123", "myservice"); - assertEquals("http:///questions/answer/123", uri.toString()); + assertThat(uri.toString()).isEqualTo("http:///questions/answer/123"); } private String client() { - return testName.getMethodName(); + return testName; } private String serverListKey() { return client() + ".ribbon.listOfServers"; } - @After - public void clearServerList() { + @AfterEach + void clearServerList() throws IOException { getConfigInstance().clearProperty(serverListKey()); + server2.close(); } interface TestInterface { @@ -420,4 +418,12 @@ interface TestInterface { @RequestLine("GET /") Response get(); } + + @BeforeEach + void setup(TestInfo testInfo) { + Optional testMethod = testInfo.getTestMethod(); + if (testMethod.isPresent()) { + this.testName = testMethod.get().getName(); + } + } } diff --git a/sax/src/test/java/feign/sax/SAXDecoderTest.java b/sax/src/test/java/feign/sax/SAXDecoderTest.java index 6b940658d..1457396fa 100644 --- a/sax/src/test/java/feign/sax/SAXDecoderTest.java +++ b/sax/src/test/java/feign/sax/SAXDecoderTest.java @@ -15,7 +15,7 @@ import static feign.Util.UTF_8; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import feign.Request; import feign.Request.HttpMethod; @@ -26,13 +26,11 @@ import java.text.ParseException; import java.util.Collection; import java.util.Collections; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; import org.xml.sax.helpers.DefaultHandler; @SuppressWarnings("deprecation") -public class SAXDecoderTest { +class SAXDecoderTest { static String statusFailed = "" // @@ -48,7 +46,6 @@ public class SAXDecoderTest { + " \n" // + " \n" // + ""; - @Rule public final ExpectedException thrown = ExpectedException.none(); Decoder decoder = SAXDecoder.builder() // .registerContentHandler( @@ -63,17 +60,19 @@ public SAXDecoder.ContentHandlerWithResult create() { .build(); @Test - public void parsesConfiguredTypes() throws ParseException, IOException { - assertEquals(NetworkStatus.FAILED, decoder.decode(statusFailedResponse(), NetworkStatus.class)); - assertEquals("Failed", decoder.decode(statusFailedResponse(), String.class)); + void parsesConfiguredTypes() throws ParseException, IOException { + assertThat(decoder.decode(statusFailedResponse(), NetworkStatus.class)) + .isEqualTo(NetworkStatus.FAILED); + assertThat(decoder.decode(statusFailedResponse(), String.class)).isEqualTo("Failed"); } @Test - public void niceErrorOnUnconfiguredType() throws ParseException, IOException { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("type int not in configured handlers"); + void niceErrorOnUnconfiguredType() throws ParseException, IOException { + Throwable exception = + assertThrows( + IllegalStateException.class, () -> decoder.decode(statusFailedResponse(), int.class)); - decoder.decode(statusFailedResponse(), int.class); + assertThat(exception.getMessage()).contains("type int not in configured handlers"); } private Response statusFailedResponse() { @@ -87,7 +86,7 @@ private Response statusFailedResponse() { } @Test - public void nullBodyDecodesToEmpty() throws Exception { + void nullBodyDecodesToEmpty() throws Exception { Response response = Response.builder() .status(204) @@ -101,7 +100,7 @@ public void nullBodyDecodesToEmpty() throws Exception { /** Enabled via {@link feign.Feign.Builder#dismiss404()} */ @Test - public void notFoundDecodesToEmpty() throws Exception { + void notFoundDecodesToEmpty() throws Exception { Response response = Response.builder() .status(404) diff --git a/slf4j/src/test/java/feign/slf4j/Slf4jLoggerTest.java b/slf4j/src/test/java/feign/slf4j/Slf4jLoggerTest.java index e0a5e9d1f..100865600 100644 --- a/slf4j/src/test/java/feign/slf4j/Slf4jLoggerTest.java +++ b/slf4j/src/test/java/feign/slf4j/Slf4jLoggerTest.java @@ -22,8 +22,7 @@ import feign.Util; import java.util.Collection; import java.util.Collections; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; import org.slf4j.simple.RecordingSimpleLogger; @@ -45,11 +44,11 @@ public class Slf4jLoggerTest { .headers(Collections.>emptyMap()) .body(new byte[0]) .build(); - @Rule public final RecordingSimpleLogger slf4j = new RecordingSimpleLogger(); + public final RecordingSimpleLogger slf4j = new RecordingSimpleLogger(); private Slf4jLogger logger; @Test - public void useFeignLoggerByDefault() throws Exception { + void useFeignLoggerByDefault() throws Exception { slf4j.logLevel("debug"); slf4j.expectMessages( "DEBUG feign.Logger - [someMethod] This is my message" + System.lineSeparator()); @@ -59,7 +58,7 @@ public void useFeignLoggerByDefault() throws Exception { } @Test - public void useLoggerByNameIfRequested() throws Exception { + void useLoggerByNameIfRequested() throws Exception { slf4j.logLevel("debug"); slf4j.expectMessages( "DEBUG named.logger - [someMethod] This is my message" + System.lineSeparator()); @@ -69,7 +68,7 @@ public void useLoggerByNameIfRequested() throws Exception { } @Test - public void useLoggerByClassIfRequested() throws Exception { + void useLoggerByClassIfRequested() throws Exception { slf4j.logLevel("debug"); slf4j.expectMessages( "DEBUG feign.Feign - [someMethod] This is my message" + System.lineSeparator()); @@ -79,7 +78,7 @@ public void useLoggerByClassIfRequested() throws Exception { } @Test - public void useSpecifiedLoggerIfRequested() throws Exception { + void useSpecifiedLoggerIfRequested() throws Exception { slf4j.logLevel("debug"); slf4j.expectMessages( "DEBUG specified.logger - [someMethod] This is my message" + System.lineSeparator()); @@ -89,7 +88,7 @@ public void useSpecifiedLoggerIfRequested() throws Exception { } @Test - public void logOnlyIfDebugEnabled() throws Exception { + void logOnlyIfDebugEnabled() throws Exception { slf4j.logLevel("info"); logger = new Slf4jLogger(); @@ -99,7 +98,7 @@ public void logOnlyIfDebugEnabled() throws Exception { } @Test - public void logRequestsAndResponses() throws Exception { + void logRequestsAndResponses() throws Exception { slf4j.logLevel("debug"); slf4j.expectMessages( "DEBUG feign.Logger - [someMethod] A message with 2 formatting tokens." diff --git a/slf4j/src/test/java/org/slf4j/simple/RecordingSimpleLogger.java b/slf4j/src/test/java/org/slf4j/simple/RecordingSimpleLogger.java index 4c9cce3f6..759234802 100644 --- a/slf4j/src/test/java/org/slf4j/simple/RecordingSimpleLogger.java +++ b/slf4j/src/test/java/org/slf4j/simple/RecordingSimpleLogger.java @@ -13,22 +13,16 @@ */ package org.slf4j.simple; -import static org.junit.Assert.assertEquals; import static org.slf4j.simple.SimpleLogger.DEFAULT_LOG_LEVEL_KEY; import static org.slf4j.simple.SimpleLogger.SHOW_THREAD_NAME_KEY; -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; -import org.junit.rules.TestRule; -import org.junit.runner.Description; -import org.junit.runners.model.Statement; import org.slf4j.LoggerFactory; /** * A testing utility to allow control over {@link org.slf4j.impl.SimpleLogger}. In some cases, * reflection is used to bypass access restrictions. */ -public final class RecordingSimpleLogger implements TestRule { +public final class RecordingSimpleLogger { private String expectedMessages = ""; @@ -49,21 +43,21 @@ public RecordingSimpleLogger expectMessages(String expectedMessages) { } /** Steals the output of stderr as that's where the log events go. */ - @Override - public Statement apply(final Statement base, Description description) { - return new Statement() { - @Override - public void evaluate() throws Throwable { - ByteArrayOutputStream buff = new ByteArrayOutputStream(); - PrintStream stderr = System.err; - try { - System.setErr(new PrintStream(buff)); - base.evaluate(); - assertEquals(expectedMessages, buff.toString()); - } finally { - System.setErr(stderr); - } - } - }; - } + // @Override + // public Statement apply(final Statement base, Description description) { + // return new Statement() { + // @Override + // public void evaluate() throws Throwable { + // ByteArrayOutputStream buff = new ByteArrayOutputStream(); + // PrintStream stderr = System.err; + // try { + // System.setErr(new PrintStream(buff)); + // base.evaluate(); + // assertThat(buff.toString()).isEqualTo(expectedMessages); + // } finally { + // System.setErr(stderr); + // } + // } + // }; + // } } diff --git a/soap-jakarta/src/test/java/feign/soap/SOAPCodecTest.java b/soap-jakarta/src/test/java/feign/soap/SOAPCodecTest.java index 8aa8cb0d1..ec3b6e5fe 100644 --- a/soap-jakarta/src/test/java/feign/soap/SOAPCodecTest.java +++ b/soap-jakarta/src/test/java/feign/soap/SOAPCodecTest.java @@ -15,7 +15,8 @@ import static feign.Util.UTF_8; import static feign.assertj.FeignAssertions.assertThat; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; import feign.Request; import feign.Request.HttpMethod; @@ -24,7 +25,11 @@ import feign.Util; import feign.codec.Encoder; import feign.jaxb.JAXBContextFactory; -import jakarta.xml.bind.annotation.*; +import jakarta.xml.bind.annotation.XmlAccessType; +import jakarta.xml.bind.annotation.XmlAccessorType; +import jakarta.xml.bind.annotation.XmlElement; +import jakarta.xml.bind.annotation.XmlRootElement; +import jakarta.xml.bind.annotation.XmlValue; import jakarta.xml.soap.SOAPElement; import jakarta.xml.soap.SOAPException; import jakarta.xml.soap.SOAPFactory; @@ -33,17 +38,13 @@ import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.Map; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; @SuppressWarnings("deprecation") -public class SOAPCodecTest { - - @Rule public final ExpectedException thrown = ExpectedException.none(); +class SOAPCodecTest { @Test - public void encodesSoap() { + void encodesSoap() { Encoder encoder = new SOAPEncoder.Builder() .withJAXBContextFactory(new JAXBContextFactory.Builder().build()) @@ -70,10 +71,7 @@ public void encodesSoap() { } @Test - public void doesntEncodeParameterizedTypes() throws Exception { - thrown.expect(UnsupportedOperationException.class); - thrown.expectMessage( - "SOAP only supports encoding raw types. Found java.util.Map"); + void doesntEncodeParameterizedTypes() throws Exception { class ParameterizedHolder { @@ -83,12 +81,19 @@ class ParameterizedHolder { Type parameterized = ParameterizedHolder.class.getDeclaredField("field").getGenericType(); RequestTemplate template = new RequestTemplate(); - new SOAPEncoder(new JAXBContextFactory.Builder().build()) - .encode(Collections.emptyMap(), parameterized, template); + Throwable exception = + assertThrows( + UnsupportedOperationException.class, + () -> + new SOAPEncoder(new JAXBContextFactory.Builder().build()) + .encode(Collections.emptyMap(), parameterized, template)); + assertThat(exception.getMessage()) + .contains( + "SOAP only supports encoding raw types. Found java.util.Map"); } @Test - public void encodesSoapWithCustomJAXBMarshallerEncoding() { + void encodesSoapWithCustomJAXBMarshallerEncoding() { JAXBContextFactory jaxbContextFactory = new JAXBContextFactory.Builder().withMarshallerJAXBEncoding("UTF-16").build(); @@ -121,7 +126,7 @@ public void encodesSoapWithCustomJAXBMarshallerEncoding() { } @Test - public void encodesSoapWithCustomJAXBSchemaLocation() { + void encodesSoapWithCustomJAXBSchemaLocation() { JAXBContextFactory jaxbContextFactory = new JAXBContextFactory.Builder() .withMarshallerSchemaLocation("http://apihost http://apihost/schema.xsd") @@ -146,7 +151,7 @@ public void encodesSoapWithCustomJAXBSchemaLocation() { } @Test - public void encodesSoapWithCustomJAXBNoSchemaLocation() { + void encodesSoapWithCustomJAXBNoSchemaLocation() { JAXBContextFactory jaxbContextFactory = new JAXBContextFactory.Builder() .withMarshallerNoNamespaceSchemaLocation("http://apihost/schema.xsd") @@ -171,7 +176,7 @@ public void encodesSoapWithCustomJAXBNoSchemaLocation() { } @Test - public void encodesSoapWithCustomJAXBFormattedOuput() { + void encodesSoapWithCustomJAXBFormattedOuput() { Encoder encoder = new SOAPEncoder.Builder() .withFormattedOutput(true) @@ -209,7 +214,7 @@ public void encodesSoapWithCustomJAXBFormattedOuput() { } @Test - public void decodesSoap() throws Exception { + void decodesSoap() throws Exception { GetPrice mock = new GetPrice(); mock.item = new Item(); mock.item.value = "Apples"; @@ -233,11 +238,11 @@ public void decodesSoap() throws Exception { SOAPDecoder decoder = new SOAPDecoder(new JAXBContextFactory.Builder().build()); - assertEquals(mock, decoder.decode(response, GetPrice.class)); + assertThat(decoder.decode(response, GetPrice.class)).isEqualTo(mock); } @Test - public void decodesSoapWithSchemaOnEnvelope() throws Exception { + void decodesSoapWithSchemaOnEnvelope() throws Exception { GetPrice mock = new GetPrice(); mock.item = new Item(); mock.item.value = "Apples"; @@ -267,11 +272,11 @@ public void decodesSoapWithSchemaOnEnvelope() throws Exception { .useFirstChild() .build(); - assertEquals(mock, decoder.decode(response, GetPrice.class)); + assertThat(decoder.decode(response, GetPrice.class)).isEqualTo(mock); } @Test - public void decodesSoap1_2Protocol() throws Exception { + void decodesSoap1_2Protocol() throws Exception { GetPrice mock = new GetPrice(); mock.item = new Item(); mock.item.value = "Apples"; @@ -295,16 +300,11 @@ public void decodesSoap1_2Protocol() throws Exception { SOAPDecoder decoder = new SOAPDecoder(new JAXBContextFactory.Builder().build()); - assertEquals(mock, decoder.decode(response, GetPrice.class)); + assertThat(decoder.decode(response, GetPrice.class)).isEqualTo(mock); } @Test - public void doesntDecodeParameterizedTypes() throws Exception { - thrown.expect(feign.codec.DecodeException.class); - thrown.expectMessage( - "java.util.Map is an interface, and JAXB can't handle interfaces.\n" - + "\tthis problem is related to the following location:\n" - + "\t\tat java.util.Map"); + void doesntDecodeParameterizedTypes() throws Exception { class ParameterizedHolder { @@ -333,11 +333,21 @@ class ParameterizedHolder { UTF_8) .build(); - new SOAPDecoder(new JAXBContextFactory.Builder().build()).decode(response, parameterized); + Throwable exception = + assertThrows( + feign.codec.DecodeException.class, + () -> + new SOAPDecoder(new JAXBContextFactory.Builder().build()) + .decode(response, parameterized)); + assertThat(exception.getMessage()) + .contains( + "java.util.Map is an interface, and JAXB can't handle interfaces.\n" + + "\tthis problem is related to the following location:\n" + + "\t\tat java.util.Map"); } @Test - public void decodeAnnotatedParameterizedTypes() throws Exception { + void decodeAnnotatedParameterizedTypes() throws Exception { JAXBContextFactory jaxbContextFactory = new JAXBContextFactory.Builder().withMarshallerFormattedOutput(true).build(); @@ -365,7 +375,7 @@ public void decodeAnnotatedParameterizedTypes() throws Exception { /** Enabled via {@link feign.Feign.Builder#dismiss404()} */ @Test - public void notFoundDecodesToNull() throws Exception { + void notFoundDecodesToNull() throws Exception { Response response = Response.builder() .status(404) @@ -382,7 +392,7 @@ public void notFoundDecodesToNull() throws Exception { } @Test - public void changeSoapProtocolAndSetHeader() { + void changeSoapProtocolAndSetHeader() { Encoder encoder = new ChangedProtocolAndHeaderSOAPEncoder(new JAXBContextFactory.Builder().build()); diff --git a/soap-jakarta/src/test/java/feign/soap/SOAPFaultDecoderTest.java b/soap-jakarta/src/test/java/feign/soap/SOAPFaultDecoderTest.java index 38a88725a..62d7c3b81 100644 --- a/soap-jakarta/src/test/java/feign/soap/SOAPFaultDecoderTest.java +++ b/soap-jakarta/src/test/java/feign/soap/SOAPFaultDecoderTest.java @@ -14,6 +14,8 @@ package feign.soap; import static feign.Util.UTF_8; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; import feign.FeignException; import feign.Request; @@ -27,15 +29,10 @@ import java.io.IOException; import java.io.InputStream; import java.util.Collections; -import org.assertj.core.api.Assertions; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; @SuppressWarnings("deprecation") -public class SOAPFaultDecoderTest { - - @Rule public final ExpectedException thrown = ExpectedException.none(); +class SOAPFaultDecoderTest { private static byte[] getResourceBytes(String resourcePath) throws IOException { InputStream resourceAsStream = SOAPFaultDecoderTest.class.getResourceAsStream(resourcePath); @@ -45,10 +42,7 @@ private static byte[] getResourceBytes(String resourcePath) throws IOException { } @Test - public void soapDecoderThrowsSOAPFaultException() throws IOException { - - thrown.expect(SOAPFaultException.class); - thrown.expectMessage("Processing error"); + void soapDecoderThrowsSOAPFaultException() throws IOException { Response response = Response.builder() @@ -60,15 +54,19 @@ public void soapDecoderThrowsSOAPFaultException() throws IOException { .body(getResourceBytes("/samples/SOAP_1_2_FAULT.xml")) .build(); - new SOAPDecoder.Builder() - .withSOAPProtocol(SOAPConstants.SOAP_1_2_PROTOCOL) - .withJAXBContextFactory(new JAXBContextFactory.Builder().build()) - .build() - .decode(response, Object.class); + SOAPDecoder decoder = + new SOAPDecoder.Builder() + .withSOAPProtocol(SOAPConstants.SOAP_1_2_PROTOCOL) + .withJAXBContextFactory(new JAXBContextFactory.Builder().build()) + .build(); + + Throwable exception = + assertThrows(SOAPFaultException.class, () -> decoder.decode(response, Object.class)); + assertThat(exception.getMessage()).contains("Processing error"); } @Test - public void errorDecoderReturnsSOAPFaultException() throws IOException { + void errorDecoderReturnsSOAPFaultException() throws IOException { Response response = Response.builder() .status(400) @@ -80,13 +78,13 @@ public void errorDecoderReturnsSOAPFaultException() throws IOException { .build(); Exception error = new SOAPErrorDecoder().decode("Service#foo()", response); - Assertions.assertThat(error) + assertThat(error) .isInstanceOf(SOAPFaultException.class) .hasMessage("Message was not SOAP 1.1 compliant"); } @Test - public void errorDecoderReturnsFeignExceptionOn503Status() throws IOException { + void errorDecoderReturnsFeignExceptionOn503Status() throws IOException { Response response = Response.builder() .status(503) @@ -99,7 +97,7 @@ public void errorDecoderReturnsFeignExceptionOn503Status() throws IOException { Exception error = new SOAPErrorDecoder().decode("Service#foo()", response); - Assertions.assertThat(error) + assertThat(error) .isInstanceOf(FeignException.class) .hasMessage( "[503 Service Unavailable] during [GET] to [/api] [Service#foo()]: [Service" @@ -107,7 +105,7 @@ public void errorDecoderReturnsFeignExceptionOn503Status() throws IOException { } @Test - public void errorDecoderReturnsFeignExceptionOnEmptyFault() throws IOException { + void errorDecoderReturnsFeignExceptionOnEmptyFault() throws IOException { String responseBody = "\n" + ""); + void doesntEncodeParameterizedTypes() throws Exception { class ParameterizedHolder { @@ -87,12 +81,19 @@ class ParameterizedHolder { Type parameterized = ParameterizedHolder.class.getDeclaredField("field").getGenericType(); RequestTemplate template = new RequestTemplate(); - new SOAPEncoder(new JAXBContextFactory.Builder().build()) - .encode(Collections.emptyMap(), parameterized, template); + Throwable exception = + assertThrows( + UnsupportedOperationException.class, + () -> + new SOAPEncoder(new JAXBContextFactory.Builder().build()) + .encode(Collections.emptyMap(), parameterized, template)); + assertThat(exception.getMessage()) + .contains( + "SOAP only supports encoding raw types. Found java.util.Map"); } @Test - public void encodesSoapWithCustomJAXBMarshallerEncoding() { + void encodesSoapWithCustomJAXBMarshallerEncoding() { JAXBContextFactory jaxbContextFactory = new JAXBContextFactory.Builder().withMarshallerJAXBEncoding("UTF-16").build(); @@ -125,7 +126,7 @@ public void encodesSoapWithCustomJAXBMarshallerEncoding() { } @Test - public void encodesSoapWithCustomJAXBSchemaLocation() { + void encodesSoapWithCustomJAXBSchemaLocation() { JAXBContextFactory jaxbContextFactory = new JAXBContextFactory.Builder() .withMarshallerSchemaLocation("http://apihost http://apihost/schema.xsd") @@ -150,7 +151,7 @@ public void encodesSoapWithCustomJAXBSchemaLocation() { } @Test - public void encodesSoapWithCustomJAXBNoSchemaLocation() { + void encodesSoapWithCustomJAXBNoSchemaLocation() { JAXBContextFactory jaxbContextFactory = new JAXBContextFactory.Builder() .withMarshallerNoNamespaceSchemaLocation("http://apihost/schema.xsd") @@ -175,7 +176,7 @@ public void encodesSoapWithCustomJAXBNoSchemaLocation() { } @Test - public void encodesSoapWithCustomJAXBFormattedOuput() { + void encodesSoapWithCustomJAXBFormattedOuput() { Encoder encoder = new SOAPEncoder.Builder() .withFormattedOutput(true) @@ -213,7 +214,7 @@ public void encodesSoapWithCustomJAXBFormattedOuput() { } @Test - public void decodesSoap() throws Exception { + void decodesSoap() throws Exception { GetPrice mock = new GetPrice(); mock.item = new Item(); mock.item.value = "Apples"; @@ -237,11 +238,11 @@ public void decodesSoap() throws Exception { SOAPDecoder decoder = new SOAPDecoder(new JAXBContextFactory.Builder().build()); - assertEquals(mock, decoder.decode(response, GetPrice.class)); + assertThat(decoder.decode(response, GetPrice.class)).isEqualTo(mock); } @Test - public void decodesSoapWithSchemaOnEnvelope() throws Exception { + void decodesSoapWithSchemaOnEnvelope() throws Exception { GetPrice mock = new GetPrice(); mock.item = new Item(); mock.item.value = "Apples"; @@ -271,11 +272,11 @@ public void decodesSoapWithSchemaOnEnvelope() throws Exception { .useFirstChild() .build(); - assertEquals(mock, decoder.decode(response, GetPrice.class)); + assertThat(decoder.decode(response, GetPrice.class)).isEqualTo(mock); } @Test - public void decodesSoap1_2Protocol() throws Exception { + void decodesSoap1_2Protocol() throws Exception { GetPrice mock = new GetPrice(); mock.item = new Item(); mock.item.value = "Apples"; @@ -299,16 +300,11 @@ public void decodesSoap1_2Protocol() throws Exception { SOAPDecoder decoder = new SOAPDecoder(new JAXBContextFactory.Builder().build()); - assertEquals(mock, decoder.decode(response, GetPrice.class)); + assertThat(decoder.decode(response, GetPrice.class)).isEqualTo(mock); } @Test - public void doesntDecodeParameterizedTypes() throws Exception { - thrown.expect(feign.codec.DecodeException.class); - thrown.expectMessage( - "java.util.Map is an interface, and JAXB can't handle interfaces.\n" - + "\tthis problem is related to the following location:\n" - + "\t\tat java.util.Map"); + void doesntDecodeParameterizedTypes() throws Exception { class ParameterizedHolder { @@ -337,7 +333,17 @@ class ParameterizedHolder { UTF_8) .build(); - new SOAPDecoder(new JAXBContextFactory.Builder().build()).decode(response, parameterized); + Throwable exception = + assertThrows( + feign.codec.DecodeException.class, + () -> + new SOAPDecoder(new JAXBContextFactory.Builder().build()) + .decode(response, parameterized)); + assertThat(exception.getMessage()) + .contains( + "java.util.Map is an interface, and JAXB can't handle interfaces.\n" + + "\tthis problem is related to the following location:\n" + + "\t\tat java.util.Map"); } @XmlRootElement @@ -351,7 +357,7 @@ public void set(T t) { } @Test - public void decodeAnnotatedParameterizedTypes() throws Exception { + void decodeAnnotatedParameterizedTypes() throws Exception { JAXBContextFactory jaxbContextFactory = new JAXBContextFactory.Builder().withMarshallerFormattedOutput(true).build(); @@ -379,7 +385,7 @@ public void decodeAnnotatedParameterizedTypes() throws Exception { /** Enabled via {@link feign.Feign.Builder#dismiss404()} */ @Test - public void notFoundDecodesToNull() throws Exception { + void notFoundDecodesToNull() throws Exception { Response response = Response.builder() .status(404) @@ -396,7 +402,7 @@ public void notFoundDecodesToNull() throws Exception { } @Test - public void changeSoapProtocolAndSetHeader() { + void changeSoapProtocolAndSetHeader() { Encoder encoder = new ChangedProtocolAndHeaderSOAPEncoder(new JAXBContextFactory.Builder().build()); diff --git a/soap/src/test/java/feign/soap/SOAPFaultDecoderTest.java b/soap/src/test/java/feign/soap/SOAPFaultDecoderTest.java index d4b57b547..501b696ba 100644 --- a/soap/src/test/java/feign/soap/SOAPFaultDecoderTest.java +++ b/soap/src/test/java/feign/soap/SOAPFaultDecoderTest.java @@ -14,6 +14,8 @@ package feign.soap; import static feign.Util.UTF_8; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; import feign.FeignException; import feign.Request; @@ -27,21 +29,13 @@ import java.util.Collections; import javax.xml.soap.SOAPConstants; import javax.xml.ws.soap.SOAPFaultException; -import org.assertj.core.api.Assertions; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; @SuppressWarnings("deprecation") -public class SOAPFaultDecoderTest { - - @Rule public final ExpectedException thrown = ExpectedException.none(); +class SOAPFaultDecoderTest { @Test - public void soapDecoderThrowsSOAPFaultException() throws IOException { - - thrown.expect(SOAPFaultException.class); - thrown.expectMessage("Processing error"); + void soapDecoderThrowsSOAPFaultException() throws IOException { Response response = Response.builder() @@ -53,15 +47,18 @@ public void soapDecoderThrowsSOAPFaultException() throws IOException { .body(getResourceBytes("/samples/SOAP_1_2_FAULT.xml")) .build(); - new SOAPDecoder.Builder() - .withSOAPProtocol(SOAPConstants.SOAP_1_2_PROTOCOL) - .withJAXBContextFactory(new JAXBContextFactory.Builder().build()) - .build() - .decode(response, Object.class); + SOAPDecoder decoder = + new SOAPDecoder.Builder() + .withSOAPProtocol(SOAPConstants.SOAP_1_2_PROTOCOL) + .withJAXBContextFactory(new JAXBContextFactory.Builder().build()) + .build(); + Throwable exception = + assertThrows(SOAPFaultException.class, () -> decoder.decode(response, Object.class)); + assertThat(exception.getMessage()).contains("Processing error"); } @Test - public void errorDecoderReturnsSOAPFaultException() throws IOException { + void errorDecoderReturnsSOAPFaultException() throws IOException { Response response = Response.builder() .status(400) @@ -73,13 +70,13 @@ public void errorDecoderReturnsSOAPFaultException() throws IOException { .build(); Exception error = new SOAPErrorDecoder().decode("Service#foo()", response); - Assertions.assertThat(error) + assertThat(error) .isInstanceOf(SOAPFaultException.class) .hasMessage("Message was not SOAP 1.1 compliant"); } @Test - public void errorDecoderReturnsFeignExceptionOn503Status() throws IOException { + void errorDecoderReturnsFeignExceptionOn503Status() throws IOException { Response response = Response.builder() .status(503) @@ -92,7 +89,7 @@ public void errorDecoderReturnsFeignExceptionOn503Status() throws IOException { Exception error = new SOAPErrorDecoder().decode("Service#foo()", response); - Assertions.assertThat(error) + assertThat(error) .isInstanceOf(FeignException.class) .hasMessage( "[503 Service Unavailable] during [GET] to [/api] [Service#foo()]: [Service" @@ -100,7 +97,7 @@ public void errorDecoderReturnsFeignExceptionOn503Status() throws IOException { } @Test - public void errorDecoderReturnsFeignExceptionOnEmptyFault() throws IOException { + void errorDecoderReturnsFeignExceptionOnEmptyFault() throws IOException { String responseBody = "\n" + "feign-jackson test - - org.hamcrest - hamcrest - test - diff --git a/spring4/src/test/java/feign/spring/SpringContractTest.java b/spring4/src/test/java/feign/spring/SpringContractTest.java index e265a32bb..cd99144d0 100755 --- a/spring4/src/test/java/feign/spring/SpringContractTest.java +++ b/spring4/src/test/java/feign/spring/SpringContractTest.java @@ -13,11 +13,14 @@ */ package feign.spring; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; - -import feign.*; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import feign.Feign; +import feign.Param; +import feign.Request; +import feign.Response; +import feign.ResponseMapper; import feign.jackson.JacksonDecoder; import feign.jackson.JacksonEncoder; import feign.mock.HttpMethod; @@ -27,24 +30,37 @@ import java.io.Reader; import java.lang.reflect.Type; import java.nio.charset.StandardCharsets; -import java.util.*; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.MissingResourceException; +import java.util.Optional; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.web.bind.annotation.*; - -public class SpringContractTest { - - @Rule public ExpectedException thrown = ExpectedException.none(); +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; + +class SpringContractTest { private MockClient mockClient; private HealthResource resource; - @Before - public void setup() throws IOException { + @BeforeEach + void setup() throws IOException { Response.Builder response = Response.builder() .status(200) @@ -107,132 +123,132 @@ public Response map(Response response, Type type) { } @Test - public void noPath() { + void noPath() { resource.getStatus(); mockClient.verifyOne(HttpMethod.GET, "/health"); } @Test - public void testWithName() { + void withName() { resource.checkWithName("name", true, true); mockClient.verifyOne(HttpMethod.GET, "/health/name?deep=true&dryRun=true"); } @Test - public void testOptionalPresent() { + void optionalPresent() { resource.checkWithOptional(Optional.of("value")); mockClient.verifyOne(HttpMethod.GET, "/health/optional?param=value"); } @Test - public void testOptionalNotPresent() { + void optionalNotPresent() { resource.checkWithOptional(Optional.empty()); mockClient.verifyOne(HttpMethod.GET, "/health/optional"); } @Test - public void testOptionalEmptyValue() { + void optionalEmptyValue() { resource.checkWithOptional(Optional.of("")); mockClient.verifyOne(HttpMethod.GET, "/health/optional?param"); } @Test - public void testOptionalNullable() { + void optionalNullable() { resource.checkWithOptional(Optional.ofNullable(null)); mockClient.verifyOne(HttpMethod.GET, "/health/optional"); } @Test - public void testRequestPart() { + void requestPart() { resource.checkRequestPart("1", "hello", "6"); final Request request = mockClient.verifyOne(HttpMethod.POST, "/health/part/1"); - assertThat( - request.requestTemplate().methodMetadata().formParams(), contains("name1", "grade1")); + assertThat(request.requestTemplate().methodMetadata().formParams()) + .containsExactly("name1", "grade1"); } @Test - public void testRequestHeader() { + void requestHeader() { resource.checkRequestHeader("hello", "6"); final Request request = mockClient.verifyOne(HttpMethod.GET, "/health/header"); - assertThat(request.headers(), hasEntry("name1", Arrays.asList("hello"))); - assertThat(request.headers(), hasEntry("grade1", Arrays.asList("6"))); + assertThat(request.headers()).containsEntry("name1", Arrays.asList("hello")); + assertThat(request.headers()).containsEntry("grade1", Arrays.asList("6")); } @Test - public void testRequestHeaderMap() { + void requestHeaderMap() { Map map = new HashMap<>(); map.put("name1", "hello"); map.put("grade1", "6"); resource.checkRequestHeaderMap(map); final Request request = mockClient.verifyOne(HttpMethod.GET, "/health/header/map"); - assertThat(request.headers(), hasEntry("name1", Arrays.asList("hello"))); - assertThat(request.headers(), hasEntry("grade1", Arrays.asList("6"))); + assertThat(request.headers()).containsEntry("name1", Arrays.asList("hello")); + assertThat(request.headers()).containsEntry("grade1", Arrays.asList("6")); } @Test - public void testRequestHeaderPojo() { + void requestHeaderPojo() { HeaderMapUserObject object = new HeaderMapUserObject(); object.setName("hello"); object.setGrade("6"); resource.checkRequestHeaderPojo(object); final Request request = mockClient.verifyOne(HttpMethod.GET, "/health/header/pojo"); - assertThat(request.headers(), hasEntry("name1", Arrays.asList("hello"))); - assertThat(request.headers(), hasEntry("grade1", Arrays.asList("6"))); + assertThat(request.headers()).containsEntry("name1", Arrays.asList("hello")); + assertThat(request.headers()).containsEntry("grade1", Arrays.asList("6")); } @Test - public void requestParam() { + void requestParam() { resource.check("1", true); mockClient.verifyOne(HttpMethod.GET, "/health/1?deep=true"); } @Test - public void requestTwoParams() { + void requestTwoParams() { resource.check("1", true, true); mockClient.verifyOne(HttpMethod.GET, "/health/1?deep=true&dryRun=true"); } @Test - public void inheritance() { + void inheritance() { final Data data = resource.getData(new Data()); - assertThat(data, notNullValue()); + assertThat(data).isNotNull(); final Request request = mockClient.verifyOne(HttpMethod.GET, "/health/generic"); - assertThat(request.headers(), hasEntry("Content-Type", Arrays.asList("application/json"))); + assertThat(request.headers()).containsEntry("Content-Type", Arrays.asList("application/json")); } @Test - public void composedAnnotation() { + void composedAnnotation() { resource.check("1"); mockClient.verifyOne(HttpMethod.GET, "/health/1"); } @Test - public void notAHttpMethod() { - thrown.expectMessage("is not a method handled by feign"); - - resource.missingResourceExceptionHandler(); + void notAHttpMethod() { + Throwable exception = + assertThrows(Exception.class, () -> resource.missingResourceExceptionHandler()); + assertThat(exception.getMessage()).contains("is not a method handled by feign"); } @Test - public void testConsumeAndProduce() { + void consumeAndProduce() { resource.produceText(new HashMap<>()); Request request = mockClient.verifyOne(HttpMethod.POST, "/health/text"); - assertThat(request.headers(), hasEntry("Content-Type", Arrays.asList("application/json"))); - assertThat(request.headers(), hasEntry("Accept", Arrays.asList("text/plain"))); + assertThat(request.headers()).containsEntry("Content-Type", Arrays.asList("application/json")); + assertThat(request.headers()).containsEntry("Accept", Arrays.asList("text/plain")); } interface GenericResource {