Grails - 使用 reCaptcha 插件对控制器的方法进行单元测试

发布于 2024-12-06 18:30:46 字数 4154 浏览 6 评论 0原文

我想对以下方法进行单元测试:

def handleEmailSharing = { EmailSharingCommand esc ->
        if (params.send) {
            def recaptchaOK = true
            if (!recaptchaService.verifyAnswer(session, request.getRemoteAddr(), params)) {
                recaptchaOK = false
            }

         }
...

这就是我尝试执行的方法:

import com.megatome.grails.RecaptchaService

class EmailSharerControllerTests extends ControllerUnitTestCase {

    protected void setUp() {
     controller.recaptchaService = new RecaptchaService()
   }

void testHandleEmailSharingSendAndSuccess() {
       mockCommandObject(EmailSharingCommand)
        def emailSharingCommand = new EmailSharingCommand(from: "[email protected]", 
                                                          to: "   [email protected]   ,    [email protected]   ", 
                                                          cc: "", 
                                                          bcc:"[email protected]",
                                                          trimmedListOfToRecipients: ["[email protected]", "[email protected]"])
        emailSharingCommand.validate()
}
controller.handleEmailSharing(emailSharingCommand)

但我收到以下错误:

Cannot get property 'recaptcha' on null object
java.lang.NullPointerException: Cannot get property 'recaptcha' on null object
    at com.megatome.grails.RecaptchaService.getRecaptchaConfig(RecaptchaService.groovy:33)
    at com.megatome.grails.RecaptchaService.this$2$getRecaptchaConfig(RecaptchaService.groovy)
    at com.megatome.grails.RecaptchaService$this$2$getRecaptchaConfig.callCurrent(Unknown Source)
    at com.megatome.grails.RecaptchaService.isEnabled(RecaptchaService.groovy:100)
    at com.megatome.grails.RecaptchaService$isEnabled.callCurrent(Unknown Source)
    at com.megatome.grails.RecaptchaService.verifyAnswer(RecaptchaService.groovy:81)
    at com.megatome.grails.RecaptchaService$verifyAnswer.call(Unknown Source)
    at bankemist.personalcreditcomparator.EmailSharerController$_closure2.doCall(EmailSharerController.groovy:49)
    at bankemist.personalcreditcomparator.EmailSharerControllerTests.testHandleEmailSharingSendButtonButMissingFromAndTo(EmailSharerControllerTests.groovy:49)

这很奇怪,因为它基本上说我的 org.codehaus.groovy.grails.commons .ConfigurationHolder 为 null,或其包含的 recaptcha 对象。 RecaptchaService.groovy 的调用行 33 是​​:

if (ConfigurationHolder.config.recaptcha) {...}

或者(最后一个:))我的 RecaptchaConfig.groovy 是如何设置的:

recaptcha {
    // These keys are generated by the ReCaptcha service
    publicKey = "xxx"
    privateKey = "xxx"

    // Include the noscript tags in the generated captcha
    includeNoScript = true
}

mailhide {
    // Generated by the Mailhide service
    publicKey = ""
    privateKey = ""
}

environments {
  development {
    recaptcha {
      // Set to false to disable the display of captcha
      enabled = true

      // Communicate using HTTPS
      useSecureAPI = false
    }
  }
  test {
    recaptcha {
      // Set to false to disable the display of captcha
      enabled = true

      // Communicate using HTTPS
      useSecureAPI = false
    }
  }

我无法解决这个问题。 我尝试将configurationHolder导入到测试文件中,但它没有改变任何东西。非常感谢任何帮助。

I would like to unit test the following method:

def handleEmailSharing = { EmailSharingCommand esc ->
        if (params.send) {
            def recaptchaOK = true
            if (!recaptchaService.verifyAnswer(session, request.getRemoteAddr(), params)) {
                recaptchaOK = false
            }

         }
...

This is the way I am trying to do it:

import com.megatome.grails.RecaptchaService

class EmailSharerControllerTests extends ControllerUnitTestCase {

    protected void setUp() {
     controller.recaptchaService = new RecaptchaService()
   }

void testHandleEmailSharingSendAndSuccess() {
       mockCommandObject(EmailSharingCommand)
        def emailSharingCommand = new EmailSharingCommand(from: "[email protected]", 
                                                          to: "   [email protected]   ,    [email protected]   ", 
                                                          cc: "", 
                                                          bcc:"[email protected]",
                                                          trimmedListOfToRecipients: ["[email protected]", "[email protected]"])
        emailSharingCommand.validate()
}
controller.handleEmailSharing(emailSharingCommand)

But I get the following error:

Cannot get property 'recaptcha' on null object
java.lang.NullPointerException: Cannot get property 'recaptcha' on null object
    at com.megatome.grails.RecaptchaService.getRecaptchaConfig(RecaptchaService.groovy:33)
    at com.megatome.grails.RecaptchaService.this$2$getRecaptchaConfig(RecaptchaService.groovy)
    at com.megatome.grails.RecaptchaService$this$2$getRecaptchaConfig.callCurrent(Unknown Source)
    at com.megatome.grails.RecaptchaService.isEnabled(RecaptchaService.groovy:100)
    at com.megatome.grails.RecaptchaService$isEnabled.callCurrent(Unknown Source)
    at com.megatome.grails.RecaptchaService.verifyAnswer(RecaptchaService.groovy:81)
    at com.megatome.grails.RecaptchaService$verifyAnswer.call(Unknown Source)
    at bankemist.personalcreditcomparator.EmailSharerController$_closure2.doCall(EmailSharerController.groovy:49)
    at bankemist.personalcreditcomparator.EmailSharerControllerTests.testHandleEmailSharingSendButtonButMissingFromAndTo(EmailSharerControllerTests.groovy:49)

Which is strange, because it basically says that my org.codehaus.groovy.grails.commons.ConfigurationHolder is null, or the recaptcha object it contains. The call line 33 of RecaptchaService.groovyis:

if (ConfigurationHolder.config.recaptcha) {...}

Or (last one :) ) this how my RecaptchaConfig.groovy is set:

recaptcha {
    // These keys are generated by the ReCaptcha service
    publicKey = "xxx"
    privateKey = "xxx"

    // Include the noscript tags in the generated captcha
    includeNoScript = true
}

mailhide {
    // Generated by the Mailhide service
    publicKey = ""
    privateKey = ""
}

environments {
  development {
    recaptcha {
      // Set to false to disable the display of captcha
      enabled = true

      // Communicate using HTTPS
      useSecureAPI = false
    }
  }
  test {
    recaptcha {
      // Set to false to disable the display of captcha
      enabled = true

      // Communicate using HTTPS
      useSecureAPI = false
    }
  }

I do not manage to work around this issue.
I have tried to import the configurationHolder into the test file but it does not chage anything. Any help greatly appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

短暂陪伴 2024-12-13 18:30:46

单元测试不会有 ConfigurationHolder,因为它们不在运行框架内执行。在单元测试中,最好的选择是模拟 RecaptchaService,因此在测试方法中如下所示:

def recapMock = mockFor(RecaptchaService)
recapMock.demand.verifyAnswer(1..1) { session, remoteAddr, params ->
     return true // Or false if you want it to fail in your test
}
controller.recaptchaService = recapMock.createMock()
// Then run your test
controller.handleEmailSharing(emailSharingCommand)

Unit tests will not have ConfigurationHolder because they are not executed inside the running framework. In unit tests the best option is to mock the RecaptchaService, so like this inside your test method:

def recapMock = mockFor(RecaptchaService)
recapMock.demand.verifyAnswer(1..1) { session, remoteAddr, params ->
     return true // Or false if you want it to fail in your test
}
controller.recaptchaService = recapMock.createMock()
// Then run your test
controller.handleEmailSharing(emailSharingCommand)
初心未许 2024-12-13 18:30:46

您应该注入一个 recaptchaService 并模拟 verifyAnswer 以返回您想要为测试用例返回的任何内容。

     def recaptchaServiceMock = mockFor(recaptchaService)

            recaptchaServiceMock.demand.verifyAnswer() {Session session, 
                                                        Map params->
                return true
            }

      currentService.recaptchaService = recaptchaServiceMock.createMock()

You should inject a recaptchaService and mock the verifyAnswer to return whatever you want to return for your test case.

     def recaptchaServiceMock = mockFor(recaptchaService)

            recaptchaServiceMock.demand.verifyAnswer() {Session session, 
                                                        Map params->
                return true
            }

      currentService.recaptchaService = recaptchaServiceMock.createMock()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文