Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grails, unit test mock domain with assigned id

I am using assigned id in my domain

class Book {

Integer id
String name

static mapping = {
    id generator: 'assigned'
    }   
}

so to add a new book:

def book = new Book([name: "The Adventures of Huckleberry Finn"])
book.id = 123
book.save(flush: true)

everything works perfectly, the problem is in my unit tests

first of all I can only mock 1 domain class, secondly, I cannot use .save() on unit test, so my only option (as far as i know) is to use mockDomain as follow:

mockDomain(Book, [ [id: 123, name: "The Adventures of Huckleberry Finn"] ])

but it is not working, it would work in a normal domain without "id generator: 'assigned'"

any ideas? I read that I wouldn't face this problem in integrated test, it is just a problem in unit test thanks

like image 330
iMiX Avatar asked May 13 '13 23:05

iMiX


1 Answers

You would need the bindable constraint for id if you want to use (by default id is not bindable) it as map params to create the domain object in unit test. The domain class would have

static constraints = {
    id bindable: true
}

Words of advice:
If you are using Grails > 2.x, use @Mock to mock domain classes instead of mockDomain. You can find details about Unit Testing in Grails docs.

Another Level Up
Use build-test-data plugin to mock domain objects.

like image 165
dmahapatro Avatar answered Sep 17 '22 16:09

dmahapatro