在 Spring MVC Test 中以用户身份运行测试

通常需要以特定用户身份运行测试。有两种简单的方法可以填充用户。

在 Spring MVC Test 中使用 RequestPostProcessor 以用户身份运行

您有多种选项可以将用户与当前的 HttpServletRequest 关联起来。以下示例以用户身份运行(该用户无需存在),其用户名为 user,密码为 password,角色为 ROLE_USER

  • Java

  • Kotlin

mvc
	.perform(get("/").with(user("user")))
mvc.get("/") {
    with(user("user"))
}

该支持通过将用户与 HttpServletRequest 关联来实现。要将请求与 SecurityContextHolder 关联,您需要确保 SecurityContextPersistenceFilterMockMvc 实例关联。您可以通过多种方式实现:

  • 调用 apply(springSecurity())

  • 将 Spring Security 的 FilterChainProxy 添加到 MockMvc

  • 当使用 MockMvcBuilders.standaloneSetup 时,手动将 SecurityContextPersistenceFilter 添加到 MockMvc 实例可能是有意义的。

您可以轻松进行自定义。例如,以下将以用户身份运行(该用户无需存在),用户名为 "admin",密码为 "pass",角色为 "ROLE_USER" 和 "ROLE_ADMIN"。

  • Java

  • Kotlin

mvc
	.perform(get("/admin").with(user("admin").password("pass").roles("USER","ADMIN")))
mvc.get("/admin") {
    with(user("admin").password("pass").roles("USER","ADMIN"))
}

如果您想使用自定义的 UserDetails,也可以轻松指定。例如,以下将使用指定的 UserDetails(该用户无需存在)来运行一个 UsernamePasswordAuthenticationToken,其 principal 为指定的 UserDetails

  • Java

  • Kotlin

mvc
	.perform(get("/").with(user(userDetails)))
mvc.get("/") {
    with(user(userDetails))
}

您可以使用以下方式以匿名用户身份运行:

  • Java

  • Kotlin

mvc
	.perform(get("/").with(anonymous()))
mvc.get("/") {
    with(anonymous())
}

如果您正在使用默认用户并希望以匿名用户身份处理一些请求,这尤其有用。

如果您想要自定义的 Authentication(无需存在),可以使用以下方式:

  • Java

  • Kotlin

mvc
	.perform(get("/").with(authentication(authentication)))
mvc.get("/") {
    with(authentication(authentication))
}

您甚至可以使用以下方式自定义 SecurityContext

  • Java

  • Kotlin

mvc
	.perform(get("/").with(securityContext(securityContext)))
mvc.get("/") {
    with(securityContext(securityContext))
}

我们还可以通过使用 MockMvcBuilders 的默认请求来确保为每个请求以特定用户身份运行。例如,以下将以用户身份运行(该用户无需存在),用户名为 "admin",密码为 "password",角色为 "ROLE_ADMIN"。

  • Java

  • Kotlin

mvc = MockMvcBuilders
		.webAppContextSetup(context)
		.defaultRequest(get("/").with(user("user").roles("ADMIN")))
		.apply(springSecurity())
		.build();
mvc = MockMvcBuilders
    .webAppContextSetup(context)
    .defaultRequest<DefaultMockMvcBuilder>(get("/").with(user("user").roles("ADMIN")))
    .apply<DefaultMockMvcBuilder>(springSecurity())
    .build()

如果您发现在许多测试中都使用相同的用户,建议将用户移至一个方法中。例如,您可以在自己的名为 CustomSecurityMockMvcRequestPostProcessors 的类中指定以下内容:

  • Java

  • Kotlin

public static RequestPostProcessor rob() {
	return user("rob").roles("ADMIN");
}
fun rob(): RequestPostProcessor {
    return user("rob").roles("ADMIN")
}

现在您可以对 CustomSecurityMockMvcRequestPostProcessors 进行静态导入并在测试中使用它。

  • Java

  • Kotlin

import static sample.CustomSecurityMockMvcRequestPostProcessors.*;

...

mvc
	.perform(get("/").with(rob()))
import sample.CustomSecurityMockMvcRequestPostProcessors.*

//...

mvc.get("/") {
    with(rob())
}

在 Spring MVC Test 中使用注解以用户身份运行

作为使用 RequestPostProcessor 创建用户的替代方法,您可以使用 测试方法安全性 中描述的注解。例如,以下将以用户名为 "user",密码为 "password",角色为 "ROLE_USER" 的用户身份运行测试。

  • Java

  • Kotlin

@Test
@WithMockUser
public void requestProtectedUrlWithUser() throws Exception {
mvc
		.perform(get("/"))
		...
}
@Test
@WithMockUser
fun requestProtectedUrlWithUser() {
    mvc
        .get("/")
        // ...
}

或者,以下将以用户名为 "user",密码为 "password",角色为 "ROLE_ADMIN" 的用户身份运行测试。

  • Java

  • Kotlin

@Test
@WithMockUser(roles="ADMIN")
public void requestProtectedUrlWithUser() throws Exception {
mvc
		.perform(get("/"))
		...
}
@Test
@WithMockUser(roles = ["ADMIN"])
fun requestProtectedUrlWithUser() {
    mvc
        .get("/")
        // ...
}
© . This site is unofficial and not affiliated with VMware.