【发布时间】:2019-06-02 20:04:09
【问题描述】:
我正在尝试测试帐户过期异常。
def authfail() {
String msg = ''
def exception = session[WebAttributes.AUTHENTICATION_EXCEPTION]
// println("print exception: ${exception} | ${session} | ${springSecurityService.getCurrentUser()}")
if (exception) {
if (exception instanceof AccountExpiredException) {
msg = message(code: 'springSecurity.errors.login.expired')
}
else if (exception instanceof CredentialsExpiredException) {
msg = message(code: 'springSecurity.errors.login.passwordExpired')
}
else if (exception instanceof DisabledException) {
msg = message(code: 'springSecurity.errors.login.disabled')
}
else {
msg = message(code: 'springSecurity.errors.login.fail')
}
}
if (springSecurityService.isAjax(request)) {
render([error: msg] as JSON)
}
else {
flash.message = msg
redirect action: 'auth', params: params
}
}
我在意识到自己被卡住之前尝试编写上面的测试用例,因为我不知道如何触发过期登录,以便满足抛出 AccountExceptionExpired 异常的单元测试标准。
void "test authFail"() {
when:
session."${WebAttributes.AUTHENTICATION_EXCEPTION}" = new AccountExpiredException( 'This account has expired' )
def logexp = controller.authfail()
then:
logexp == 'springSecurity.errors.login.expired'
when:
session."${WebAttributes.AUTHENTICATION_EXCEPTION}" = new CredentialsExpiredException( 'This credentials have expired' )
def passexp = controller.authfail()
then:
passexp == 'springSecurity.errors.login.passwordExpired'
when:
session."${WebAttributes.AUTHENTICATION_EXCEPTION}" = new DisabledException( 'The account is disabled' )
def logdis = controller.authfail()
then:
logdis == 'springSecurity.errors.login.disabled'
when:
session."${WebAttributes.AUTHENTICATION_EXCEPTION}" = new UnsupportedOperationException( 'Sorry, we were not able to find a user with that username and password.' )
def logfail = controller.authfail()
then:
logfail == 'springSecurity.errors.login.fail'
when:
controller.authfail()
then:
1 * springSecurityService.isAjax( _ ) >> true
controller.response.json == [error :'springSecurity.errors.login.fail']
}
}
【问题讨论】:
标签: unit-testing grails spring-security