测试类中的Spring Boot RestTemplate调用在第二种方法中不起作用

Spring Boot RestTemplate call in test class doesn't work in second method

提问人:SmokingTurtle 提问时间:11/8/2023 最后编辑:SmokingTurtle 更新时间:11/9/2023 访问量:18

问:

这是我的 RestUtil 类

import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
public class RestUtil {
    private final RestTemplate restTemplate;

    public RestUtil(RestTemplateBuilder builder) {
        this.restTemplate = builder.build();
    }

    public ResponseEntity<Object> sendRequest(String url, HttpMethod httpMethod,
                                              HttpEntity<String> httpEntity, Class aClass) {
        return restTemplate.exchange(url, httpMethod, httpEntity, aClass);
    }

}

我的测试类中有两种方法,当我同时运行多个测试时,第二个方法会出现 Post Read Time Out 异常,但如果我单独运行它们,它们都可以工作。

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class MyControllerContractTest {
    @LocalServerPort
    private Integer port;


  @Autowired
  RestUtil restUtil;

    @BeforeEach
    void setUp() {
        RestAssured.baseURI = "http://localhost:" + port;
    }

   @Test
   public void testMethod1() {
        //........
        ResponseEntity<Object> authenticationResponse  = restUtil.sendRequest("http://localhost:"+port+"/tokenn", HttpMethod.POST, new HttpEntity<>(postHeader),String.class);

        //.....
    }
    @Test
    public void testMethod2() {
        //.....
        ResponseEntity<Object> authenticationResponse  = restUtil.sendRequest("http://localhost:"+port+"/tokenn", HttpMethod.POST, new HttpEntity<>(postHeader),String.class);
        //.....
    }
}

RestUtil 有什么问题?

spring-boot 集成测试 junit5 resttemplate spring-test

评论


答: 暂无答案