简体   繁体   中英

RestAssured cannot connect (Unit Test - Jersey REST API with Spring boot)

I am developping a REST-API with Jersey, I use Spring to run the server. I am currently trying to write some unit test for it, I choose RestAssured (had problems with the Jersey Test Framework).

For now I am simply trying to test a dummy resource but it does not work. It seems that it cannot connect (to the server I guess). Here is my test :

@SpringBootTest
public class NotificationTest {


    @Test
    public void test_dummy() throws IOException, InterruptedException {

        String username = "joeBiden@mail.com";
        String pwd = "joe485";
        
        RestAssured.port = 8443;
        RestAssured.baseURI = "https://localhost";
        RestAssured.basePath = "/api";
        RestAssured.authentication = basic(username, pwd);
        RestAssured.useRelaxedHTTPSValidation();
        
        given().auth().preemptive().basic(username, pwd).when().get("/login").then().statusCode(200);
        
        RestAssured.when().get(URI.create("/api/dummy/1"))
            .then().statusCode(200)
            .assertThat().body("id", equalTo(1));
    }
}

You can see that I have set the port, baseURI and basePath (I am testing a secured API, we use https). I have tried to find ways to mock the Spring server without success. Here is the output :

    23:42:08.339 [Test worker] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]
23:42:08.355 [Test worker] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating BootstrapContext using constructor [public org.springframework.test.context.support.DefaultBootstrapContext(java.lang.Class,org.springframework.test.context.CacheAwareContextLoaderDelegate)]
23:42:08.416 [Test worker] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [be.ac.umons.g04.api.core.resources.NotificationTest] from class [org.springframework.boot.test.context.SpringBootTestContextBootstrapper]
23:42:08.433 [Test worker] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Neither @ContextConfiguration nor @ContextHierarchy found for test class [be.ac.umons.g04.api.core.resources.NotificationTest], using SpringBootContextLoader
23:42:08.441 [Test worker] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [be.ac.umons.g04.api.core.resources.NotificationTest]: class path resource [be/ac/umons/g04/api/core/resources/NotificationTest-context.xml] does not exist
23:42:08.444 [Test worker] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [be.ac.umons.g04.api.core.resources.NotificationTest]: class path resource [be/ac/umons/g04/api/core/resources/NotificationTestContext.groovy] does not exist
23:42:08.445 [Test worker] INFO org.springframework.test.context.support.AbstractContextLoader - Could not detect default resource locations for test class [be.ac.umons.g04.api.core.resources.NotificationTest]: no resource found for suffixes {-context.xml, Context.groovy}.
23:42:08.446 [Test worker] INFO org.springframework.test.context.support.AnnotationConfigContextLoaderUtils - Could not detect default configuration classes for test class [be.ac.umons.g04.api.core.resources.NotificationTest]: NotificationTest does not declare any static, non-private, non-final, nested classes annotated with @Configuration.
23:42:08.492 [Test worker] DEBUG org.springframework.test.context.support.ActiveProfilesUtils - Could not find an 'annotation declaring class' for annotation type [org.springframework.test.context.ActiveProfiles] and class [be.ac.umons.g04.api.core.resources.NotificationTest]
23:42:08.601 [Test worker] DEBUG org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider - Identified candidate component class: file [E:\UNIF\BAC2\Projet-de-Genie-Logiciel\PGL-Aout\PGL04\api\build\classes\java\main\be\ac\umons\g04\api\core\Launcher.class]
23:42:08.607 [Test worker] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Found @SpringBootConfiguration be.ac.umons.g04.api.core.Launcher for test class be.ac.umons.g04.api.core.resources.NotificationTest
23:42:08.747 [Test worker] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - @TestExecutionListeners is not present for class [be.ac.umons.g04.api.core.resources.NotificationTest]: using defaults.
23:42:08.748 [Test worker] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener, org.springframework.boot.test.autoconfigure.webservices.client.MockWebServiceServerTestExecutionListener, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.event.ApplicationEventsTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener, org.springframework.test.context.event.EventPublishingTestExecutionListener]
23:42:08.770 [Test worker] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Skipping candidate TestExecutionListener [org.springframework.test.context.transaction.TransactionalTestExecutionListener] due to a missing dependency. Specify custom listener classes or make the default listener classes and their required dependencies available. Offending class: [org/springframework/transaction/interceptor/TransactionAttributeSource]
23:42:08.776 [Test worker] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Skipping candidate TestExecutionListener [org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener] due to a missing dependency. Specify custom listener classes or make the default listener classes and their required dependencies available. Offending class: [org/springframework/transaction/interceptor/TransactionAttribute]
23:42:08.780 [Test worker] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@411aab0f, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@2ad56fb6, org.springframework.test.context.event.ApplicationEventsTestExecutionListener@7d463042, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@990886, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@144f8949, org.springframework.test.context.support.DirtiesContextTestExecutionListener@15e6fca9, org.springframework.test.context.event.EventPublishingTestExecutionListener@596e1a77, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener@11fbf4e4, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener@79963253, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener@5bb78a7c, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener@72239edf, org.springframework.boot.test.autoconfigure.webservices.client.MockWebServiceServerTestExecutionListener@3cb118ab, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener@747da1c4]
23:42:08.789 [Test worker] DEBUG org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener - Before test class: context [DefaultTestContext@11ba4bf0 testClass = NotificationTest, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@2557e04b testClass = NotificationTest, locations = '{}', classes = '{class be.ac.umons.g04.api.core.Launcher}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.autoconfigure.actuate.metrics.MetricsExportContextCustomizerFactory$DisableMetricExportContextCustomizer@a3f6208, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@192299b4, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@1428ce93, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@539f22ff, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@fd7a8f0, org.springframework.boot.test.context.SpringBootTestArgs@1, org.springframework.boot.test.context.SpringBootTestWebEnvironment@702b155b], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.activateListener' -> true]], class annotated with @DirtiesContext [false] with mode [null].
23:42:08.834 [Test worker] DEBUG org.springframework.test.context.support.TestPropertySourceUtils - Adding inlined properties to environment: {spring.jmx.enabled=false, org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.5.1)

2021-07-23 23:42:09.183  INFO 12824 --- [    Test worker] b.a.u.g.a.c.resources.NotificationTest   : Starting NotificationTest using Java 11.0.2 on VS-Kamino with PID 12824 (started by lefan in E:\UNIF\BAC2\Projet-de-Genie-Logiciel\PGL-Aout\PGL04\api)
2021-07-23 23:42:09.185  INFO 12824 --- [    Test worker] b.a.u.g.a.c.resources.NotificationTest   : No active profile set, falling back to default profiles: default
2021-07-23 23:42:11.088  INFO 12824 --- [    Test worker] b.a.u.g.a.c.resources.NotificationTest   : Started NotificationTest in 2.244 seconds (JVM running for 4.416)

Connection refused: connect
java.net.ConnectException: Connection refused: connect
    at java.base/java.net.PlainSocketImpl.connect0(Native Method)
    at java.base/java.net.PlainSocketImpl.socketConnect(PlainSocketImpl.java:101)
    at java.base/java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:399)
    at java.base/java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:242)
    at java.base/java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:224)
    at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:403)
    at java.base/java.net.Socket.connect(Socket.java:591)
    at org.apache.http.conn.ssl.SSLSocketFactory.connectSocket(SSLSocketFactory.java:543)
    at org.apache.http.conn.ssl.SSLSocketFactory.connectSocket(SSLSocketFactory.java:415)
    /!\ the output is way longer, with tons of method calls, I had to cut through because there were too many characters. /!\


NotificationTest > test_dummy() FAILED
    java.net.ConnectException at NotificationTest.java:49
1 test completed, 1 failed
> Task :api:test FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':api:test'.
> There were failing tests. See the report at: file:///E:/UNIF/BAC2/Projet-de-Genie-Logiciel/PGL-Aout/PGL04/api/build/reports/tests/test/index.html
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
BUILD FAILED in 14s
4 actionable tasks: 2 executed, 2 up-to-date

It clearly says that it cannot connect, if I delete the @SpringBootTest annotation, it will say that it cannot connect to the route https://localhost:8443 :

23:44:32.876 [Test worker] DEBUG org.apache.http.impl.conn.BasicClientConnectionManager - Get connection for route {s}->https://localhost:8443
23:44:32.901 [Test worker] DEBUG org.apache.http.impl.conn.DefaultClientConnectionOperator - Connecting to localhost:8443
23:44:35.246 [Test worker] DEBUG org.apache.http.impl.conn.DefaultClientConnectionOperator - Connect to localhost:8443 timed out. Connection will be retried using another IP address
23:44:35.246 [Test worker] DEBUG org.apache.http.impl.conn.DefaultClientConnectionOperator - Connecting to localhost:8443
23:44:37.275 [Test worker] DEBUG org.apache.http.impl.conn.DefaultClientConnection - Connection org.apache.http.impl.conn.DefaultClientConnection@3f898179 closed
23:44:37.275 [Test worker] DEBUG org.apache.http.impl.conn.DefaultClientConnection - Connection org.apache.http.impl.conn.DefaultClientConnection@3f898179 shut down
23:44:37.276 [Test worker] DEBUG org.apache.http.impl.conn.BasicClientConnectionManager - Releasing connection org.apache.http.impl.conn.ManagedClientConnectionImpl@367dd194

I cannot find a workaround to perform my test request.

If you need more informations I will gladly upload them. If you have any hints feel free to share ! Thank you !

The default behaviour of @SpringBootTest is starting a mock server, but you can start a real one like this:

@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT)
@TestPropertySource(properties = "server.port=8443")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM