我有一個控制器類與此代碼:的Grails /斯波克單元測試
List<MultipartFile> files = []
List<String> convertedContents = []
def convertedFiles = [:]
try {
params.myFile.each {
if (((MultipartFile) it.value).empty) {
throw new NoUploadedFileException('Break .each closure due to empty input.')
}
files.add((MultipartFile) it.value)
}
} catch (NoUploadedFileException e) {
redirect uri: request.getHeader('referer')
return
}
convertedContents = converterService.convertToBase64(files)
(code omitted)
我也有一個測試:
def "sampleTest"() {
when:
controller.sendFax()
then:
thrown(NoUploadedFileException)
response.redirectedUrl == 'index.gsp'
}
我試圖測試的是,我的控制器將拋出當沒有文件上傳並且點擊提交按鈕時出現「NoUploadedFileException」。
這是錯誤:
Running 1 unit test... 1 of 1
| Failure: sampleTest(com.synacy.HomeControllerSpec)
| Expected exception com.synacy.NoUploadedFileException, but got
java.lang.NullPointerException
at org.spockframework.lang.SpecInternals.thrownImpl(SpecInternals.java:79)
at com.synacy.HomeControllerSpec.throws NoUploadedFileException and returns to the
same page when no file is uploaded(HomeControllerSpec.groovy:36)
Caused by: java.lang.NullPointerException: Cannot invoke method convertToBase64() on
null object
at com.synacy.HomeController.sendFax(HomeController.groovy:43)
at com.synacy.HomeControllerSpec.sampleTest(HomeControllerSpec.groovy:33)
看來,它是不會通過try-catch塊,或者如果是,執行不工作。
也許'params.myFile.each'與'NullPointerException'失敗,因爲你沒有發送任何參數? –
NullPointerException指向try-catch塊後面的convertToBase64()方法。如果MyFile爲空或空,我的catch塊應該能夠處理它。 P.S.我試着檢查「== null || isEMpty()」來確認。問題仍然存在 – Marz
如果'params.myFile'爲空,那麼'each' closure將不會運行 –