Spring Boot 2.1 - 没有 Spring Security 自动配置的 @WebMvcTest [英] Spring Boot 2.1 - @WebMvcTest without Spring Security Auto-Configuration

查看:37
本文介绍了Spring Boot 2.1 - 没有 Spring Security 自动配置的 @WebMvcTest的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在迁移到 Spring Boot 2.1 之前,我们使用 @WebMvcTest 结合 @AutoConfigureMockMvc 在我们的服务中进行了几个控制器测试:

Before migrating to Spring Boot 2.1, we had a couple of controller tests in our services utilizing @WebMvcTest in combination with @AutoConfigureMockMvc:

@WebMvcTest(SomeController.class)
@AutoConfigureMockMvc(secure = false)
public class SomeControllerTests { ... }

这会导致 Spring Security 配置被禁用,您可以在不模拟 OAuth/JWT 的情况下运行 MVC 测试.

This had the effect that the Spring Security configuration was disabled and you could run MVC tests without mocking OAuth/JWT.

在 Spring Boot 2.1 中,secured 属性已被弃用,发行说明中提到

In Spring Boot 2.1, the secured attribute is deprecated and the release notes mention that

[...] @WebMvcTest 查找 WebSecurityConfigurer bean [...].

[...] @WebMvcTest looks for a WebSecurityConfigurer bean [...].

为了避免不推荐使用的 secured 属性和加载我们的 WebSecurityConfigurer,我们将测试重写为:

In order to avoid the deprecated secured attribute and loading of our WebSecurityConfigurer we rewrote our tests to:

@WebMvcTest(
    value = SomeController.class,
    excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = WebSecurityConfigurer.class),
    excludeAutoConfiguration = MockMvcSecurityAutoConfiguration.class)
public class SomeControllerTests { ... }

问题是:Spring Boot 2.1 中是否有更紧凑的方式来定义此类测试?

The question is: is there a more compact way in Spring Boot 2.1 to define such tests?

推荐答案

是的,与其解决该标志已被弃用的事实,您应该接受这样一个事实,即这将朝着这个方向前进.

Yes, rather than working around the fact the flag is deprecated, you should embrace the fact that this is going in that direction going forward.

从 Spring Boot 2.1 开始,如果您有 Spring Security,您的测试将使用您的自定义配置进行保护.这样做的实际问题是什么?

As of Spring Boot 2.1, if you have Spring Security, your tests will be secured using your custom configuration. What is the actual problem with that?

如果您不想对某些测试进行身份验证,只需使用 Spring Security 的测试基础架构并添加 @WithMockUser.

If you don't want to authenticate for certain tests, just use Spring Security's test infrastructure and add @WithMockUser.

这篇关于Spring Boot 2.1 - 没有 Spring Security 自动配置的 @WebMvcTest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆