Grails如何对异常进行单元测试

Grails how to perform unit test on exceptions

我正在尝试测试帐户过期异常。

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']

    }
}

以下将测试您的大部分方法:

import grails.plugin.springsecurity.SpringSecurityService
import grails.test.mixin.TestFor
import org.springframework.security.authentication.AccountExpiredException
import org.springframework.security.authentication.CredentialsExpiredException
import org.springframework.security.authentication.DisabledException
import org.springframework.security.web.WebAttributes
import spock.lang.Specification

@TestFor(YourController)
class YourControllerSpec extends Specification {

def springSecurityService = Mock( SpringSecurityService )

void setup() {
    controller.springSecurityService = springSecurityService
}

void "test authFail"() {
    given:
        session."${WebAttributes.AUTHENTICATION_EXCEPTION}" = new AccountExpiredException( 'This account has expired' )
    when:
        controller.authfail()
    then:
        flash.message == 'springSecurity.errors.login.expired'
    when:
        session."${WebAttributes.AUTHENTICATION_EXCEPTION}" = new CredentialsExpiredException( 'This credentials have expired' )
        controller.authfail()
    then:
        flash.message == 'springSecurity.errors.login.passwordExpired'
    when:
        session."${WebAttributes.AUTHENTICATION_EXCEPTION}" = new DisabledException( 'The account is disabled' )
        controller.authfail()
    then:
        flash.message == 'springSecurity.errors.login.disabled'
    when:
        session."${WebAttributes.AUTHENTICATION_EXCEPTION}" = new UnsupportedOperationException( 'Bad stuff' )
        controller.authfail()
    then:
        flash.message == 'springSecurity.errors.login.fail'
    when:
        controller.authfail()
    then:
        1 * springSecurityService.isAjax( _ ) >> true
        response.json == [error :'springSecurity.errors.login.fail']
}
}

会话只是一个映射,我们在其中添加了字符串常量的键和异常的值。 对于所有测试,除了最后一个我们将落入您的最后一个 else 块,在最终测试中我们 return 对 `isAjax' 为真。

虽然这不是 Grails,但它是 SpringBoot 2.0。

如果将 failureHandler 公开为一个 bean,就可以监视它。

@SpyBean
AuthenticationFailureHandler failureHandler;

并简单地验证是否已抛出异常

Mockito.verify(failureHandler).onAuthenticationFailure(
    any(),
    any(),
    any(AccountExpiredException.class)
);

一个简单的 test 可以是这样的:

@Test
public void accountExpired() throws Exception {
    doReturn(user
        .username("expired")
        .accountExpired(true)
        .build()
    ).when(userDetailsService).loadUserByUsername(any(String.class));
    mvc.perform(
        MockMvcRequestBuilders.post("/login")
            .param("username", "expired")
            .param("password", "password")
    )
        .andExpect(status().is4xxClientError())
        .andExpect(unauthenticated())
    ;
    Mockito.verify(failureHandler).onAuthenticationFailure(
        any(),
        any(),
        any(AccountExpiredException.class)
    );
}

https://github.com/fhanik/spring-security-community/

处的所有样本