Unit testing with Spring Security

后端 未结 11 2203
暖寄归人
暖寄归人 2020-11-29 15:19

My company has been evaluating Spring MVC to determine if we should use it in one of our next projects. So far I love what I\'ve seen, and right now I\'m taking a look at th

11条回答
  •  北荒
    北荒 (楼主)
    2020-11-29 15:46

    Just do it the usual way and then insert it using SecurityContextHolder.setContext() in your test class, for example:

    Controller:

    Authentication a = SecurityContextHolder.getContext().getAuthentication();
    

    Test:

    Authentication authentication = Mockito.mock(Authentication.class);
    // Mockito.whens() for your authorization object
    SecurityContext securityContext = Mockito.mock(SecurityContext.class);
    Mockito.when(securityContext.getAuthentication()).thenReturn(authentication);
    SecurityContextHolder.setContext(securityContext);
    

提交回复
热议问题