簡體   English   中英

使用復合鍵的Grails單元測試

[英]Grails Unit Testing with Composite Keys

我正在嘗試對將帶有復合鍵的對象插入數據庫的方法進行單元測試。 每當我為此進行單元測試時,都會得到以下結果。

Failure:  |
testTransaction(com.myapp.foo.TestServiceSpec)
 |
Condition not satisfied:

Transaction.count() == 1
            |       |
            0       false

    at com.myapp.foo.TestServiceSpec.testTransaction(TestServiceSpec.groovy:166)

如果我從域類中刪除了組合鍵代碼,並且沒有其他任何內容,則測試通過。

這是我的域類Transaction.groovy:

class Transaction implements Serializable {
    String timestamp
    String source
    String tableName
    String fieldName
    Integer changeNumber
    String fieldValue
    String objectId

    static mapping = {
        id composite: ["timestamp", "source", "tableName", "fieldName", "changeNumber"], generator: 'assigned'
    }

    boolean equals(other) {
        if (!(other instanceof Transaction)) {
            return false
        }

        other.timestamp == timestamp && other.source == source && other.id == id && other.tableName == tableName && other.fieldName == fieldName && other.changeNumber == changeNumber
    }

    int hashCode() {
        def builder = new HashCodeBuilder()
        builder.append timestamp
        builder.append source
        builder.append tableName
        builder.append fieldName
        builder.append changeNumber
        builder.toHashCode()
    }
}

這是正在測試的代碼:

def response = [code: 'OK']
def transaction = new Transaction()

transaction.timestamp  = (new Date()).format("yyyy-MM-dd HH:mm:ss.SSS")
transaction.source       = "APP"
transaction.tableName    = "TABLE_NAME"
transaction.fieldName    = "FIELD_NAME"
transaction.fieldValue   = "FIELD_VALUE"
transaction.objectId     = "OBJECT_ID"

def changeNumber = Transaction.createCriteria().get {
    eq("objid", currentTransaction.objid)
    eq("tableName", currentTransaction.tableName)
    projections {
        max("changeNumber")
    }
}

currentTransaction.changeNumber = (changeNumber ?: 0) + 1

if(!transaction.save()) {
    transaction.errors.each {
        println it
    }

    response = [code: 'error transaction', status: 500]
}

return response

最后,這是我的單元測試代碼:

void testTransaction() {
    when:
    def response = testService.loadTransaction() // Creates transaction row

    then:
    assert response == [code: 'OK']
    assert Transaction.count() == 1
}

域結構是由另一方定義的,我無法以任何方式更改它,因此組合鍵是必須的。 不幸的是,此應用程序中的許多類都使用組合鍵,因此,如果無法對它們進行單元測試,則單元測試將無法覆蓋我的很多代碼。 任何讓我朝着正確方向前進的信息都將非常有用。

不要使用單元測試來測試持久性。

單元測試具有GORM實現,但它沒有數據庫支持,只有ConcurrentHashMap 很好,但是僅在避免對控制器等其他工件類型進行單元測試時,才應使用它來避免模擬持久層。 如果要測試持久性,請使用數據庫。

否則,您將看到類似這樣的時髦問題,以及諸如誤報或更糟的類似問題-誤報,如果測試不應該通過,則錯誤會留在“經過良好測試”的代碼中。

暫無
暫無

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

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