Spring Reactive Test не может запустить Netty Server - PullRequest
0 голосов
/ 25 мая 2018

У меня есть весенний тестовый пример, как показано ниже, когда я запускаю, он не запускает сервер Netty и предоставляет следующее исключение.

Caused by: org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.context.ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean.
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:155)

Ниже приведен мой тестовый пример:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringWebFluxDemoApplication.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class CustomPriceControllerTest {

    @Autowired
    private ApplicationContext context;

    private WebTestClient testClient;

    @Before
    public void init() {
        testClient = WebTestClient.bindToApplicationContext(context).configureClient().baseUrl("http://localhost:8080").responseTimeout(Duration.ofSeconds(30)).build();
    }

    @Test
    public void broadcastVoltageConsumption() {

        this.testClient.get().uri("/api/getCustomPrice")
                .accept(MediaType.APPLICATION_STREAM_JSON)
                .exchange()
                .expectBodyList(Custom.class)
                .consumeWith((customResults) -> {
                    List<Custom> list = CustomResults.getResponseBody();
                    Assert.assertTrue(list != null && list.size() > 0);
                });
    }
}

Мой pom.xml исключил зависимость tomcat для включения Netty.Мой класс загрузки Spring работает отлично.Он загружает сервер Netty.

Обновление - pom.xml

 <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
            <exclusions>
                <!-- Exclude the Tomcat dependency -->
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.projectreactor</groupId>
            <artifactId>reactor-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

Пришлось добавить javax.servlet-api, потому что у меня возникли проблемы с javax.servlet-apiотсутствует.

Обновление - 2 Удаление зависимости javax.servlet из pom.xml решает проблему.

Когда я пытаюсь запустить основное приложение, запускается Netty.сервер нормально.Чего не хватает в этой конфигурации?Кто-нибудь может помочь с этим?

Ответы [ 3 ]

0 голосов
/ 23 мая 2019

У меня была такая же проблема.Я просто удаляю эту зависимость (которая имеет зависимость от сервлета):

testCompile('org.springframework.restdocs:spring-restdocs-mockmvc')
0 голосов
/ 09 июня 2019

Если какой-либо зависимости нужен сервлет, это заставит Jetty запуститься, и netty никогда не запустится в этом случае.

Всякий раз, когда вы видите, что webflux запускает Jetty, а не netty, вы должны выполнить следующую команду, а затемПоищите, кто включает Jetty в качестве зависимости, и вы найдете ответ.

./gradlew dependencies

В вашем случае вы включаете зависимость сервлета напрямую, которая вызывает эту проблему.

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <scope>test</scope>
    </dependency>
0 голосов
/ 25 мая 2018

Вы хотели, чтобы веб-сервер работал на Netty, но вы получаете исключение, специфичное для сервлета

Поскольку Netty не является технологией, основанной на сервлете, вам кажется, что где-то (конфигурация gradle / maven / @) высмешиваем их, поэтому просто удалите все ссылки на зависимости сервлетов и повторите попытку

...