簡體   English   中英

RestAssured 無法連接(單元測試 - Jersey REST API with Spring boot)

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

我正在用 Jersey 開發 REST-API,我使用 Spring 來運行服務器。 我目前正在嘗試為它編寫一些單元測試,我選擇 RestAssured(在 Jersey 測試框架中有問題)。

現在我只是想測試一個虛擬資源,但它不起作用。 它似乎無法連接(我猜是連接到服務器)。 這是我的測試:

@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));
    }
}

你可以看到我已經設置了端口、baseURI 和 basePath(我正在測試一個安全的 API,我們使用 https)。 我試圖找到模擬 Spring 服務器的方法,但沒有成功。 這是輸出:

    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

明明說不能連接,如果我刪除@SpringBootTest注解,會說不能連接到路由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

我找不到執行我的測試請求的解決方法。

如果您需要更多信息,我很樂意上傳它們。 如果您有任何提示,請隨時分享! 謝謝 !

@SpringBootTest的默認行為是啟動一個模擬服務器,但你可以像這樣啟動一個真實的服務器:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM