如何在Spring Security中对@Secured进行单元测试

时间:2014-04-12 02:10:34

标签: spring-security junit4

基本上我试图在我的应用程序中对@Secured功能进行单元测试。以下是安全实施的代码片段:

@Service
public class ReportService {

    @Secured(value={"ROLE_EMPLOYEE_A"})
    public void funcA() {
        System.out.println("This only accessible for Employee A.");
    }

}

现在我在Spring Security中定义了一系列Employee个用户,仅用于我的单元测试目的:

<security:global-method-security secured-annotations="enabled"/>

<security:authentication-manager>
    <security:authentication-provider>
        <security:password-encoder hash="plaintext"/>
        <security:user-service>
           <security:user name="empl1" password="pass1" authorities="ROLE_EMPLOYEE_A" />
           <security:user name="empl2" password="pass2" authorities="ROLE_EMPLOYEE_B" />
        </security:user-service>
    </security:authentication-provider>
 </security:authentication-manager>

在我的单元测试代码中,我有以下定义:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
"classpath:applicationcontext.xml",
"classpath:securitycontext.xml"
})
public class ReportServiceTest {
    @Autowired
    private ReportService reportService;

    @Test(expected = AccessDeniedException.class)
    public void testA() {
        assertNotNull(userService);

        UserDetails ud = userService.loadUserByUsername("empl2");
        assertNotNull(ud);

        Authentication auth = new UsernamePasswordAuthenticationToken(ud.getUsername(), ud.getPassword(), ud.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(auth);
        reportService.funcA();
}

在这个测试中,我期待抛出AccessDeniedException,但不知何故测试通过了,并且“这只适用于员工A。”打印在控制台输出中。我确信真正的执行工作正常,但我很好奇,知道为什么它在单元测试中不起作用?

0 个答案:

没有答案