How to unit test grails domain class that has a relational mapping?

牧云@^-^@ 提交于 2019-12-10 16:37:47

问题


The output of my test gives com.example.book.Book : null. When I debug the test, b object is created with "MyBook" as its name. But since its has a static mapping belongsTo, the test fails. How do I make this work. When I comment the belongsTo mapping in the Books.groovy, the test passes. So how do I test Domain classes with mappings. Should I instantiate a Library object and add a Book object to it? But that doesn't make testing the domain class in isolation as it is meant to be in a unit test, does it?

Below is my code.

Domains:

//Book.groovy
package com.example.book

class Book {
    static constraint = {
        name blank: false, size: 2..255, unique: true
    }
    static belongsTo = [lib: Library]
    String name
}

//Library.groovy
package com.example.library

class Library {
    static hasMany = [book: Book, branch: user: User]
    static constraints = {
        name blank: false
        place blank: false
    }
    String name
    String place
}

Unit tests:

//BookUnitTests.groovy
package com.example.book

import grails.test.*

class BookUnitTests extends GrailsUnitTestCase {
    protected void setUp() {
        super.setUp()
        mockForConstraintsTests(Book)
    }

    protected void tearDown() {
        super.tearDown()
    }

    void testPass() {
        def b = new Book(name: "MyBook")
        assert b.validate()
    }
}

Test Output:

Failure:  testPass(com.example.book.BookUnitTests)
|  Assertion failed: 

assert b.validate()
       | |
       | false
       com.example.book.Book : null

       at com.example.book.BookUnitTests.testPass(BookUnitTests.groovy:17)

Thanks.


回答1:


Yes, the way you have this set up the Book cannot exist without a Library. You will have to create a Library and assign the book to it.

Whether using belongsTo makes sense depends on your requirements. Do you really need to save the library and have all the books get saved as a result?



来源:https://stackoverflow.com/questions/9823650/how-to-unit-test-grails-domain-class-that-has-a-relational-mapping

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!