问题描述
我正在使用Spring进行MVC测试
I am using Spring for MVC tests
这是我的考试班
@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")));
}
}
这是MVC配置
@Configuration
@EnableWebMvc
public class MvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
registry.addViewController("/login/form").setViewName("login");
}
}
这是安全配置
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
@Qualifier("customUserDetailsService")
UserDetailsService userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/resources/**", "/signup", "/signup/form", "/").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login/form").permitAll().loginProcessingUrl("/login").permitAll()
.and()
.logout().logoutSuccessUrl("/login/form?logout").permitAll()
.and()
.csrf().disable();
}
@Autowired
public void configureGlobalFromDatabase(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
}
我运行测试时失败,并显示以下消息:
When I run my test it fails with the message:
java.lang.AssertionError: Status expected:<200> but was:<401>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:54)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:81)
at org.springframework.test.web.servlet.result.StatusResultMatchers$10.match(StatusResultMatchers.java:664)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:171)
at com.marco.nutri.integration.web.controller.ITIndexController.should_render_index(ITIndexController.java:46)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
我知道由于URL受spring安全性保护而失败,但是当我运行我的应用程序时,即使未经身份验证也可以访问该URL.
I understand that it fails due to the fact that the url is protected with spring security, but when I run my application I can access that url even without being authenticated.
我做错什么了吗?
推荐答案
我找到了答案
Spring文档说:
I found the answer
Spring docs says that:
根据github中的这个问题:
And according to this issue in github:
https://github.com/spring-projects/spring-boot/问题/5476
如果类路径中存在spring-security-test,则默认情况下,@ WebMvcTest自动配置spring安全性.
The @WebMvcTest by default auto configure spring security if spring-security-test is present in the class path (which in my case is).
因此,由于未选择WebSecurityConfigurer类,因此默认安全性是自动配置的,这就是我收到url中的401的动机,而该问题在我的安全性配置中未得到保护. Spring安全性默认的自动配置通过基本身份验证来保护所有url.
So since WebSecurityConfigurer classes aren't picked, the default security was being auto configured, that is the motive I was receiving the 401 in url's that was not secured in my security configuration. Spring security default auto configuration protects all url's with basic authentication.
我要解决的问题是使用@ContextConfiguration注释类,并在文档中对@MockBean进行注释:
What I did to solve the problem was to annotate the class with @ContextConfiguration, and @MockBean like it is described in the documentation:
这是测试班
@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")));
}
}
应用程序,MvcConfig和SecurityConfig都是我的配置类
Application, MvcConfig and SecurityConfig are all my configuration classes
这篇关于Spring Test返回不安全URL的401的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!