Unit testing with Spring Security

后端 未结 11 2176
暖寄归人
暖寄归人 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:45

    Personally I would just use Powermock along with Mockito or Easymock to mock the static SecurityContextHolder.getSecurityContext() in your unit/integration test e.g.

    @RunWith(PowerMockRunner.class)
    @PrepareForTest(SecurityContextHolder.class)
    public class YourTestCase {
    
        @Mock SecurityContext mockSecurityContext;
    
        @Test
        public void testMethodThatCallsStaticMethod() {
            // Set mock behaviour/expectations on the mockSecurityContext
            when(mockSecurityContext.getAuthentication()).thenReturn(...)
            ...
            // Tell mockito to use Powermock to mock the SecurityContextHolder
            PowerMockito.mockStatic(SecurityContextHolder.class);
    
            // use Mockito to set up your expectation on SecurityContextHolder.getSecurityContext()
            Mockito.when(SecurityContextHolder.getSecurityContext()).thenReturn(mockSecurityContext);
            ...
        }
    }
    

    Admittedly there is quite a bit of boiler plate code here i.e. mock an Authentication object, mock a SecurityContext to return the Authentication and finally mock the SecurityContextHolder to get the SecurityContext, however its very flexible and allows you to unit test for scenarios like null Authentication objects etc. without having to change your (non test) code

提交回复
热议问题