Я использую Spring Boot 2.0.1 и Junit 5. Я пытаюсь получить порт в рамках интеграционного теста. Однако значение порта всегда равно нулю. Я не уверен, что могло быть причиной этого. Я попытался изменить перечисление веб-среды на случайный порт, но, похоже, ничего не работает.
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 (NB. Показывает только зависимости)
<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




Добавьте @TestPropertySource(locations = "classpath:test.properties") поверх своего тестового класса. Вы пробовали @Value("${server.port}") вместо @LocalServerPort?
Здесь вы можете найти пример с использованием RANDOM_PORT. Вы можете перейти на DEFINED_PORT, просто изменив значение webEnvironment, и в этом случае значение переменной serverPort будет 8080, значение по умолчанию.
Вам не хватает зависимости от spring-boot-starter-web.
У меня была такая же проблема. Это решение сработало для меня:
@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 и т. д.
У меня была такая же проблема, этот набор аннотаций ниже работал у меня. Без @ContextConfiguration порт был 0.
@ContextConfiguration
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class TestBase {
@LocalServerPort
protected int port;
}
В JUnit5 нет @RunWith
Используйте @ExtendWith в JUnit5
У меня такая же проблема, и я использую junit5, думаю, ваша проблема должна быть такой же. просто сделайте, как показано ниже:
Это должно решить проблему
Связано: stackoverflow.com/questions/30312058/…