Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何测试安全的弹簧控制器_Java_Spring_Spring Boot_Spring Security_Integration Testing - Fatal编程技术网

Java 如何测试安全的弹簧控制器

Java 如何测试安全的弹簧控制器,java,spring,spring-boot,spring-security,integration-testing,Java,Spring,Spring Boot,Spring Security,Integration Testing,我目前有一个用SpringBoot2、SpringMVC、SpringData/JPA和Thymeleaf构建的应用程序 我正在编写一些单元/集成测试,我想测试控制器,它由SpringSecurity保护,由注册用户的数据库支持 测试它的最佳方法是什么?我已经尝试过其中一些方法,例如使用注释,如@WithMockUser,但都没有成功 编辑:只是提醒一下,我不是在测试@RestControllers。我直接在测试类中注入一个@Controller,并调用它的方法。没有Spring安全性,它就可以

我目前有一个用SpringBoot2、SpringMVC、SpringData/JPA和Thymeleaf构建的应用程序

我正在编写一些单元/集成测试,我想测试控制器,它由SpringSecurity保护,由注册用户的数据库支持

测试它的最佳方法是什么?我已经尝试过其中一些方法,例如使用注释,如
@WithMockUser
,但都没有成功

编辑:只是提醒一下,我不是在测试
@RestController
s。我直接在测试类中注入一个
@Controller
,并调用它的方法。没有Spring安全性,它就可以正常工作

一个例子:

@Controller
public class SecuredController {
  @GetMapping("/")
  public String index() {
    return "index";
  }
}
/
路径由Spring Security保护,通常会重定向到
/login
以验证用户

我的单元测试如下所示:

@WebMvcTest(controllers = SecuredController.class)
class SecuredControllerTest {

  @Autowired
  private SecuredController controller;

  @Autowired
  private MockMvc mockMvc;

  @Test
  @WithMockUser(username = "user", password = "pass", roles = {"USER"})
  public void testAuthenticatedIndex() throws Exception {
    mockMvc.perform(get("/"))
        .andExpect(status().isOk())
        .andDo(print());
  }
}
我遇到的第一个错误是,要求我注入UserDetailsService实现,这是我希望避免的。但是如果我确实注入了服务,测试会工作,但返回404而不是200


有什么想法吗?

在测试课上,使用注释

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
安装测试方法

@Before
@WithMockUser("spring")
@Test
实际测试方法

@Before
@WithMockUser("spring")
@Test
像这些例子一样测试Spring安全性


您需要通过导入
websecurityConfigureAdapter
类将安全配置添加到Spring上下文中

@WebMvcTest(controllers=SecuredController.class)
@导入(SecuredControllerTest.Config.class)
类SecuredControllerTest{
@配置
@启用Web安全性
静态类配置扩展MyWebSecurity配置适配器{
@自动连线
public void configureGlobal(AuthenticationManagerBuilder auth)引发异常{
auth.inMemoryAuthentication().withUser(“用户”).password(“pa$$”).roles(“用户”);
auth.inMemoryAuthentication().withUser(“admin”).password(“pa$$”).roles(“admin”);
}
}
...
}

嵌入的
静态类配置
只是为了改变用户的来源,在这种情况下,在内存中进行
身份验证
就足够了。

我不确定它是否有帮助,但你可以看一看,这个答案确实有助于测试
@RestController
,我正在直接测试
@Controller
,不是通过
restemplate
调用它们,而是直接将它们注入测试类并调用它们的方法。你能分享一些代码片段吗?@sandiee我添加了一些代码片段。希望有帮助。我正在使用
websecurityConfigureAdapter
进行配置。但是它从数据库加载用户,我想以某种方式模拟一下。我是否应该创建一个新的
websecurityConfigureAdapter
实现来进行测试?