我昨天遇到同样的问题,为了完整起见,这里是我的解决方案:
这是我的“活”的配置下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();
}
}
在测试情况下,我启用配置文件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
}
}
如果你都还好用嘲讽的服务B,您可以用'MockRestServiceServer'。我可以分享一个例子。 – barbakini
这可能是一个选项,但我想包括实际的服务电话,即使响应是罐装的。 – derSteve
当使用'MockRestServiceServer'时,spring启动实际上是一个调用。但只有它被'MockRestServiceServer'所捕获,并且它返回你确定的响应。对于尤里卡部分。它已经是一个熟练的框架工作,你不需要测试它(对于色带或负载平衡问题等) – barbakini