Getting Started with @WebMvcTest

Get familiar with the utilization of @WebMvcTest using an example.

We'll cover the following...

Create a test

We will begin by making an example @WebMvcTest.

Consider the following UserControllerTest class for the UserController that we have been working with:

Press + to interact
package com.tamingthymeleaf.application.user.web;
import com.tamingthymeleaf.application.user.UserService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Bean;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@WebMvcTest(UserController.class)
class UserControllerTest {
@Autowired
private MockMvc mockMvc; //<.>
@MockBean
private UserService userService; //<.>
@Test
void testGetUsersRedirectsToLoginWhenNotAuthenticated() throws Exception { //<.>
mockMvc.perform(get("/users")) //<.>
.andDo(print()) //<.>
.andExpect(status().is3xxRedirection()) //<.>
.andExpect(redirectedUrl("http://localhost/login")); //<.>
}
@TestConfiguration
static class TestConfig { //<.>
@Bean
public PasswordEncoder passwordEncoder() { //<.>
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
}
}
  • Annotate the test class with @WebMvcTest so the testing infrastructure will start. We indicate what controller we want to test by adding the class name of our UserController class name as ...