spring boot testing: Zero to Hero

Abstract

@SpringBootTest and web testing

  • @SpringBootTest to start up your spring boot application in your tests.
  • You can inject MockMvc in your test fields or as your test method argument:
@SpringBootTest
class TodoMockMvcTest {
  // here
  @Autowired
  MockMvc mvc;
  
  @Test
  void testTodo(@Autowired MockMvc mvc) { // or here
  }
}

You can use a mocked web server (which is the default):

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
@AutoConfigureMockMvc
class TodoMockMvcTest {}

HtlmUnit

You can use HtmlUnit to test simple HTML page:

import org.htlmunit.WebClient;
 
@SpringBootTest
@AutoConfigureMockMvc
class TodoMockMvcTest {
  @Autowired
  WebClient webClient; // This is not WebFlux WebClient
 
  @Test
  void addTodos() {
    HtmlPage page = webClient.getPage("/");
    HtmlInput text = page.querySelector("#new-todo");
    HtmlButton addTodoButton = page.querySelector("#add-todo");
    text.type("Hello, world");
 
    page = addTodoButton.click();
    // ...
  }
}