org.apache.shiro.UnavailableSecurityManagerExcepti

2019-09-04 14:04发布

问题:

i have a junit test case that runs a code like:

if (SecurityUtil.isAuthenticated()) { 

}

and it gives an exception:

org.apache.shiro.UnavailableSecurityManagerException: No SecurityManager accessible to the calling code, either bound to the org.apache.shiro.util.ThreadContext or as a vm static singleton.  This is an invalid application configuration.

My Test Class configuration is as follows:

@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({ WebContextTestExecutionListener.class,
        DependencyInjectionTestExecutionListener.class,
        DirtiesContextTestExecutionListener.class,
        TransactionalTestExecutionListener.class })
@ActiveProfiles("test")
@DirtiesContext
@ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = {
        SpringConfig.class, SpringTestingConfig.class,
        SpringLocalContainerJPAConfig.class, CustomConfiguration.class })
public class MyTestClass { }

please advise how to fix this error, thanks.

回答1:

solved as follows:

private ThreadState _threadState;
protected Subject _mockSubject;

        @Before
        public void before() {
            _mockSubject = Mockito.mock(Subject.class);
            _threadState = new SubjectThreadState(_mockSubject);
            _threadState.bind();
        }