org.springframework.web.reactive.function.client.WebClientRequestException:连接被拒绝:/0:0:0:0:0:0:0:1:80;

Pat*_*Pat 4 java junit5 spring-webflux

关于使用 Junit5 + Spring WebClient 进行单元测试的小问题。

\n

我有一个@Service带有 WebClient 的基础课程@Autowired

\n
@Autowired private final WebClient webClient;\nprivate MyAtServiceClass(WebClient webClient) {\n this.webClient = webClient;\n}\n\n    public Mono<MyPojo> sendHttpRequestToSomewhere(String payload) {\n        return webClient.mutate().baseUrl("http://...").build().post().body(BodyInserters.fromValue(payload)).retrieve().bodyToMono(MyPojo.class);\n    }\n
Run Code Online (Sandbox Code Playgroud)\n

由于我只想进行单元测试,因此我在测试类中使用以下内容执行一些 \xe2\x80\x9cmock\xe2\x80\x9d :

\n
String payload = getSomeHardedCodedJsonPayload();\nWebClient webClient = WebClient.builder()\n        .exchangeFunction(clientRequest ->\n                Mono.just(ClientResponse.create(HttpStatus.OK)\n                        .header("content-type", "application/json")\n                        .body(payload)\n                        .build())\n        ).build();\n\nMyAtServiceClass myAtServiceClass     = new MyAtServiceClass(webClient);\nMono<MyPojo> mono = myAtServiceClass.sendHttpRequestToSomewhere();\nassertEquals(\xe2\x80\x9cfoo\xe2\x80\x9d, mono.block().getFoo());\n
Run Code Online (Sandbox Code Playgroud)\n

然而,当我运行单元测试时,期望它只返回我的虚拟对象,我收到下面的连接被拒绝异常。

\n

请问根本原因是什么?

\n
org.springframework.web.reactive.function.client.WebClientRequestException: Connection refused: /0:0:0:0:0:0:0:1:80; nested exception is io.netty.channel.AbstractChannel$AnnotatedConnectException: Connection refused: /0:0:0:0:0:0:0:1:80\n\n    at org.springframework.web.reactive.function.client.ExchangeFunctions$DefaultExchangeFunction.lambda$wrapException$9(ExchangeFunctions.java:137)\n    Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException: \nError has been observed at the following site(s):\n    |_ checkpoint \xe2\x87\xa2 Request to POST /somewhere [DefaultWebClient]\nStack trace:\n        at org.springframework.web.reactive.function.client.ExchangeFunctions$DefaultExchangeFunction.lambda$wrapException$9(ExchangeFunctions.java:137)\n        at reactor.core.publisher.MonoErrorSupplied.subscribe(MonoErrorSupplied.java:70)\n        at reactor.core.publisher.Mono.subscribe(Mono.java:4046)\n        at reactor.core.publisher.FluxOnErrorResume$ResumeSubscriber.onError(FluxOnErrorResume.java:103)\n        at reactor.core.publisher.FluxPeek$PeekSubscriber.onError(FluxPeek.java:221)\n        at reactor.core.publisher.FluxPeek$PeekSubscriber.onError(FluxPeek.java:221)\n        at reactor.core.publisher.FluxPeek$PeekSubscriber.onError(FluxPeek.java:221)\n        at reactor.core.publisher.MonoNext$NextSubscriber.onError(MonoNext.java:93)\n        at reactor.core.publisher.MonoFlatMapMany$FlatMapManyMain.onError(MonoFlatMapMany.java:204)\n        at reactor.core.publisher.SerializedSubscriber.onError(SerializedSubscriber.java:124)\n        at reactor.core.publisher.FluxRetryWhen$RetryWhenMainSubscriber.whenError(FluxRetryWhen.java:224)\n        at reactor.core.publisher.FluxRetryWhen$RetryWhenOtherSubscriber.onError(FluxRetryWhen.java:273)\n        at reactor.core.publisher.FluxConcatMap$ConcatMapImmediate.drain(FluxConcatMap.java:413)\n        at reactor.core.publisher.FluxConcatMap$ConcatMapImmediate.onNext(FluxConcatMap.java:250)\n        at reactor.core.publisher.EmitterProcessor.drain(EmitterProcessor.java:491)\n        at reactor.core.publisher.EmitterProcessor.tryEmitNext(EmitterProcessor.java:299)\n        at reactor.core.publisher.SinkManySerialized.tryEmitNext(SinkManySerialized.java:97)\n        at reactor.core.publisher.InternalManySink.emitNext(InternalManySink.java:27)\n        at reactor.core.publisher.FluxRetryWhen$RetryWhenMainSubscriber.onError(FluxRetryWhen.java:189)\n        at reactor.core.publisher.MonoCreate$DefaultMonoSink.error(MonoCreate.java:189)\n        at reactor.netty.http.client.HttpClientConnect$MonoHttpConnect$ClientTransportSubscriber.onError(HttpClientConnect.java:306)\n        at reactor.core.publisher.MonoCreate$DefaultMonoSink.error(MonoCreate.java:189)\n        at reactor.netty.resources.DefaultPooledConnectionProvider$DisposableAcquire.onError(DefaultPooledConnectionProvider.java:166)\n        at reactor.netty.internal.shaded.reactor.pool.AbstractPool$Borrower.fail(AbstractPool.java:427)\n        at reactor.netty.internal.shaded.reactor.pool.SimpleDequePool.lambda$drainLoop$5(SimpleDequePool.java:310)\n        at reactor.core.publisher.FluxDoOnEach$DoOnEachSubscriber.onError(FluxDoOnEach.java:186)\n        at reactor.core.publisher.MonoCreate$DefaultMonoSink.error(MonoCreate.java:189)\n        at reactor.netty.resources.DefaultPooledConnectionProvider$PooledConnectionAllocator$PooledConnectionInitializer.onError(DefaultPooledConnectionProvider.java:565)\n        at reactor.core.publisher.MonoFlatMap$FlatMapMain.secondError(MonoFlatMap.java:192)\n        at reactor.core.publisher.MonoFlatMap$FlatMapInner.onError(MonoFlatMap.java:259)\n        at reactor.netty.transport.TransportConnector$MonoChannelPromise.tryFailure(TransportConnector.java:464)\n        at reactor.netty.transport.TransportConnector$MonoChannelPromise$1.tryFailure(TransportConnector.java:515)\n        at io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.fulfillConnectPromise(AbstractNioChannel.java:321)\n        at io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.finishConnect(AbstractNioChannel.java:337)\n        at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:707)\n        at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:655)\n        at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:581)\n        at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:493)\n        at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:989)\n        at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)\n        at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)\n        at java.base/java.lang.Thread.run(Thread.java:834)\n    Suppressed: java.lang.Exception: #block terminated with an error\n        at reactor.core.publisher.BlockingSingleSubscriber.blockingGet(BlockingSingleSubscriber.java:99)\n        at reactor.core.publisher.Mono.block(Mono.java:1703)\n\n        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\n        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n        at java.base/java.lang.reflect.Method.invoke(Method.java:566)\n        at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:688)\n        at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)\n        at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)\n        at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)\n        at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)\n        at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)\n        at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)\n        at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)\n        at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)\n        at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)\n        at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)\n        at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)\n        at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)\n        at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)\n        at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:210)\n        at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\n        at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:206)\n        at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:131)\n        at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:65)\n        at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)\n        at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\n        at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)\n        at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)\n        at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)\n        at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\n        at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)\n        at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)\n        at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)\n        at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)\n        at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)\n        at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\n        at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)\n        at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)\n        at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)\n        at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\n        at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)\n        at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)\n        at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)\n        at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)\n        at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)\n        at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\n        at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)\n        at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)\n        at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)\n        at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)\n        at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)\n        at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)\n        at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)\n        at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)\n        at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)\n        at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:108)\n        at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)\n        at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)\n        at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)\n        at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)\n        at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:96)\n        at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:75)\n        at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:71)\n        at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)\n        at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:220)\n        at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:53)\nCaused by: io.netty.channel.AbstractChannel$AnnotatedConnectException: Connection refused: /0:0:0:0:0:0:0:1:80\nCaused by: java.net.ConnectException: Connection refused\n    at java.base/sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)\n    at java.base/sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:779)\n    at io.netty.channel.socket.nio.NioSocketChannel.doFinishConnect(NioSocketChannel.java:330)\n    at io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.finishConnect(AbstractNioChannel.java:334)\n    at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:707)\n    at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:655)\n    at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:581)\n    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:493)\n    at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:989)\n    at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)\n    at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)\n    at java.base/java.lang.Thread.run(Thread.java:834)\n
Run Code Online (Sandbox Code Playgroud)\n

上面是整个堆栈跟踪。

\n

谢谢

\n

mor*_*ore 6

与你的问题无关,但也许它可以帮助那些像我一样陷入同样陷阱的人(尽管你可能知道这一点,就像我实际上所做的那样)。

正如多个教程中所述,您必须密切注意.uri(...)您使用的方法的版本。

有关版本的更多详细信息uri(...)可以在 Spring API 中找到:WebClient.UriSpec

如果您使用eg,.uri(URI)您将覆盖您之前可能指定的任何URL(使用eg .baseUrl("http://localhost:8888")),因此,如果您只想将路径(例如)附加/my-service/booking到基本URL,则不能使用此重载方法,否则您将错过host和/or port,因此出现上述错误消息。