【发布时间】:2016-04-21 19:40:41
【问题描述】:
我有一个 Spring 应用程序,我正在构建 JUnit 测试来测试某个 Controller。
问题是在Controller里面我调用了这个代码:
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
final String userName = authentication.getName();
换句话说,我需要在调用此Controller 之前进行身份验证。我用这段代码写了一个JUnit 测试:
private MockMvc mockMvc;
@Test
public void getPageTest() throws Exception{
final ProcessFileController controller = new ProcessFileController();
mockMvc = standaloneSetup(controller).build();
mockMvc.perform(get(URI.create("/processFile.html")).sessionAttr("freeTrialEmailAddress", "")).andExpect(view().name("processFile"));
}
当我运行它时,它会在final String userName = authentication.getName(); 上给我一个NullPointerException,因为我的authentication 是null,因为我没有登录。
问题是:有没有办法模拟身份验证?欢迎所有想法。
谢谢。
【问题讨论】:
-
你为什么要手动而不是使用
@AuthenticationPrincipal? -
chrylis,该架构不是为使用
@AuthenticationPrincipal而设计的,我需要一个想法,一种方法来处理我现在拥有的当前架构。谢谢你的回答。
标签: java spring spring-mvc junit spring-security