2014-01-16 47 views
0

我試着寫單元測試這個控制器的方法單元測試@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的東西。幫我!

+0

哪個標線? – avijendr

+0

查看控制器方法代碼並在那裏發表評論 – mjgirl

回答

0

當您嘗試撥打服務時,NPE正在發生。你的類AuthorizeTestBase不知道任何spring bean服務/ dao等。所以它應該加載彈簧鋼絲配置。以下是一個例子。

@RunWith(SpringJUnit4ClassRunner.class) 
@WebAppConfiguration 
@ContextConfiguration(locations = {"classpath:/applicationContext-test.xml", 
            "classpath:/applicationContext-ABC-test.xml", 
            "classpath:/applicationContext-DEF-test.xml", 
            "classpath:/applicationContext-serviceGHI-test.xml", 
            "classpath:/applicationContext-securityHIJ-test.xml" 
}) 
public class AuthorizeTestBase { 
..... 

} 

也請看看成 - Spring MVC Test Framework

+0

我可以弄清楚,但是控制器方法不應該在第一個地方運行,因爲它有@PreAuthorized anotation並且用戶角色是錯誤的? – mjgirl

+0

@mjgirl - 那麼你還沒有弄清楚我很害怕。如果你在我的答案中看到了評論 - 你的應用程序將如何知道角色和內容? ((「hasRole(#d.code)or hasRole('ROLE_ALL_ACCESS'))如果彈簧配置沒有加載? – avijendr

+0

所以我在說,在這種情況下我不應該得到NullPointer,但得到它是因爲認證出錯。問題是現在我真正的sec-config使用ldap,它在pom.xml中檢索它的連接屬性 – mjgirl