我試着寫單元測試這個控制器的方法單元測試@PreAuthorized(hasRole)控制器方法
@PreAuthorize("hasRole(#d.code) or hasRole('ROLE_ALL_ACCESS')")
@RequestMapping(value = "{department}/{examination}", method = RequestMethod.GET)
public String show(ModelMap model, Principal principal, Locale locale, D d) {
model.addAttribute(service.getItem(d) //THIS CAUSES NULL ON TEST
.addAttribute(new DateTime())
.addAttribute(locale);
return "show";
我想這
@Test (expected=AccessDeniedException.class)
public void testShowAccessDenied() {
super.simulateRole("ROLE_STUDENT");
controller.show(new ModelMap(), Helper.getTestPrincipal(), Locale.getDefault(), new D());
但它會導致空指針異常的標記線,這意味着測試正在運行該方法,而不是基於錯誤的角色拋出AccessDeniedException。
我的超級測試類是
public class AuthorizeTestBase {
private Mockery jmock = new JUnit4Mockery();
private AuthenticationManager authenticationManager= jmock.mock(AuthenticationManager.class);
@Before
public void setUp() {
jmock.checking(new Expectations() {{ ignoring(anything()); }});
}
protected void simulateRole(String role) {
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
authorities.add(new SimpleGrantedAuthority(role));
PreAuthenticatedAuthenticationToken pat = new PreAuthenticatedAuthenticationToken(Helper.getTestPrincipal(), "", authorities);
SecurityContextHolder.getContext().setAuthentication(authenticationManager.authenticate(pat));
}
Helper.getTestPrincipal是
LdapPerson.Essence essence = new LdapPerson.Essence();
LdapPerson user = (LdapPerson) essence.createUserDetails();
return new PreAuthenticatedAuthenticationToken(user, "password");
我覺得我缺少嘲諷的AuthenticationManager的東西。幫我!
哪個標線? – avijendr
查看控制器方法代碼並在那裏發表評論 – mjgirl