gpt4 book ai didi

java - Grails Spock - 从服务抛出异常 UndeclaredThrowableException

转载 作者:太空宇宙 更新时间:2023-11-04 15:21:47 25 4
gpt4 key购买 nike

在运行时此代码有效:

// Service class
class UserService {
ApiClient api

User create(User user) throws EmailTakenException, UsernameTakenException {
User savedUser

try {
savedUser = api.users.create user
setEnabled savedUser.id, true
return savedUser
}
catch(ApiException ex) {
switch(ex.subStatus) {
case SubStatus.USERS_EMAIL_TAKEN:
throw new EmailTakenException()
break
case SubStatus.USERS_USERNAME_TAKEN:
throw new UsernameTakenException()
break
}
}
}
}

从 Controller 调用:

// Controller class, an action
def create(CreateCommand cmd) {
if(request.get) {
render view: 'create'
return
}

if(!cmd.validate()) {
flash.model = cmd
redirect action: 'create'
return
}

def user = new User()
bindData user, params

try {
userService.create user

flash.success = 'ui.save.success'
}
catch(EmailTakenException ex) {
flash.model = cmd
flash.error = 'ui.email.taken'
}
catch(UsernameTakenException ex) {
flash.model = cmd
flash.error = 'ui.username.taken'
}

redirect action: 'create'
}

“User”、“SubStatus”和“ApiException”类来自 jar 库依赖项。当出现问题时,ApiClient 会抛出 ApiException。

在运行时,这段代码工作得很好,但是当我为此编写规范时,它会抛出 UndeclaredThrowableException。这是 Spock 规范:

ApiClient api
UsersApi apiUsers

void setup() {
api = Mock()
apiUsers = Mock()
api.users >> apiUsers

service.api = api
}

def "create: it should be able to throw an exception when email is already taken"() {
setup:
def user = new User(email: 'foo@cod.com', username: 'foo', name: 'Bar Foo')
def exception = Mock(ApiException)
exception.subStatus >> SubStatus.USERS_EMAIL_TAKEN

when:
service.create user

then:
thrown(EmailTakenException) // GrailsException is runtime
1 * apiUsers.create(_ as User) >> { throw new ApiException(400, SubStatus.USERS_EMAIL_TAKEN, null) }
}

最佳答案

也许您可以使用 @FailsWith 注释重写您的测试? http://code.google.com/p/spock/wiki/SpockBasics#Extensions

关于java - Grails Spock - 从服务抛出异常 UndeclaredThrowableException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20321922/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com