Mastering Spring 5.0
上QQ阅读APP看书,第一时间看更新

Setting up the Controller to test

The controller we want to test is BasicController. The convention to create a unit test is a class name with a suffix Test. 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();
}
}

A few important things to note are as follows:

  • 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 configured controller(s), BasicController in this instance.