Spring Boot Test не удалось автоматически подключить порт с аннотацией LocalServerPort - PullRequest
0 голосов
/ 08 мая 2018

Я использую Spring Boot 2.0.1 и Junit 5. Я пытаюсь получить порт в интеграционном тесте. Однако значение порта всегда равно нулю. Я не уверен, что может быть причиной этого. Я попытался изменить enum веб-среды на случайный порт, но ничего не работает.

package com.example.demo;

import org.junit.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import static org.junit.jupiter.api.Assertions.assertNotEquals;

@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class DemoApplicationTests {

@LocalServerPort
private int port;
@Test


public void printPort() throws Exception {
     assertNotEquals(port, 0);
}
}

Ниже приведен pom (примечание показывает только зависимости)

<properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <junit-jupiter.version>5.2.0</junit-jupiter.version>
        <junit-platform.version>1.2.0</junit-platform.version>
    </properties>

    <dependencies>
         <dependency>
                <groupId>org.junit.platform</groupId>
                <artifactId>junit-platform-launcher</artifactId>
                <scope>test</scope>
                <version>${junit-platform.version}</version>
            </dependency>
            <dependency>
                <groupId>org.junit.platform</groupId>
                <artifactId>junit-platform-engine</artifactId>
                <scope>test</scope>
                <version>${junit-platform.version}</version>
            </dependency>
            <dependency>
                <groupId>org.junit.jupiter</groupId>
                <artifactId>junit-jupiter-api</artifactId>
                <scope>test</scope>
                <version>${junit-jupiter.version}</version>
            </dependency>
            <dependency>
                <groupId>org.junit.jupiter</groupId>
                <artifactId>junit-jupiter-engine</artifactId>
                <scope>test</scope>
                <version>${junit-jupiter.version}</version>
            </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

application.properties

server.port=8080

Ответы [ 5 ]

0 голосов
/ 26 ноября 2018

У меня была такая же проблема, этот набор комментариев ниже работал для меня. Без @ContextConfiguration порт был 0.

@ContextConfiguration
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class TestBase {

@LocalServerPort
protected int port;

}
0 голосов
/ 29 октября 2018

У меня была такая же проблема. Это решение работало для меня:

@Service
public class TestService implements ApplicationListener<ServletWebServerInitializedEvent> {

   private int localPort;

   @Override
   public void onApplicationEvent(final ServletWebServerInitializedEvent event) {
       localPort = event.getWebServer().getPort();
   }
}

Вы можете автоматически подключить эту службу или реализовать ApplicationListener непосредственно в своем тестовом классе. Просто предупреждение - переменная localPort инициализируется во время запуска приложения после того, как bean-компонент полностью готов, поэтому он не будет доступен в @PostConstruct и т. Д.

0 голосов
/ 09 мая 2018

Здесь вы можете найти пример, используя RANDOM_PORT. Вы можете изменить значение на DEFINED_PORT, просто изменив значение webEnvironment, и в этом случае значение переменной serverPort будет равно 8080, значение по умолчанию.

0 голосов
/ 09 мая 2018

Вам не хватает зависимости от spring-boot-starter-web.

0 голосов
/ 08 мая 2018

Добавьте @TestPropertySource(locations = "classpath:test.properties") поверх вашего тестового класса. Вы пробовали @Value("${server.port}") вместо @LocalServerPort?

...