添加断点时,spock unebing rettemplate起作用

发布于 2025-02-03 12:59:30 字数 1211 浏览 2 评论 0原文

我正在用Spock编写一个单元测试,并试图使用Stub RESTTEMPLATE.POSTFORENTITY(),但是看到一个奇怪的问题,即仅在我添加断点并评估表达式时,该存根才能起作用。它不起作用,并在正常运行时调用pastentity()方法。

这是我的实施。

测试:

def "AuthTokenRequest"() {
    given:
    def url = "https://authEndpoint"
    def map = new LinkedMultiValueMap<>()
    RestTemplate restTemplate = GroovySpy(global: true)
    restTemplate.postForEntity(*_) >> new ResponseEntity(new AuthResponse(), HttpStatus.OK)

    when:
    def responseEntity = client.authTokenRequest(url, map)

    then:
    responseEntity == response
}

方法制作HTTP请求:

public AuthResponse authTokenRequest(String url, MultiValueMap map) {
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<AuthResponse> responseEntity = restTemplate.postForEntity(url, createAuthEntity(map), AuthResponse.class);
    return responseEntity.getBody()?:null
    }

当我运行此测试时,我会得到java.net.inknownhostexception例外postentity()没有固定。

当我对响应态度&lt; authresponse&gt; gt;;响应率= restTemplate.postForentity(url,createEauthentity(map),authresponse.class); 并评估表达式,我得到了固定的响应。

我做错了吗?

I am writing an unit test in Spock and trying to stub RestTemplate.postForEntity() but seeing a weird issue where the stubs only works when I add a breakpoint and evaluate the expression. It doesnt work and calls the postForEntity() method when run normally.

Here is my implementation.

Test:

def "AuthTokenRequest"() {
    given:
    def url = "https://authEndpoint"
    def map = new LinkedMultiValueMap<>()
    RestTemplate restTemplate = GroovySpy(global: true)
    restTemplate.postForEntity(*_) >> new ResponseEntity(new AuthResponse(), HttpStatus.OK)

    when:
    def responseEntity = client.authTokenRequest(url, map)

    then:
    responseEntity == response
}

Method making the HTTP request:

public AuthResponse authTokenRequest(String url, MultiValueMap map) {
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<AuthResponse> responseEntity = restTemplate.postForEntity(url, createAuthEntity(map), AuthResponse.class);
    return responseEntity.getBody()?:null
    }

When I run this test, I get a java.net.UnknownHostException exception because https://authEndpoint doesnt point anywhere which also proves that postEntity() is not being stubbed.

When I put a breakpoint on ResponseEntity<AuthResponse> responseEntity = restTemplate.postForEntity(url, createAuthEntity(map), AuthResponse.class); and evaluate the expression, I get the stubbed response.

Am I doing this wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文