相关疑难解决方法(0)

Spring Test为不安全的URL返回401

我正在使用Spring进行MVC测试

这是我的测试课

@RunWith(SpringRunner.class)
@WebMvcTest
public class ITIndexController {

    @Autowired
    WebApplicationContext context;

    MockMvc mockMvc;

    @MockBean
    UserRegistrationApplicationService userRegistrationApplicationService;

    @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")));
    }
}
Run Code Online (Sandbox Code Playgroud)

这是MVC配置

@Configuration
@EnableWebMvc
public class MvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/login/form").setViewName("login");
    }
}
Run Code Online (Sandbox Code Playgroud)

这是安全配置

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    @Qualifier("customUserDetailsService")
    UserDetailsService userDetailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception …
Run Code Online (Sandbox Code Playgroud)

java spring spring-mvc spring-test spring-boot

14
推荐指数
3
解决办法
8444
查看次数

标签 统计

java ×1

spring ×1

spring-boot ×1

spring-mvc ×1

spring-test ×1