Unterschied zwischen der Verwendung MockMvc mit SpringBootTest und Mit WebMvcTest

Ich bin neu in Spring Boot und versuche zu verstehen, wie testing arbeitet in SpringBoot. Ich bin ein bisschen verwirrt darüber, was ist der Unterschied zwischen folgenden zwei code-snippets:

Code-snippet 1:

@RunWith(SpringRunner.class)
@WebMvcTest(HelloController.class)
public class HelloControllerApplicationTest {
    @Autowired    
    private MockMvc mvc;

    @Test
    public void getHello() throws Exception {
        mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(content().string(equalTo("Greetings from Spring Boot!")));
    }
}

Dieser test verwendet die @WebMvcTest Anmerkung, die ich glaube, ist für feature-Scheibe-Tests und tests der Mvc-Schicht der Webanwendung.

Code-snippet 2:

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

    @Autowired
    private MockMvc mvc;

    @Test
    public void getHello() throws Exception {
    mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andExpect(content().string(equalTo("Greetings from Spring Boot!")));
    }
}

Dieser test verwendet die @SpringBootTest Kommentare und MockMvc. Also wie unterscheidet sich dies von code-snippet 1? Was macht diese anders machen?

Bearbeiten:
Hinzufügen von Code-Snippet 3 (Fand dies als ein Beispiel von integration-Tests in der Spring-Dokumentation)

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

@LocalServerPort
private int port;

private URL base;

@Autowired
private TestRestTemplate template;

@Before
public void setUp() throws Exception {
    this.base = new URL("http://localhost:" + port + "/");
}

@Test
public void getHello() throws Exception {
    ResponseEntity<String> response = template.getForEntity(base.toString(),
            String.class);
    assertThat(response.getBody(), equalTo("Greetings from Spring Boot!"));
}
}
InformationsquelleAutor Revansha | 2016-10-05
Schreibe einen Kommentar