How to configure HandlerMethodArgumentResolver in spring boot test

Viewed 4313

I am writing a unit for a controller with spting boot @WebMvcTest.

Using @WebMvcTest, I will be able to inject a MockMvc object as given below :-

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {TestConfig.class})
@WebMvcTest
class MyControllerTest {
    @Autowired
    private MockMvc mockMvc;

    @Test
    public void my_controller_test() throws Exception {
       mockMvc.perform(post("/create-user"))
              .andExpect(status().isCreated());
    }
}

In the controller I am injecting a Principal argument using spring HandlerMethodArgumentResolver. Please inform me how can I write a unit test with MockMvc , so that I can inject a mock Principal object as the argument in the controller method.

The sction Auto-configured Spring MVC tests explains that the Test annotated with @WebMvcTest will scan beans of HandlerMethodArgumentResolver. So I created a bean which extends HandlerMethodArgumentResolver and return the mock Principal object as below .

@Component
public class MockPrincipalArgumentResolver implements HandlerMethodArgumentResolver {
   @Override
   public boolean supportsParameter(MethodParameter parameter) {
     return parameter.getParameterType().equals(Principal.class);
   }

   @Override
   public Object resolveArgument(MethodParameter parameter...) throws Exception {
     return new MockPrincipal();
   }
 }

But still the Argument MockPrincipal is not getting passed to controller method.

Spring boot version :- 1.4.5.RELEASE

1 Answers
Related