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

Integration tests on spring-boot throws Connection refused

我在 Spring 引导上进行了单元测试:

@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);
    }
}

我的application.properties也是单人启动

用于测试并位于 resources 和 testResources 中。

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);
    }
}

您必须 运行 使用 运行ning 服务器进行测试 ,

如果你需要启动完整的 运行ning 服务器,你可以使用随机端口:

  • @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

对于 运行 @SpringBootTest 和具有静态端口的 JUnit5 (Jupiter),您可以使用:

@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
class MyUnitTests {
    @Test
    void checkActuator() throws Exception {
        final String url = "http://localhost:8080/actuator/health";
        @SuppressWarnings("rawtypes")
        ResponseEntity<Map> re = new RestTemplate().getForEntity(url, Map.class);
        System.out.println(re);
        assertEquals(HttpStatus.OK, re.getStatusCode());
        re.getStatusCode();
    }
}

如果您使用的是 JUnit 4:

  • 变化:@ExtendWith(SpringExtension.class)
  • 收件人:@RunWith(SpringRunner.class)

然后将端口 属性 添加到您的 application.yml(在文件夹 src/main/resources 内):

server:
  port: 8080

或者如果有 application.properties:

server.port=8080

参考: