既然你想測試通過的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(...);
}
}
只需在PreAuthorize中使用「principal」的其他人員註釋,此操作將失敗並顯示nullpointerexcpetion,並且不會觸發重新授權,除非您在PreAuthorize批註中或security.xml中包含isAuthenticated()的效果。 – chrismarx 2014-02-28 15:34:22