0

我正在尝试使用 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 {

}
4

1 回答 1

0

你可以使用

@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"));
     }
 }
于 2019-07-17T12:00:57.343 回答