java – 使用WireMock和Eureka的Spring Boot集成测试失败并显示“No instances available”

在为使用RestTemplate(和引擎盖下的功能区)和Eureka来解析服务B依赖关系的Spring Boot应用程序(服务A)编写集成测试时,在调用服务A时出现“无实例可用”异常.

我尝试通过WireMock模拟服务B,但我甚至没有进入WireMock服务器.似乎RestTemplate尝试从Eureka获取Service实例,而该实例不在我的测试中运行.它通过属性禁用.

服务A呼叫服务B.
服务发现通过RestTemplate,Ribbon和Eureka完成.

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

解决方法:

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

这是我在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();
    }
}

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

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

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

 //...
@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
   }
}
上一篇:java – WireMock使用NoSuchMethodError HttpServletResponse.getHeader失败


下一篇:java – 为什么我要使用MockWebServer而不是WireMock?