【问题标题】:Why do I keep getting 404's when using @AutoConfigureMockMvc in SpringBoot test?为什么在 SpringBoot 测试中使用 @AutoConfigureMockMvc 时总是出现 404?
【发布时间】:2019-07-17 10:48:51
【问题描述】:

我正在尝试使用 springrunner 编写集成测试。我将它作为 springboottest 运行并使用 autoconfiguremockmvc。但是,我不断收到 404。看来我的控制器/端点没有被 autoconfiguremockmvc 加载。有谁知道如何将其连接起来以便接上我的控制器的解决方案?

我确实在我的测试类中添加了一个基本控制器,并且我能够成功地点击它,但到目前为止我无法点击我想在我的集成测试中使用的实际控制器。

@RunWith(SpringRunner.class)
@SpringBootTest(classes = { TestConfig.class })
@TestPropertySource(locations = "classpath:application-test.properties")
@AutoConfigureMockMvc
public class ControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void test() throws Exception {

        MockHttpServletRequestBuilder request =
                MockMvcRequestBuilders.post(URL).contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)
                        .accept(MediaType.APPLICATION_JSON_UTF8_VALUE)
                        .content(json);

        final ResponseEntity<String> response =
                new ResponseEntity<>("works", HttpStatus.OK);

        final ResultActions result = this.mockMvc.perform(request).andDo(print());

        result.andExpect(status().isOk())
                .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE));
    }
}

@TestConfiguration
@EnableAutoConfiguration
public class TestConfig {

}

【问题讨论】:

  • @AutoConfigureMockMvc 顾名思义,仅用于配置MockMvc,它不会检测到任何其他内容。您的问题是您正在为测试使用单独的配置。您应该只使用 @SpringBootTest 注释并让它检测/加载您的完整应用程序,而不是测试配置。

标签: spring-boot integration-testing spring-boot-test mockmvc springrunner


【解决方案1】:

你可以使用

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)

RestAssured 库结合起来测试任何端点/api,如下所示

// include dependency in pom
<dependency>
        <groupId>io.rest-assured</groupId>
        <artifactId>rest-assured</artifactId>
        <version>3.0.5</version>
        <scope>test</scope>

</dependency>

//Test Class

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

//inject test local port
@LocalServerPort
private int port;

@Before
public void setUp() {
    //assign port for reset assured
    RestAssured.port = port;
}
@Test
public void test() {

    given()
            .get("/api")
            .then()
            .assertThat()
            .statusCode(HttpStatus.OK.value())
            .contentType(ContentType.JSON)
            .body("name", is("test"));
     }
 }

【讨论】:

  • 你能发布你的用例、控制器和测试吗?
猜你喜欢
  • 2021-05-01
  • 2019-02-04
  • 1970-01-01
  • 2019-10-03
  • 2016-04-06
  • 1970-01-01
  • 2019-11-02
  • 2019-05-12
  • 1970-01-01
相关资源
最近更新 更多