title: How to test a controller with constructor injection by MockMvc
body: <p>I have a controller with constructor injection</p>
  
  <pre><code>@RestController
  @RequestMapping("/user")
  public class MainController {
  
      private final UserMapper userMapper; // autowired by constructor below
  
      public MainController(UserMapper userMapper) {
          this.userMapper = userMapper;
      }
  
      @RequestMapping("/getChannels")
      public String index() {
          LoginUser user = userMapper.getUserByName("admin");
          return "Channels: " + user.getChannels();
      }
  }
  </code></pre>
  
  <p>It's a simple class which is working fine. However when I tried to run a JUnit testing with below class I got an error.</p>
  
  <pre><code>@RunWith(SpringJUnit4ClassRunner.class)
  @WebAppConfiguration
  public class MainControllerTest {
  
      private MockMvc mvc;
      private final UserMapper userMapper;
  
      public MainControllerTest(UserMapper userMapper) {
          this.userMapper = userMapper;
      }
  
      @Before
      public void setUp() throws Exception {
          mvc = MockMvcBuilders.standaloneSetup(new MainController(userMapper)).build();
      }
  
      ......
  </code></pre>
  
  <p>The error is: </p>
  
  <pre><code>java.lang.Exception: Test class should have exactly one public zero-argument constructor
  </code></pre>
  
  <p>I was confused by above error message that how could I inject the userMapper with a zero-argument constructor?
  I know it's possible to add the @Autowired for userMapper in MainController however the field injection is not recommended.
  Please could anybody guide me a suitable way for both constructor injection and MockMvc testing. Thanks.</p>