本文介紹了用Spock模擬的彈簧架模板的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
誰能給我舉個例子,如何使用Spock測試RestTemplate。
我的類如下所示:
@Service
public class SomeService {
@Autowired
private EndpointUrlProvider endpointUrlProvider;
private RestTemplate restTemplate = new RestTemplate();
public SomeResponse doSomePostRequest(HttpEntity<?> httpEntity) throws Exception {
ResponseEntity<SomeResponse> response;
try{
response = restTemplate.postForEntity(endpointUrlProvider.getSomeUrl(),httpEntity,SomeResponse.class);
} catch (Exception e){
throw new Exception("Exception occured during post for:" + httpEntity.getBody().getClass().getSimpleName() + " Cause: " + e.getMessage());
}
if(response.getStatusCode() == HttpStatus.OK){
return response.getBody();
}
throw new Exception("Error during " + response.getBody().getClass().getSimpleName() + "Http status is diffrent than 200: " + response.getBody().toString());
}
}
測試:
class SomeTest extends Specification {
RestTemplate restTemplate = Mock {
postForEntity(_, _, SomeResponse.class) >> new ResponseEntity(new SomeResponse(), HttpStatus.OK)
}
@Autowired
SomeService someService
def "someTest"() {
when:
SomeResponse someResponse = someService.doSomePostRequest(new HttpEntity<>(new SomeBody(), new HttpHeaders()))
then:
someResponse == new SomeResponse()
}
}
主要問題是RESTTemplate的模仿行為,我正在尋找解決方案,如何以正確的方式做到這一點。我不穿彈簧靴。
推薦答案
情況如下:
您在服務類中創建了新的RestTemplate
。
private RestTemplate restTemplate = new RestTemplate();
然后在測試中創建模擬并調用服務方法:
RestTemplate restTemplate = Mock {
postForEntity(_, _, SomeResponse.class) >> new ResponseEntity(new SomeResponse(), HttpStatus.OK)
}
....
someService.doSomePostRequest
但是您的服務內部仍然有常用的REST模板。您應該注入模擬對象。我建議您通過構造函數來完成這項工作。因此將您的代碼更改為:
@Service
public class SomeService {
private EndpointUrlProvider endpointUrlProvider;
private RestTemplate restTemplate;
@Autowired
public SomeService(EndpointUrlProvider endpointUrlProvider, RestTemplate restTemplate){
this.endpointUrlProvider = endpointUrlProvider;
this.restTemplate = restTemplate;
}
您的測試將是:
class SomeTest extends Specification {
RestTemplate restTemplate = Mock {
postForEntity(_, _, SomeResponse.class) >> new ResponseEntity(new SomeResponse(), HttpStatus.OK)
}
SomeService someService = new SomeService ( null, restTemplate);
def "someTest"() {
when:
SomeResponse someResponse = someService.doSomePostRequest(new HttpEntity<>(new SomeBody(), new HttpHeaders()))
then:
someResponse == new SomeResponse()
}
}
現在您的服務對象將在注入的模擬上調用方法,而不是通常的RestTemplate
附注
構造函數注入被認為是春季的一種很好的做法。
最好是創建RestTemplate Bean并將其注入到任何地方,而不是在所有服務中創建新對象。
這篇關于用Spock模擬的彈簧架模板的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,