使用依赖于Spring Security的JUnit测试Spring Controller

Jos*_*des 4 java junit spring spring-mvc spring-security

我有一个Spring应用程序,我正在构建JUnit测试来测试某个Controller.

问题是Controller我在里面调用这段代码:

final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
final String userName = authentication.getName();
Run Code Online (Sandbox Code Playgroud)

换句话说,我需要在调用之前进行身份验证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"));
        }
Run Code Online (Sandbox Code Playgroud)

当我跑的时候给了我一个NullPointerException权利,final String userName = authentication.getName();因为我authenticationnull因为我没有登录.

问题是:有没有办法模拟身份验证?欢迎所有想法.

谢谢.

hol*_*s83 5

Spring Security版本4对此进行了一些改进.

首先确保你在测试的类路径中有测试框架,Maven看起来像:

<dependency>
  <groupId>org.springframework.security</groupId>
  <artifactId>spring-security-test</artifactId>
  <version>4.0.4.RELEASE</version>
  <scope>test</scope>
</dependency>
Run Code Online (Sandbox Code Playgroud)

有用的进口:

import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.*;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.*;
Run Code Online (Sandbox Code Playgroud)

测试设置:

mockMvc = webAppContextSetup(applicationContext).apply(springSecurity()).build();
Run Code Online (Sandbox Code Playgroud)

(我认为您需要WebApplicationContext而不是单个控制器.)

然后测试类似于:

mockMvc.perform(get(...).with(user("username").roles("USER"))).andExpect(...);
Run Code Online (Sandbox Code Playgroud)