Springboot MockMvc 中的单元测试用例返回 403 Forbidden

问题描述 投票:0回答:1

我为 Post api 的控制器编写了单元测试用例。但测试用例失败了。作为参考,我已经放了 输出日志详细信息。所以请任何人帮助我,我哪里出错了。 这是 PDFTaggerController 的 api。这里@RequestPart FileContent是pdf文档.

@RequestMapping(value = "/v1/getFillableFormElements", method = RequestMethod.POST)
    public @ResponseBody HttpEntity getFillableFormElements(@RequestPart("FileContent") @Valid 
    MultipartFile FileContent, @RequestParam int pageNo) throws IOException {
    FormElementsService formElementsService = new 
     FormElementsServiceImpl();         
  formElementsService .process(pdfFilePath,returnFilePath);
            return setReturnHttpHeaders(returnFilePath);
}

上述测试用例

@WebMvcTest
@ContextConfiguration(classes = PDFTaggerController.class) 
public class PDFTaggerControllerTests {
    @MockBean
    PDFTaggerController controller;
    @Autowired
    private MockMvc mockMvc;
    @Autowired
    private WebApplicationContext webApplicationContext;

    @Before()
    public void setup()
    {
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }
    
    @Test
    public void getFillableFormElements() throws Exception {
        File file = new File("C:\\Downloads\\sample.pdf");
        FileInputStream fileInputStream = new FileInputStream(file);
        MockMultipartFile firstFile = new MockMultipartFile("file", file.getName(), 
        "multipart/.pdf", fileInputStream);
        
        doNothing().when(retrieveFillableFormElementsService).process(anyString(), anyString());             
        mockMvc.perform(MockMvcRequestBuilders.multipart("/api/v1/getFillableFormElements")
                 .file(firstFile)
                 .param("pageNo", "0"))
                 .andExpect(status().isOk());
    }
}

这是测试的输出

MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /api/v1/getFillableFormElements
       Parameters = {pageNo=[0]}
          Headers = [Content-Type:"multipart/form-data;charset=UTF-8"]
             Body = null
    Session Attrs = {org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository.CSRF_TOKEN=org.springframework.security.web.csrf.DefaultCsrfToken@5d08976a}

Handler:
             Type = null

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 403
    Error message = Forbidden
          Headers = [X-Content-Type-Options:"nosniff", X-XSS-Protection:"1; mode=block", Cache-Control:"no-cache, no-store, max-age=0, must-revalidate", Pragma:"no-cache", Expires:"0", X-Frame-Options:"DENY"]
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

Spring 安全配置

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private AuthenticationEntryPoint authenticationEntryPoint;
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/api/v1/status");
    }
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().
        authorizeRequests().antMatchers("*").permitAll()
        .antMatchers("/pingnot").anonymous()
        .antMatchers("/**").authenticated().and().exceptionHandling().and().httpBasic()
        .authenticationEntryPoint(authenticationEntryPoint).and().sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.authorizeRequests().antMatchers("/swagger-ui.html").authenticated().and()
        .formLogin().permitAll().and()
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED);
        http.addFilterBefore(new BasicAuthenticationFilter(authenticationManager()), BasicAuthenticationFilter.class);
    }
spring-boot unit-testing junit4 junit5
1个回答
0
投票

请提供身份验证详细信息,可以是令牌或cookie。

mockMvc.perform(MockMvcRequestBuilders.multipart("/api/v1/getFillableFormElements")
                 .file(firstFile)
                 .param("pageNo", "0")
                 .header("Authorization", "Bearer " + token)) // Add token as header
                 .andExpect(status().isOk());

您可以禁用测试授权

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private AuthenticationEntryPoint authenticationEntryPoint;
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
            .authorizeRequests()
                .antMatchers("/api/v1/status").permitAll()
                .antMatchers("/api/v1/getFillableFormElements").permitAll() // Permit access to this endpoint
                .anyRequest().authenticated()
                .and()
            .httpBasic()
                .authenticationEntryPoint(authenticationEntryPoint)
                .and()
            .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.