liveBook · Manning

Spring MVC

As explained in Testing Spring Boot Applications

Spring MVC is Spring's servlet-based web application framework for handling HTTP requests and constructing web applications.

Spring MVC, also called Spring Web MVC or Spring Web, is Spring Boot’s usual servlet-based stack for web applications. Selecting Spring Web gives a Boot application an embedded Tomcat server to handle HTTP traffic and pass requests to application code. WebFlux is the alternative reactive stack, based on Netty. section 4.1 section 1.1

Testing MVC behavior need not mean starting Tomcat. The Spring Boot webmvc-test starter supplies test-only dependencies, while MockMvcTester provides an API for making requests and checking responses without that server’s startup cost and unrelated infrastructure. section 4.1 section 1.1

Listing 4.1 Basic MockMvcTester-based test
@SpringBootTest
@AutoConfigureMockMvc #1
class ApiTests {

  @Autowired MockMvcTester mvc; #1

  @Test
  void indexPageHasSelectedCity() {
    selectCity("Paris");

    var response = mvc.get() #2
      .uri("/") #3
      .exchange(); #4

    assertThat(response)
      .hasStatus(HttpStatus.OK) #5
      .bodyText().contains("Paris (France)"); #6
  }

}

The test configures MockMvcTester, sends a GET request to the index page, and checks both the HTTP status and rendered HTML. The selected city supplies a concrete value to look for in the response. section 4.1

Choose assertions to match the MVC endpoint:

  • For an HTML page, check its status and visible response text. section 4.1
  • For a JSON API, compare the response with expected JSON, extract a field, or convert it to Java objects for assertions. section 4.1
  • For a POST request, provide its content type and body, then check the returned status and body. section 4.1

The weather application illustrates both sides of an MVC interface: its index request returns rendered HTML, while later JavaScript interactions call HTTP APIs and consume JSON. Mocked weather-service responses keep those tests focused on the web behavior being checked. section 4.1

How Testing Spring Boot Applications covers it

How deep it goes
Explains the servlet server’s role and works through request assertions, stopping short of MVC dispatch internals.
Examples
Uses a weather application’s index page, JSON weather endpoint, and POST request to demonstrate response checks.
What it assumes
Assumes a Spring Boot web application and introduces the MVC test starter and request-testing setup.
What you can do after
Apply it via MockMvcTester to check MVC responses without starting embedded Tomcat.
How it connects
Connects Spring MVC to Tomcat, WebFlux, MockMvcTester, rendered HTML, and JSON APIs.

Also explained in

Compare how 4 books explain Spring MVC →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Testing Spring Boot Applications. The section links point to the parts of the book it draws on.