Spring MockMVC, Spring security and Mockito

前端 未结 1 1625
生来不讨喜
生来不讨喜 2021-02-19 17:15

I\'d like to test a Spring Boot Rest controller, which is secured using Spring security, and use mocks inside it. I have tried with Mockito, but I thin

1条回答
  •  佛祖请我去吃肉
    2021-02-19 17:27

    By default the integration looks for a bean with the name of "springSecurityFilterChain". In the example that was provided, a standalone setup is being used which means MockMvc will not be aware of the WebApplicationContext provided within the test and thus not be able to look up the "springSecurityFilterChain" bean.

    The easiest way to resolve this is to use something like this:

        MockMvc mockMvc = MockMvcBuilders
                // replace standaloneSetup with line below
                .webAppContextSetup(wac)
                .alwaysDo(print())
                .apply(SecurityMockMvcConfigurers.springSecurity())
                .build();
    

    If you really want to use a standaloneSetup (doesn't really make sense since you already have a WebApplicationContext), you can explicitly provide the springSecurityFilterChain using:

    @Autowired
    FilterChainProxy springSecurityFilterChain;
    
    @Before
    public void startMocks(){
        controller = wac.getBean(RecipesController.class);
    
        MockMvc mockMvc = MockMvcBuilders
                .standaloneSetup(controller)
                .alwaysDo(print())
                .apply(SecurityMockMvcConfigurers.springSecurity(springSecurityFilterChain))
                .build();
    
        MockitoAnnotations.initMocks(this);
    }
    

    0 讨论(0)
提交回复
热议问题