gpt4 book ai didi

spring-boot - spring-boot 上的集成测试抛出连接被拒绝

转载 作者:行者123 更新时间:2023-12-03 15:57:10 25 4
gpt4 key购买 nike

我对 Spring Boot 进行了单元测试:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
public class CustomerControllerIT {
private RestTemplate restTemplate = new RestTemplate();
@Test
public void findAllCustomers() throws Exception {
ResponseEntity<List<Customer>> responseEntity = restTemplate.exchange(
"http://localhost:8080/Customer", HttpMethod.GET, null,
new ParameterizedTypeReference<List<Customer>>() {
});
List<Customer> list = responseEntity.getBody();
Assert.assertEquals(list.size(), 0);
}
}
  • 如果我在启动的应用程序上启动测试 - 测试正常
  • 如果我尝试仅启动 IT,则会出现连接拒绝错误

  • 我的 application.properties单次启动也是一样。
    用于测试并位于资源和测试资源中。
    Application.class 是:
    @ComponentScan({"mypackage"})
    @EntityScan(basePackages = {"mypackage.model"})
    @EnableJpaRepositories(basePackages = {"mypackage.persistence"})
    @SpringBootApplication
    public class Application extends SpringBootServletInitializer {
    public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
    }
    }

    最佳答案

    您必须使用正在运行的服务器运行测试 ,
    如果您需要启动一个完整运行的服务器,您可以使用随机端口:

  • @SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)

  • An available port is picked at random each time your test runs


    你需要这个 maven 依赖:
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-test</artifactId>
    </dependency>
    例子:
    @RunWith(SpringRunner.class)
    @SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
    public class TestRest {

    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    public void findAllCustomers() throws Exception {
    ResponseEntity<List<Customer>> responseEntity = restTemplate.exchange(
    "/Customer", HttpMethod.GET, null,
    new ParameterizedTypeReference<List<Customer>>(){});
    List<Customer> list = responseEntity.getBody();
    Assert.assertEquals(list.size(), 0);
    }
    }
    更多内容请阅读文档 reference

    关于spring-boot - spring-boot 上的集成测试抛出连接被拒绝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52335562/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com