简体   繁体   English

如何对具有关系映射的grails域类进行单元测试?

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

The output of my test gives com.example.book.Book : null . 我的测试输出为com.example.book.Book : null When I debug the test, b object is created with "MyBook" as its name . 当我调试测试时,将以"MyBook"作为name创建b对象。 But since its has a static mapping belongsTo , the test fails. 但是由于它具有静态映射belongsTo ,因此测试失败。 How do I make this work. 我如何做这项工作。 When I comment the belongsTo mapping in the Books.groovy, the test passes. 当我在belongsTo中注释belongsTo映射时,测试通过。 So how do I test Domain classes with mappings. 因此,我如何使用映射测试域类。 Should I instantiate a Library object and add a Book object to it? 我应该实例化Library对象并向其中添加Book对象吗? 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. 谢谢。

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. 是否使用belongsTo是否有意义取决于您的要求。 Do you really need to save the library and have all the books get saved as a result? 您是否真的需要保存图书馆并因此保存所有书籍?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM