Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to unit test grails domain class that has a relational mapping?
    primarykey
    data
    text
    <p>The output of my test gives <code>com.example.book.Book : null</code>. When I debug the test, <code>b</code> object is created with <code>"MyBook"</code> as its <code>name</code>. But since its has a static mapping <code>belongsTo</code>, the test fails. How do I make this work. When I comment the <code>belongsTo</code> mapping in the Books.groovy, the test passes. So how do I test Domain classes with mappings. Should I instantiate a <code>Library</code> object and add a <code>Book</code> 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?</p> <p>Below is my code.</p> <p>Domains:</p> <pre><code>//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 } </code></pre> <p>Unit tests: </p> <pre><code>//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() } } </code></pre> <p>Test Output:</p> <pre><code>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) </code></pre> <p>Thanks.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload