Spring Boot 与 WireMock 和 Eureka 的集成测试失败,并显示“没有可用的实例”

der*_*eve 5 java spring spring-boot wiremock netflix-eureka

当为使用 RestTemplate(和底层的 Ribbon)和 Eureka 来解决服务 B 依赖关系的 Spring Boot 应用程序(服务 A)编写集成测试时,我在调用服务 A 时收到“无可用实例”异常。

我尝试通过 WireMock 模拟服务 B,但我什至没有到达 WireMock 服务器。RestTemplate 似乎尝试从 Eureka 获取 Service 实例,但它在我的测试中没有运行。它通过属性被禁用。

服务A调用服务B。服务发现是通过RestTemplate、Ribbon和Eureka完成的。

有人有一个包含 Spring、Eureka 和 WireMock 的工作示例吗?

Han*_*nes 3

我昨天遇到了同样的问题,为了完整起见,这是我的解决方案:

这是我的“实时”配置src/main/java/.../config

//the regular configuration not active with test profile
@Configuration
@Profile("!test")
public class WebConfig {
    @LoadBalanced
    @Bean
    RestTemplate restTemplate() {
        //you can use your regular rest template here.
        //This one adds a X-TRACE-ID header from the MDC to the call.
        return TraceableRestTemplate.create();
    }
}
Run Code Online (Sandbox Code Playgroud)

我将此配置添加到测试文件夹中src/main/test/java/.../config

//the test configuration
@Configuration
@Profile("test")
public class WebConfig {
    @Bean
    RestTemplate restTemplate() {
        return TraceableRestTemplate.create();
    }
}
Run Code Online (Sandbox Code Playgroud)

在测试用例中,我激活了配置文件test

 //...
@ActiveProfiles("test")
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ServerCallTest {
   @Autowired
   private IBusiness biz;

   @Autowired
   private RestTemplate restTemplate;

   private ClientHttpRequestFactory originalClientHttpRequestFactory;

   @Before
   public void setUp() {
       originalClientHttpRequestFactory = restTemplate.getRequestFactory();
   }

   @After
   public void tearDown() {
      restTemplate.setRequestFactory(originalClientHttpRequestFactory);
   }

   @Test
   public void fetchAllEntries() throws BookListException {
      MockRestServiceServer mockServer = MockRestServiceServer.createServer(restTemplate);

       mockServer                
            .andExpect(method(HttpMethod.GET))
            .andExpect(header("Accept", "application/json"))
            .andExpect(requestTo(endsWith("/list/entries/")))
            .andRespond(withSuccess("your-payload-here", MediaType.APPLICATION_JSON));

       MyData data = biz.getData();

       //do your asserts
   }
}
Run Code Online (Sandbox Code Playgroud)