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 {@Autowiredprivate MockMvc mockMvc; //<.>@MockBeanprivate UserService userService; //<.>@Testvoid testGetUsersRedirectsToLoginWhenNotAuthenticated() throws Exception { //<.>mockMvc.perform(get("/users")) //<.>.andDo(print()) //<.>.andExpect(status().is3xxRedirection()) //<.>.andExpect(redirectedUrl("http://localhost/login")); //<.>}@TestConfigurationstatic class TestConfig { //<.>@Beanpublic 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 ourUserController
class name as ...