The controller we want to test is BasicController. The convention to create a unit test is a class name with the Test suffix . We will create a test class named BasicControllerTest.
The basic setup is shown as follows:
public class BasicControllerTest {
private MockMvc mockMvc;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.standaloneSetup(new BasicController()).build();
}
}
The following definitions explain the workings of the preceding code block:
- mockMvc: This variable can be used across different tests. So, we define an instance variable of the MockMvc class.
- @Before setup: This method is run before every test in order to initialize MockMvc.
- MockMvcBuilders.standaloneSetup(new BasicController()).build(): This line of code builds a MockMvc instance. It initializes DispatcherServlet to serve requests to the controller(s) configured, BasicController, in this instance.