Spring Boot WebFlux测试未找到MockMvc

时间:2018-08-13 14:06:29

标签: spring spring-mvc spring-boot spring-webflux spring-boot-test

问题

我正在尝试运行一个简单的spring boot测试,但出现错误提示它在运行时无法MockMvc。文档表明我使用了正确的注释,并使用start.spring.io创建了pom.xml。不确定为什么会有问题。

错误:

 No qualifying bean of type 'org.springframework.test.web.servlet.MockMvc'

测试代码

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class MyWebApplicationTests {

    @Autowired
    MockMvc mockMvc;

    @Test
    public void Can_Do_Something() throws Exception {
        mockMvc.perform(get("/hello-world")).andDo(print()).andExpect(status().isOk())
                .andExpect(content().string(containsString("Hello World")));
    }

}

文档:

我正在使用此文档作为参考-> https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html#boot-features-testing-spring-boot-applications-testing-with-mock-environment

POM.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.mywebapp</groupId>
    <artifactId>webapp</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>my-webapp</name>
    <description>Backend application</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.0.M1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>10</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </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>
            <version>3.0.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.el</groupId>
            <artifactId>javax.el-api</artifactId>
            <version>3.0.0</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.web</groupId>
            <artifactId>javax.el</artifactId>
            <version>2.2.6</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </pluginRepository>
        <pluginRepository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>


</project>

2 个答案:

答案 0 :(得分:0)

正如M. Deinum所指出的那样,Spring Boot中没有为WebFlux配置加载MockMvc。您需要使用 WebTestClient 。因此,将AutoConfigureMockMvc替换为 AutoConfigureWebTestClient ,并使用webTestClient方法代替。

要注意的一件事是,这是在幕后进行实际的Web调用,并将启动服务器。 MockMVC不会启动服务器。 What is the difference between MockMvc and WebTestClient?

答案 1 :(得分:0)

当人们在切换到Spring WebFlux后尝试测试其端点时,这个问题似乎出现在搜索列表的顶部,因此我将在此处添加确定的内容。 (应该指出的是,过去我很难使WebTestClient与带有注释的RestController的端点一起起作用。但是此代码有效。我认为我缺少一个依赖项,并且不是清除。)

MyService.java

@Service
public class MyService {
     public String doSomething(String input) {
         return input + " implementation";
     }
}

MyController.java

@RestController
@RequestMapping(value = "/api/v1/my")
public class MyController {
    @Autowired
    private MyService myService;

    @RequestMapping(value = "", method = RequestMethod.POST, consumes = {APPLICATION_JSON_VALUE})
    public ResponseEntity<Mono<String>> processPost(@RequestBody String input)
    {
        String response = myService.doSomething(input);
        return ResponseEntity.ok(Mono.just(response));
    }

TestMyController.java

@ExtendWith(SpringExtension.class)
@WebFluxTest(MyController.class)
public class TestMyController {
    @Autowired
    private WebTestClient webTestClient;

    @MockBean
    private MyService myService;

    @Test
    public void testPost() throws Exception {
          // Setup the Mock MyService. Note the 'mocked' vs 'implementation' 
          when(myService.doSomething(anyString())).thenAnswer((Answer<String>) invocation -> {
               String input = invocation.getArgument(0);
               return input + " mocked";
          });

          String response = webTestClient.post()
                .uri("/api/v1/my")
                .body(BodyInserters.fromObject("is"))
                .accept(MediaType.APPLICATION_JSON)
                .exchange()
                .expectStatus().isOk()
                .returnResult(String.class)
                .getResponseBody()
                .blockFirst();
          assertThat(response).matches("is mocked");
    }
}

可能导致难以诊断的问题的依赖项似乎来自reactor-test。因此,如果WebTestClient无法正常工作,请确保存在依赖性。

pom.xml

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-webflux</artifactId>
        <version>2.1.5.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <version>2.1.5.RELEASE</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>io.projectreactor</groupId>
        <artifactId>reactor-test</artifactId>
        <version>3.2.9.RELEASE</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <artifactId>jackson-module-kotlin</artifactId>
                <groupId>com.fasterxml.jackson.module</groupId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter</artifactId>
        <version>5.4.2</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.google.truth</groupId>
        <artifactId>truth</artifactId>
        <version>0.45</version>
        <scope>test</scope>
    </dependency>
相关问题