2017-09-04 100 views
0

我正在测试我的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); 

回答

2

你嘲笑Spring的Authentication对象的位置:

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

你告诉Spring的SecurityContextHolder在这里保存此Authentication对象:

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

所以,如果你想嘲笑Authentication对象返回“某个名称”,然后只设置一些模拟期望。例如:

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

谢谢,它的工作原理做容易得多;) – DonLeo

1

这可以在Spring注解org.springframework.security.test.context.support.WithMockUser

@Test 
    @WithMockUser(username = "viewUser", authorities = { "view" }) 
    public void mytest(){}