我昨天遇到同樣的問題,爲了完整起見,這裏是我的解決方案:
這是我的「活」的配置下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