簡體   English   中英

Grails域單元測試-MockFor()

[英]Grails domain unit testing - mockFor()

這是域類:

class Registration {

  String email
  String generatedKey

  def beforeInsert = {
      String newToken = GlobalHelper.getRandomString()
      generatedKey = newToken
  }
}

這是單元測試的相關部分:

    def c = mockFor(GlobalHelper)
    c.demand.static.getRandomString {-> return "nestoABC" }
    c.createMock()
    reg.beforeInsert()

運行測試時,出現此錯誤:


沒有這樣的屬性:類的GlobalHelper:RegistrationTests

groovy.lang.MissingPropertyException:否這樣的屬性:類的GlobalHelper:RegistrationTests.testConstraints(RegistrationTests.groovy:57)上的RegistrationTests


GlobalHelper類位於Groovy源文件夾中,提到的第57行是帶有嘲笑()方法的行。

Grails Testing文檔對於此問題不是很有幫助...

我知道可以使用集成測試輕松解決此問題,但我認為它也應該以這種方式工作。

提前致謝

根據文檔,模擬靜態方法當前不起作用。

您正在使用哪個版本的Grails?

使用Grails 1.1.1,以下測試適用於上述Registration域。 這應該在帶有測試插件的Grails 1.1+和Grails 1.0.x上運行。

您需要確保您的單元測試擴展了GrailsUnitTestCase 我犯了很多次錯誤。

import grails.test.*

class RegistrationTests extends GrailsUnitTestCase {

    void testBeforeInsert() {
        def reg = new Registration()
        reg.generatedKey = "preBeforeInsert"
        String randomString = "nestoABC"

        def c = mockFor(GlobalHelper)
        c.demand.static.getRandomString {-> return randomString }

        assertNotSame(reg.generatedKey, randomString)
        reg.beforeInsert()
        assertSame(reg.generatedKey, randomString)

        c.verify() //Verify the demands
    }
}

我遇到了這個問題,並通過完全限定要模擬的類的類名來解決了這個問題。 因此,對於您的示例:

def c = mockFor(GlobalHelper)

會成為

def c = mockFor(com.example.fully.qualified.GlobalHelper)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM