由于您要测试通过Spring AOP实现的功能,因此需要使用Spring
TestContext框架针对应用程序上下文运行测试。
然后,使用最少的安全性配置创建基本测试:
abstract-security-test.xml:
<security:authentication-manager alias="authenticationManager"> <security:authentication-provider user-service-ref = "userService" /></security:authentication-manager><security:global-method-security pre-post-annotations="enabled" /><bean id = "userService" class = "..." />
AbstractSecurityTest.java:
@ContextConfiguration("abstract-security-test.xml")abstract public class AbstractSecurityTest { @Autowired private AuthenticationManager am; @After public void clear() { SecurityContextHolder.clearContext(); } protected void login(String name, String password) { Authentication auth = new UsernamePasswordAuthenticationToken(name, password); SecurityContextHolder.getContext().setAuthentication(am.authenticate(auth)); }}现在,您可以在测试中使用它:
@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(...)public class CreatePostControllerSecurityTest extends AbstractSecurityTest { ... @Test @ExpectedException(AuthenticationCredentialsNotFoundException.class) public void testNoAuth() { controller.modifyContent(...); } @Test @ExpectedException(AccessDeniedException.class) public void testAccessDenied() { login("userWithoutAccessRight", "..."); controller.modifyContent(...); } @Test public void testAuthOK() { login("userWithAccessRight", "..."); controller.modifyContent(...); }}


