How to unit test controllers that use springSecurityService?

后端 未结 4 1352
傲寒
傲寒 2021-02-08 19:05

I have a user class like such:

class User {
    transient springSecurityService
    String displayName
    String password

    protected void encode         


        
4条回答
  •  孤街浪徒
    2021-02-08 19:59

    I think the right thing to do is to mock out the service. You'll want to test the different cases that can be the return value and that the correct value is passed to the service method.

    @Test
    public void something() {
       def user = ...
       def expectedPassword = 'mock encoded pass' 
       controller.springSecurityService = [encodePassword: { String passwd -> return expectedPassword }]
    
       ...
    }
    

    or

    @Test
    public void something() {
       def user = ...
       def expectedPassword = 'mock encoded pass' 
       def mockSecurityService = mockFor(SpringSecurityService)
       mockSecurityService.demand.encodePassword { String passwd -> return expectedPassword}
       controller.springSecurityService = mockSecurityService.createMock()
    
       ...
       mockSecurityService.verify() // throws exception if demands aren't met
    }
    

提交回复
热议问题