情况如下:
你创造新的RestTemplate
在您的服务级别中。
private RestTemplate restTemplate = new RestTemplate();
然后您在测试中创建模拟并调用您的服务方法:
RestTemplate restTemplate = Mock {
postForEntity(_, _, SomeResponse.class) >> new ResponseEntity(new SomeResponse(), HttpStatus.OK)
}
....
someService.doSomePostRequest
但你的服务里面仍然有通常的休息模板。您应该注入模拟对象。我建议你通过构造函数来完成它。因此,将您的代码更改为:
@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()
}
}
现在你的服务对象将调用注入的 MOCK 上的方法,这不是通常的情况RestTemplate
p.s.
spring 认为构造函数注入是一个很好的实践。
最好创建一个 RestTemplate bean 并将其注入到任何地方,而不是在所有服务中创建新对象。