#spring-boot #mockito #jhipster #junit5 #spring-cloud-feign
#пружинный ботинок #мокито #jhipster #июнь5 #весеннее облако-притворство
Вопрос:
Я использую Jhipster для создания 2 микросервисов. Один микросервис вызывает другой микросервис с помощью FeignClient, но когда я пытаюсь протестировать первый микросервис, он выдает ошибку, я думаю, что причина в FeignClient. Что в этих случаях рекомендуется делать? Любая рекомендация будет признательна
Резервный ресурс
@PostMapping("/reservations") public ResponseEntitylt;?gt; createReservation(@RequestBody Reservation reservation){ Reservation result = reservationService.saveReservation(reservation); return ResponseEntity .created(new URI("/api/reservations/" result.getId())) .headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, result.getId().toString())) .body(result); }
Служба резервированияимпл
Этот класс вызывает функцию FeignClient перед сохранением бронирования.
@Override public Reservation saveReservation(Reservation reservation) { roomFeignClient.updateRoomByNumber(reservation.getRoom()); return save(reservation); }
Резервация ресурсов
Тестовый класс автоматически генерируется Jhipster
@IntegrationTest @AutoConfigureMockMvc @WithMockUser class ReservationResourceIT { private static final Long DEFAULT_CLIENT = 1L; private static final Long UPDATED_CLIENT = 2L; private static final Long DEFAULT_ROOM = 101L; private static final Long UPDATED_ROOM = 2L; private static final LocalDate DEFAULT_ENTRY_DATE = LocalDate.ofEpochDay(0L); private static final LocalDate UPDATED_ENTRY_DATE = LocalDate.now(ZoneId.systemDefault()); private static final LocalDate DEFAULT_OUT_DATE = LocalDate.ofEpochDay(0L); private static final LocalDate UPDATED_OUT_DATE = LocalDate.now(ZoneId.systemDefault()); private static final Double DEFAULT_TOTAL_PRICE = 1D; private static final Double UPDATED_TOTAL_PRICE = 2D; private static final String ENTITY_API_URL = "/api/reservations"; private static final String ENTITY_API_URL_ID = ENTITY_API_URL "/{id}"; private static Random random = new Random(); private static AtomicLong count = new AtomicLong(random.nextInt() (2 * Integer.MAX_VALUE)); @Autowired private ReservationRepository reservationRepository; @Autowired private EntityManager em; @Autowired private MockMvc restReservationMockMvc; private Reservation reservation; public static Reservation createEntity(EntityManager em) { Reservation reservation = new Reservation() .client(DEFAULT_CLIENT) .room(DEFAULT_ROOM) .entryDate(DEFAULT_ENTRY_DATE) .outDate(DEFAULT_OUT_DATE) .totalPrice(DEFAULT_TOTAL_PRICE); return reservation; } public static Reservation createUpdatedEntity(EntityManager em) { Reservation reservation = new Reservation() .client(UPDATED_CLIENT) .room(UPDATED_ROOM) .entryDate(UPDATED_ENTRY_DATE) .outDate(UPDATED_OUT_DATE) .totalPrice(UPDATED_TOTAL_PRICE); return reservation; } @BeforeEach public void initTest() { reservation = createEntity(em); } @Test @WithMockUser(roles = "ADMIN") @Transactional void createReservation() throws Exception { int databaseSizeBeforeCreate = reservationRepository.findAll().size(); // Create the Reservation restReservationMockMvc .perform(post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(reservation))) .andExpect(status().isCreated()); // Validate the Reservation in the database Listlt;Reservationgt; reservationList = reservationRepository.findAll(); assertThat(reservationList).hasSize(databaseSizeBeforeCreate 1); Reservation testReservation = reservationList.get(reservationList.size() - 1); assertThat(testReservation.getClient()).isEqualTo(DEFAULT_CLIENT); assertThat(testReservation.getRoom()).isEqualTo(DEFAULT_ROOM); assertThat(testReservation.getEntryDate()).isEqualTo(DEFAULT_ENTRY_DATE); assertThat(testReservation.getOutDate()).isEqualTo(DEFAULT_OUT_DATE); assertThat(testReservation.getTotalPrice()).isEqualTo(DEFAULT_TOTAL_PRICE); } }
Вот сообщение об ошибке, когда я запускаю тест
2021-12-10 14:08:25.302 DEBUG 16236 --- [ main] reactor.util.Loggers : Using Slf4j logging framework 2021-12-10 14:08:25.304 DEBUG 16236 --- [ main] reactor.core.publisher.Hooks : Hooking onLastOperator: org.springframework.security.core.context.SecurityContext 2021-12-10 14:08:25.689 DEBUG 16236 --- [ main] feign.template.Template : Explicit slash decoding specified, decoding all slashes in uri 2021-12-10 14:08:25.857 WARN 16236 --- [oundedElastic-1] o.s.c.l.core.RoundRobinLoadBalancer : No servers available for service: roomservice 2021-12-10 14:08:25.859 WARN 16236 --- [ main] .s.c.o.l.FeignBlockingLoadBalancerClient : Service instance was not resolved, executing the original request 2021-12-10 14:08:32.730 WARN 16236 --- [oundedElastic-1] o.s.c.l.core.RoundRobinLoadBalancer : No servers available for service: roomservice 2021-12-10 14:08:32.731 WARN 16236 --- [ main] .s.c.o.l.FeignBlockingLoadBalancerClient : Service instance was not resolved, executing the original request 2021-12-10 14:08:32.771 ERROR 16236 --- [ main] o.z.problem.spring.common.AdviceTraits : Internal Server Error feign.RetryableException: roomservice executing GET http://roomservice/api/rooms/state/101 at feign.FeignException.errorExecuting(FeignException.java:249) at feign.SynchronousMethodHandler.executeAndDecode(SynchronousMethodHandler.java:129) at feign.SynchronousMethodHandler.invoke(SynchronousMethodHandler.java:89) at feign.ReflectiveFeign$FeignInvocationHandler.invoke(ReflectiveFeign.java:100) at com.sun.proxy.$Proxy195.changeStateRoom(Unknown Source) at com.hotel.reservation.service.impl.ReservationServiceImpl.changeStateRoom(ReservationServiceImpl.java:149) at com.hotel.reservation.service.impl.ReservationServiceImpl.saveReservation(ReservationServiceImpl.java:165) at com.hotel.reservation.service.impl.ReservationServiceImpl$FastClassBySpringCGLIB$9845a4f5.invoke(lt;generatedgt;) at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218) at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:779) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:750) at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:123) at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:388) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:750) at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:692) at com.hotel.reservation.service.impl.ReservationServiceImpl$EnhancerBySpringCGLIB$bb12020f.saveReservation(lt;generatedgt;) at com.hotel.reservation.web.rest.ReservationResource.createReservation(ReservationResource.java:77) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:566) at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:197) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:141) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:894) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1060) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:962) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909) at javax.servlet.http.HttpServlet.service(HttpServlet.java:517) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:72) at javax.servlet.http.HttpServlet.service(HttpServlet.java:584) at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167) at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134) at org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:91) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:327) at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:115) at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:81) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:119) at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:126) at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:81) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:105) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:149) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) at com.hotel.reservation.security.jwt.JWTFilter.doFilter(JWTFilter.java:37) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:103) at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:89) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:90) at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:75) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:110) at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:80) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:55) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:211) at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:183) at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:358) at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:271) at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134) at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134) at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134) at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:93) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134) at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:183) at com.hotel.reservation.web.rest.ReservationResourceIT.createReservation(ReservationResourceIT.java:110) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:566) at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:688) at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60) at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131) at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149) at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140) at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84) at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115) at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105) at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106) at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64) at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45) at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37) at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104) at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98) at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:210) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:206) at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:131) at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:65) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129) at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126) at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84) at java.base/java.util.ArrayList.forEach(ArrayList.java:1541) at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129) at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126) at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84) at java.base/java.util.ArrayList.forEach(ArrayList.java:1541) at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129) at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126) at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84) at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32) at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57) at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51) at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:108) at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88) at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54) at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67) at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52) at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:96) at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:75) at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:71) at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33) at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235) at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54) Caused by: java.net.UnknownHostException: roomservice at java.base/java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:229) at java.base/java.net.Socket.connect(Socket.java:608) at java.base/sun.net.NetworkClient.doConnect(NetworkClient.java:177) at java.base/sun.net.www.http.HttpClient.openServer(HttpClient.java:474) at java.base/sun.net.www.http.HttpClient.openServer(HttpClient.java:569) at java.base/sun.net.www.http.HttpClient.lt;initgt;(HttpClient.java:242) at java.base/sun.net.www.http.HttpClient.New(HttpClient.java:341) at java.base/sun.net.www.http.HttpClient.New(HttpClient.java:362) at java.base/sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:1253) at java.base/sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1187) at java.base/sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1081) at java.base/sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:1015) at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1592) at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1520) at java.base/java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:527) at feign.Client$Default.convertResponse(Client.java:108) at feign.Client$Default.execute(Client.java:104) at org.springframework.cloud.openfeign.loadbalancer.LoadBalancerUtils.executeWithLoadBalancerLifecycleProcessing(LoadBalancerUtils.java:56) at org.springframework.cloud.openfeign.loadbalancer.RetryableFeignBlockingLoadBalancerClient.lambda$execute$2(RetryableFeignBlockingLoadBalancerClient.java:156) at org.springframework.retry.support.RetryTemplate.doExecute(RetryTemplate.java:329) at org.springframework.retry.support.RetryTemplate.execute(RetryTemplate.java:225) at org.springframework.cloud.openfeign.loadbalancer.RetryableFeignBlockingLoadBalancerClient.execute(RetryableFeignBlockingLoadBalancerClient.java:103) at feign.SynchronousMethodHandler.executeAndDecode(SynchronousMethodHandler.java:119) ... 156 common frames omitted MockHttpServletRequest: HTTP Method = POST Request URI = /api/reservations Parameters = {} Headers = [Content-Type:"application/json;charset=UTF-8", Content-Length:"84"] Body = {"client":1,"room":101,"entryDate":[1970,1,1],"outDate":[1970,1,1],"totalPrice":1.0} Session Attrs = {} Handler: Type = com.hotel.reservation.web.rest.ReservationResource Method = com.hotel.reservation.web.rest.ReservationResource#createReservation(Reservation) Async: Async started = false Async result = null Resolved Exception: Type = feign.RetryableException ModelAndView: View name = null View = null Model = null FlashMap: Attributes = null MockHttpServletResponse: Status = 500 Error message = null Headers = [Vary:"Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers", Content-Type:"application/problem json", X-Content-Type-Options:"nosniff", X-XSS-Protection:"1; mode=block", Cache-Control:"no-cache, no-store, max-age=0, must-revalidate", Pragma:"no-cache", Expires:"0", X-Frame-Options:"DENY", Content-Security-Policy:"default-src 'self'; frame-src 'self' data:; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://storage.googleapis.com; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:", Referrer-Policy:"strict-origin-when-cross-origin", Feature-Policy:"geolocation 'none'; midi 'none'; sync-xhr 'none'; microphone 'none'; camera 'none'; magnetometer 'none'; gyroscope 'none'; fullscreen 'self'; payment 'none'"] Content type = application/problem json Body = {"type":"https://www.jhipster.tech/problem/problem-with-message","title":"Internal Server Error","status":500,"detail":"roomservice executing GET http://roomservice/api/rooms/state/101","path":"/api/reservations","message":"error.http.500"} Forwarded URL = null Redirected URL = null Cookies = [] 2021-12-10 14:08:32.854 DEBUG 16236 --- [ main] reactor.core.publisher.Hooks : Reset onLastOperator: org.springframework.security.core.context.SecurityContext java.lang.AssertionError: Status expected:lt;201gt; but was:lt;500gt; Expected :201 Actual :500 lt;Click to see differencegt; at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:59) at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:122) at org.springframework.test.web.servlet.result.StatusResultMatchers.lambda$matcher$9(StatusResultMatchers.java:627)
Комментарии:
1. Как показывает ошибка, притворный клиент пытается подключиться к хосту с именем, подобным вашему микросервису
roomservice
, поскольку обычно он преобразуется в ip-адрес или реальное имя хоста с использованием информации из реестра служб. Какой реестр вы используете?2. Я использую реестр Jhipster, который является сервером Eureka
3. Ну, вопрос в том, какой тест вы хотите написать? Модульные тесты: вы должны издеваться над фальшивым клиентом или любой службой, для которой требуется внешняя зависимость. Интеграционные тесты: затем вы должны запустить 2 микросервиса и сервер eureka.
4. Я хочу написать интеграционные тесты. Мои 2 микросервиса и сервер eureka работают, когда я запускаю тест, но ошибка все равно продолжает появляться
5. Таким образом, это означает, что ваш тест не извлекает реестр с вашего сервера eureka, возможно, это неправильная конфигурация. Почему вы хотите писать интеграционные тесты , вы не сможете тестировать угловые случаи, а настройка намного сложнее.
@IntegrationTest
не являются интеграционными тестами в том смысле, в каком вы используете их с вашими 2 микросервисами и запущенным сервером eureka.