0

我的 Spring 应用程序中有以下方法

public static String getCurrentUserStudentId() {
    return ((LdapPerson) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getID();
}

这适用于应用程序运行,但是当我运行调用此方法的测试时,它给出

org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken cannot be cast to fi.utu.security.ldap.userdetails.LdapPerson

我不太熟悉 Spring Security 来提供所有可能相关的文件,但问我。我希望有人能告诉我该怎么做。

4

1 回答 1

0

SecurityContextHolder在静态变量中保留对“策略”的引用,这意味着该细节会从测试泄漏到测试。

你有几个选择:

  1. 在您的测试中,使用以下设置器之一设置正确的策略SecurityContextHolder

  2. 创建一个模拟实现,getCurrentUserStudentId为其返回一个固定的测试结果。

  3. 将获取当前用户 ID 的代码放入 bean 中,然后将其注入而不是调用SecurityContextHolder. 实现这个 bean 的两个版本:一个调用SecurityContextHolder,另一个返回一个字符串。

于 2013-08-21T11:46:01.607 回答