名称为的模拟身份验证

scyqe7ek  于 2021-07-03  发布在  Java
关注(0)|答案(2)|浏览(334)

我正在测试我的spring mvc应用程序。要求是模仿 SecurityContext ,但我需要 Authentication 具有某个名称,不为空。有什么办法吗?
这是我的密码:

Authentication auth = Mockito.mock(Authentication.class);
SecurityContext secCont = Mockito.mock(SecurityContext.class);
Mockito.when(secCont.getAuthentication()).thenReturn(auth);
SecurityContextHolder.setContext(secCont);
wmomyfyw

wmomyfyw1#

使用spring注解可以更轻松地完成这项工作 org.springframework.security.test.context.support.WithMockUser ```
@Test
@WithMockUser(username = "viewUser", authorities = { "view" })
public void mytest(){}

1hdlvixo

1hdlvixo2#

你嘲笑了Spring Authentication 此处的对象:

Authentication auth = Mockito.mock(Authentication.class);

你已经告诉Spring的 SecurityContextHolder 来储存这个 Authentication 此处的对象:

Mockito.when(secCont.getAuthentication()).thenReturn(auth);

所以,如果你想嘲笑 Authentication 对象返回“some name”,然后在其上设置一些模拟期望。例如:

Mockito.when(auth.getName()).thenReturn("aName");

相关问题