Как игнорировать аннотацию @PreAuthorize(«IsAuthenticated()») в модульном тестировании?

#java #spring-boot #authentication #junit

#java #весенняя загрузка #аутентификация #junit

Вопрос:

Я написал тестовый класс:

 @RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@WebAppConfiguration
@Transactional
public class ProfileTest {

@Autowired
private UserService userService;

@Autowired
private ProfileService profileService;

@Autowired
private InterestService interestService;

private SiteUser[] users = {
        new SiteUser("test1@testing.com", "testPass"),
        new SiteUser("test2@testing.com", "testPass"),
        new SiteUser("test3@testing.com", "testPass"),
};

private String[][] interests = {
        {"music", "guitar_xxxxxx", "plants"},
        {"music", "music", "philosophy_19"},
        {"random", "football"},
};

@Test
public void testInterests() {
    
    for(int i=0; i<users.length; i  ) {
        SiteUser user = users[i];
        String[] interestArray = interests[i];
        
        userService.register(user);
        
        HashSet<Interest> interestSet = new HashSet<>();
        
        for(String interestText : interestArray) {
            Interest interest = interestService.createIfNotExists(interestText);
            interestSet.add(interest);
            
            assertNotNull("interest should not be null", interest);
            assertNotNull("Interest should have ID", interest.getId());
            assertEquals("Text should match", interestText, interest.getName());
        }
        
        Profile profile = new Profile(user);
        profile.setInterests(interestSet);
        profileService.save(profile); // ERROR 1
        
        Profile retrievedProfile = profileService.getUserProfile(user); // ERROR 2
        
        assertEquals("Interest sets should match", interestSet, retrievedProfile.getInterests());
    }
}

}
  

Но эта ошибка возникает в строках с комментариями ERROR 1 и ERROR 2, и я выяснил, почему это происходит, однако я не знаю, как это исправить или есть ли какой-либо обходной путь.

Проблема здесь:

 @Service
public class ProfileService {

@Autowired
ProfileDao profileDao;

@PreAuthorize("isAuthenticated()") // ERROR 1
public void save(Profile profile) {
    profileDao.save(profile);
}

@PreAuthorize("isAuthenticated()") // ERROR 2
public Profile getUserProfile(SiteUser user) {
    return profileDao.findByUser(user);
}
}
  

Эти аннотации @PreAuthorize («IsAuthenticated ()») вызывают проблему, потому что, когда я пытаюсь использовать эти два метода в моем UnitTest, я получаю это исключение: (AuthenticationCredentialsNotFoundException: объект аутентификации не был найден в SecurityContext):

 org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext
at org.springframework.security.access.intercept.AbstractSecurityInterceptor.credentialsNotFound(AbstractSecurityInterceptor.java:379)
at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:223)
at org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:65)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:747)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:689)
at com.socialnetwork.service.ProfileService$$EnhancerBySpringCGLIB$$22c09751.save(<generated>)
at com.socialnetwork.tests.ProfileTest.testInterests(ProfileTest.java:72)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  

И если я удалю эти аннотации, мой тест пройдет. Итак, вы знаете, как я могу исправить свои тесты?

Ответ №1:

Почему вы хотите пропустить эти аннотации? пробовали ли вы использовать @WithMockUser для того, чтобы использовать mocked user как часть вашего контекста?

Здесь у вас есть, как использовать эту аннотацию.

Комментарии:

1. Спасибо! Это устранило мою проблему — все, что мне нужно было сделать, это добавить аннотацию @WithMockUser поверх моего метода ‘testInterests ()’. (И чтобы использовать аннотацию @WithMockUser, мне пришлось добавить зависимость ‘spring-security-test’ в мой pom.xml .