我发现
Spring文档说的答案是:
@WebMvcTest将自动配置Spring MVC基础结构,并将扫描的bean限制为@ Controller,@ ControllerAdvice,@
JsonComponent,Filter,WebMvcConfigurer和HandlerMethodArgumentResolver。使用此注释时,不会扫描常规@Component
bean。
并根据github中的这个问题:
https://github.com/spring-projects/spring-
boot/issues/5476
如果在类路径中存在spring-security-test(在我的情况下),默认情况下,@WebMvcTest自动配置spring安全性。
因此,由于未选择WebSecurityConfigurer类,因此默认安全性是自动配置的,这就是我收到url中的401的动机,而该问题在我的安全性配置中未得到保护。Spring
Security默认的自动配置通过基本身份验证来保护所有url。
我要解决的问题是用@ContextConfiguration注释类,而@MockBean像在文档中进行了描述:
通常,@ WebMvcTest将限于单个控制器,并与@MockBean结合使用,以为所需的协作者提供模拟实现。
这是测试课
@RunWith(SpringRunner.class)@WebMvcTest@ContextConfiguration(classes={Application.class, MvcConfig.class, SecurityConfig.class})public class ITIndex { @Autowired WebApplicationContext context; MockMvc mockMvc; @MockBean UserRegistrationApplicationService userRegistrationApplicationService; @MockBean UserDetailsService userDetailsService; @Before public void setUp() { this.mockMvc = MockMvcBuilders .webAppContextSetup(context) .apply(springSecurity()) .build(); } @Test public void should_render_index() throws Exception { mockMvc.perform(get("/")) .andExpect(status().isOk()) .andExpect(view().name("index")) .andExpect(content().string(containsString("Login"))); }}Application,MvcConfig和SecurityConfig都是我的配置类



