У меня есть служба Spring Boot, такая как
@GetMapping("/myService")
@PreAuthorize("hasAnyAuthority('EDIT')")
public String savePermissionList(...) {
....
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Integer roleId = null;
if (authentication.getDetails() instanceof MyRole) {
roleId = (((MyRole) authentication.getDetails()).getId());
}
}
Мне нужна эта служба для сохранения списка разрешений, которые мне понадобятся позже. Поскольку я хочу протестировать другие сервисы, мне нужно запустить этот метод в самом начале моих тестов. Я думал, что могу использовать что-то вроде этого:
@Before
public void setUp() throws Exception {
role1 = new MyRole(....)
MockitoAnnotations.initMocks(this);
final Authentication authentication = mock(Authentication.class);
final SecurityContext securityContext = mock(SecurityContext.class);
when(securityContext.getAuthentication()).thenReturn(authentication);
SecurityContextHolder.setContext(securityContext);
when(authentication.getDetails()).thenReturn(role1);
final ArrayList<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority("EDIT"));
when((List<GrantedAuthority>) authentication.getAuthorities()).thenReturn(authorities);
...
savePermissionList(...);
Но проблема, с которой я сталкиваюсь, это сообщение об ошибке:
org.springframework.security.authentication.ProviderNotFoundException: No AuthenticationProvider found for org.springframework.security.core.Authentication$MockitoMock$1249720784