我正在使用 Grails 4.0.3 并希望斷言在給定情況下會引發例外。下面,我的 PidService。
def validatePidIssuingConclusionDocument(JSONObject pidIssuingConclusionDocument){
String message = "Document issuing number is mandatory"
if(!pidIssuingConclusionDocument.has("docIssuingNumber")){throw new Exception(message)}
}
下面,我的測驗用例:
void "wrong document"() throws Exception {
JSONObject documentWithoutIssuingNumber = new JSONObject()
documentWithoutIssuingNumber.accumulate("docIssuingNumber","123")
pidService.buildPidIssuingOrder(documentWithoutIssuingNumber)
// How can I assert that the exception is thrown and verify it message.
}
我嘗試在測驗用例中使用 try/catch 沒有成功。有人可以幫我嗎?我需要斷言拋出了例外,并且訊息是在給定情況下,檔案發行號是強制性的。
uj5u.com熱心網友回復:
我需要斷言拋出了例外,并且訊息是在給定情況下,檔案發行號是強制性的。
我無法圍繞您提供的代碼提供可執行示例,因為缺少某些內容(例如buildPidIssuingOrder
)。請參閱https://github.com/jeffbrown/dnunesexception上的專案,其中包含一個示例,該示例顯示了一種在測驗中處理例外的方法。
grails-app/services/dnunesexception/PidService.groovy
package dnunesexception
import org.grails.web.json.JSONObject
class PidService {
def buildPidIssuingOrder(JSONObject pidIssuingConclusionDocument) {
throw new Exception('Document issuing number is mandatory')
}
}
src/test/groovy/dnunesexception/PidServiceSpec.groovy
package dnunesexception
import grails.testing.services.ServiceUnitTest
import spock.lang.Specification
import org.grails.web.json.JSONObject
class PidServiceSpec extends Specification implements ServiceUnitTest<PidService>{
void "test something"() {
when:
JSONObject documentWithoutIssuingNumber = new JSONObject()
documentWithoutIssuingNumber.accumulate("docIssuingNumber","123")
service.buildPidIssuingOrder(documentWithoutIssuingNumber)
then:
def e = thrown(Exception)
and:
e.message == 'Document issuing number is mandatory'
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/446219.html