簡體   English   中英

使用Grails對域類進行單元測試

[英]Unit testing for domain classes using Grails

目前正在搜索教程,解釋和示例。 我嘗試了不同的例子,並遇到了不同的錯誤。 我目前的錯誤是:

| 錯誤編譯錯誤編譯[unit]測試:啟動失敗:

在我的測試報告中。 它輸出這個:

單元測試結果 - 摘要未執行任何測試。

我的“UserSpec.groovy”代碼是這樣的:

package newmyproject245

import grails.test.mixin.*
import spock.lang.Specification

@TestFor(User)
class UserSpec extends ConstraintSpecification {

    def setup() {
        Expectations.applyTo User
    }

    def cleanup() {
    }

    void testShouldDoNothing() {
        Expectations.applyTo User

        user."password is not blank"
        user."password is not nullable"
        user."name is not blank"
        user."name is not nullable"
    }

    void testEventNameConstraints() {
        Expectations.applyTo User
        def user = new User()

        user."name is not blank"
        user."name is not nullable"
    }
}

任何人都可以幫忙。 我是grails的新手。 謝謝!

除了上面的問題,我在課堂上省略了Contraints ,如圖所示:

class UserSpec extends Specification {

我遇到了這個錯誤:

| 運行1單元測試... 1 of 1 | 失敗:initializationError(org.junit.runner.manipulation.Filter)| java.lang.Exception:沒有在org.junit的org.junit.internal.requests.FilterRequest.getRunner(FilterRequest.java:35)上找到與org.junit.runner.Request$1@12c27788的grails測試目標模式過濾器匹配的測試。 runner.JUnitCore.run(JUnitCore.java:138)| 完成1單元測試,1 0m 0s失敗| 錯誤運行測試時發生致命錯誤:非空屬性引用瞬態值 - 必須在當前操作之前保存瞬態實例:newmyproject245.Order.product - > newmyproject245.Product; 嵌套異常是org.hibernate.TransientPropertyValueException:非null屬性引用瞬態值 - 必須在當前操作之前保存瞬態實例:newmyproject245.Order.product - > newmyproject245.Product(使用--stacktrace查看完整跟蹤)

有人幫忙。 再次,謝謝!

我已經得到了答案。 查看代碼以供參考:

UserSpec.groovy

package project101

import grails.test.mixin.TestMixin
import grails.test.mixin.support.GrailsUnitTestMixin
import spock.lang.Specification

/**
 * See the API for {@link grails.test.mixin.support.GrailsUnitTestMixin} for usage instructions
 */
@TestMixin(GrailsUnitTestMixin)
@TestFor(User)
class UserSpec extends Specification {

    def user

    def setup() {
        user = new User(firstName: 'FIRSTNAME', lastName: 'LASTNAME', address: 'Finland', username: 'user1', password: 'pass123', userType: 'ADMIN')

    }

    def cleanup() {
        user = null
    }

    void "Test if User handles"() {
        given:
            setup()
        when: "User field has null value"
            user?.username = null
        then: "Validation returns false"
            user?.validate() == false
            user?.errors?.hasFieldErrors('username') == true
    }
}

並確保測試環境dbCreate是“create-drop”以避免此類錯誤。 DataSource.groovy中找到

test {
        dataSource {
            pooled = true
            dbCreate = "create-drop"

問候,

謝謝! (^ _〜)

暫無
暫無

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

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