有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

生成pdf文件的java测试Grails应用程序无法获取null对象的属性“config”

我正在尝试测试将生成pdf文件的服务类,但出现以下错误:

[getDocument] EXCEPTION: variables: [input, input, input], message: Cannot get property 'config' on null object

我的服务级别是:

class TemplateService {

    static transactional = false
    def grailsApplication

    def getDocument(inputs, idTemp) {
        def result
        if(inputs) {
            long dateBeginTransaction = System.currentTimeMillis()

            try {
                def http = new HTTPBuilder(grailsApplication.config.tempdoc.url?.replace("COI", idTemp))
                http.auth.basic grailsApplication.config.rest.login, grailsApplication.config.rest.password

                http.request(POST,JSON) { req ->
                    headers.'Accept' = 'application/json'
                    headers.'Content-type' = 'application/json'
                    body = [
                        inputs: inputs
                    ]
                    response.success = { resp, json ->
                        log.info "[getDocument] time: " + (System.currentTimeMillis() - dateBeginTransaction) / 1000 + " ms"
                        result = json?.pdf
                    }

                    response.failure = { resp, reader ->
                        log.error "[getDocument] inputs: " + inputs + ", response: " + resp + ", message: " + reader?.message
                    }
                }
            } catch (Exception e) {
                log.error "[getDocument] EXCEPTION: inputs: " + inputs + ", message: " + e.message
            }
        } else {
            log.error "[getDocument] params sense valors"
        }
        result
    }
}

这是我的测试: *注意:输入是一个arraylist

void "generate document"() {
    given: "generate document"
        def TemplateService = new TemplateService()

    when:
        def result = TemplateService.getDocument(inputs, idTemp)

    then:
        result != null
        result.size() > 0   

    where:
       inputs = [ "input", "input", "input"]
        idTemp =  "12AD"
}

共 (2) 个答案

  1. # 1 楼答案

    至少,您必须在测试中模拟配置。在Grails 3.3.5中:

    class PlaServiceSpec extends Specification implements ServiceUnitTest<Plaservice>, DataTest {
    
        Closure doWithConfig() {{ config ->
            config.plantidoc.url = 'my url'
        }}
    
        void "generate document"() {
            given:
                def variables = ["input:input", "input:input"]
                def idPlantitlla = "12AD"
    
            when:
                def result = service.getDocument(variables, idPlantitlla)
    
            then:
                // test the result
        }
    }
    
  2. # 2 楼答案

    您可以使您的测试成为集成测试(将其移动到test/integrationtest文件夹),这样grailsApplication将被注入到您的服务中