如何在控制器单元测试中禁用安全性?

时间:2018-08-13 11:57:53

标签: unit-testing spring-boot spring-security spring-test-mvc

我尝试禁用控制器单元测试的安全性,但始终出现错误403。

我的单元测试:

@RunWith(SpringRunner.class)
@WebMvcTest(value = MeasureController.class, secure = false)
@AutoConfigureMockMvc(secure = false)
public class MeasureControllerTest {

    @Autowired
    private MockMvc mvc;
    @Autowired
    private ObjectMapper objectMapper;
    @MockBean
    private ObjectService objectService;
    @Autowired
    private MeasureController measureController;

    /**
     * Test of sayHello method, of class MeasureController.
     *
     * @throws java.lang.Exception
     */
    @Test
    public void OnPostShouldReturnCreatedStatusIfEmptyMeasure() throws Exception {
        final String url = "/object/" + uuidKey + "/measures/";
        this.mvc.perform(post(url)
                .content("[]")
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isCreated());

        verifyZeroInteractions(objectService);
    }
}

安全配置:

@Configuration
@EnableResourceServer
public class SecurityResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and().authorizeRequests()
                .antMatchers("/v2/api-docs", "/swagger-resources/**", "/swagger-ui.html", "/webjars/**").permitAll()
                .anyRequest().authenticated()
                ;
    }

    @Primary
    @Bean
    public RemoteTokenServices tokenServices() {
        final RemoteTokenServices tokenService = new RemoteTokenServices();
        tokenService.setCheckTokenEndpointUrl("https://..../oauth/check_token");
        tokenService.setClientId(".....");
        tokenService.setClientSecret(".....");
        return tokenService;
    }
}

spring文档说将AutoConfigureMockMvc.secure设置为false或将WebMvcTest.secure设置为false。但是两者都不能禁用安全性。我有事吗?

我使用Spring Boot 2.0.4。和spring-security-oauth2 2.3.3。发布

2 个答案:

答案 0 :(得分:0)

“ WebMvcTest.secure”已被弃用。您必须进行控制器测试:

@RunWith(SpringRunner.class)
@WebMvcTest(value = PatientDeviceController.class, excludeAutoConfiguration = SecurityAutoConfiguration.class)
@AutoConfigureMockMvc(secure = false)

答案 1 :(得分:0)

对于其他来这里寻找答案(以及我未来的自我)的人,在Spring Boot 2.2中进行了测试:

Shape shape = new Triangle(50f, 50f);
float areaOfTri = shape.area(); // dispatches to Triangle.area()

shape = new Rectangle(50f, 50f);
float areaOfQuad = shape.area(); // dispatches to Rectangle.area()