Imr*_*ran 4 java rest spring mockmvc
我有一个spring rest mvc控制器,它有url"/ public/rest/vehicle/get".在我的安全配置中,我已经定义了对/ public/rest的任何请求都不应该要求身份验证.
http.
csrf().disable()
.authorizeRequests()
.antMatchers("/home/**", "/**", "/css/**", "/js/**", "/fonts/**", "/images/**", "/public/rest/**","/login*","/signin/**","/signup/**").permitAll()
.antMatchers("/property/**").authenticated()
.and()
.formLogin().loginPage("/login").permitAll()
.and().httpBasic().disable();
Run Code Online (Sandbox Code Playgroud)
当我启动我的应用程序并使用浏览器或任何其他方式提交请求时,此配置正常工作.现在,我有一个看起来像这样的测试类,
@RunWith(SpringRunner.class)
@WebMvcTest(VehicleController.class)
public class VehicleControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private VehicleService vehicleService;
@Test
public void getVehicle() throws Exception {
given(this.vehicleService.get(0)).
willReturn(new VehicleEquipmentDTO());
this.mockMvc.perform(get("/public/rest/vehicle/get").param("id","0"))
.andDo(print())
.andExpect(status().isOk());//.andExpect(content().string("Honda Civic"));
}}
Run Code Online (Sandbox Code Playgroud)
现在,当我运行这个测试时,它说
java.lang.AssertionError: Status
Expected :200
Actual :401
Run Code Online (Sandbox Code Playgroud)
当我打印请求响应时,我发现它因为安全性而抱怨."错误消息=访问此资源需要完全身份验证" 任何想法,为什么它不使用我的安全配置,以及强制它使用正确配置的工作是什么?提前致谢
终于找到了原因.由于WebMvcTest只是切片测试,因此不需要安全配置.解决方法是明确导入它,如,
@Import(WebSecurityConfig.class)
Run Code Online (Sandbox Code Playgroud)
这解决了我同样的问题
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class ClientResourceControllerTest {
Run Code Online (Sandbox Code Playgroud)
小智 5
我遇到了同样的问题,搜索了一段时间后,发现了以下解决方案。
因为,您已在应用程序中启用了Spring Security以及其他批注,所以可以像这样secure=false在@AutoConfigureMockMvc批注中指定参数:
@AutoConfigureMockMvc(secure=false)
public class YourControllerTest {
//All your test methods here
}
Run Code Online (Sandbox Code Playgroud)
说明:要禁用Spring Security自动配置,我们可以使用MockMvc实例通过以下方式禁用安全性:@AutoConfigureMockMvc(secure=false)
| 归档时间: |
|
| 查看次数: |
3746 次 |
| 最近记录: |