Home > other >  How to assert the content of a service message exception in a Grails unit test
How to assert the content of a service message exception in a Grails unit test

Time:03-18

I am using Grails 4.0.3 and want to assert that an exception is thrown in a given situation. Below, my PidService.

def validatePidIssuingConclusionDocument(JSONObject pidIssuingConclusionDocument){
        String message = "Document issuing number is mandatory"
        if(!pidIssuingConclusionDocument.has("docIssuingNumber")){throw new Exception(message)}
}

Below, my test case:

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.
}

I tried to use try/catch in the test case without success. Could anyone help me? I need to assert that the exception is thrown and the message is Document issuing number is mandatory in the given case.

CodePudding user response:

I need to assert that the exception is thrown and the message is Document issuing number is mandatory in the given case.

I can't provide an executable example around the code you provided because some things are missing (like buildPidIssuingOrder). See the project at https://github.com/jeffbrown/dnunesexception which contains an example that shows a way to deal with the exception in a test though.

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'

    }
}
  • Related