Reputation: 31
I am trying to create a test in grails to ensure indeed that the unique:true constraint works, here's my class and test file:
package edu.drexel.goodwin.events.domain
class UpayConfig {
String name
String siteId
String postingCode
static constraints = {
name(blank:false, maxSize:50)
siteId(blank:false, unique:true)
postingCode(blank:false)
}
}
package edu.drexel.goodwin.events.domain
import grails.test.*
class UpayConfigTests extends GrailsUnitTestCase { protected void setUp() { super.setUp() }
protected void tearDown() {
super.tearDown()
}
void testCleanUpayConfigValidates() {
mockForConstraintsTests UpayConfig
def cleanUpayConfig = create()
assertTrue cleanUpayConfig.validate()
}
void testUpayConfigSiteIdMustBeUnique() {
mockForConstraintsTests UpayConfig
def upayConfigOne = create()
def upayConfigTwo = create()
assertFalse upayConfigOne.validate()
assertFalse upayConfigTwo.validate()
upayConfigTwo.siteId = '81'
assertTrue upayConfigOne.validate()
assertTrue upayConfigTwo.validate()
}
UpayConfig create() {
def upayConfig = new UpayConfig(
siteId: '82',
name: 'SMT - Workshops',
postingCode: '6'
)
}
}
But that second test fails, the upayConfig variables both return true for .validate() even though I am telling them both to have the same siteId...
I have a feeling this has something to do with the fact that these aren't being placed in the database, just being stored in memory?
All help is much appreciated, thank you. -Asaf
Upvotes: 2
Views: 907
Reputation: 31
Thank you. I looked up this website: http://www.ibm.com/developerworks/java/library/j-grails10209/index.html and it had a section called "Testing the unique constraint with mockForConstraintsTests()" so following it I modified my test to be as follows and it passed correctly:
void testUpayConfigSiteIdMustBeUnique() {
def upayConfigOne = create()
mockForConstraintsTests(UpayConfig, [upayConfigOne])
def upayConfigTwo = create()
assertFalse upayConfigTwo.validate()
assertEquals "unique", upayConfigTwo.errors["siteId"]
upayConfigTwo.siteId = '81'
assertTrue upayConfigTwo.validate()
}
Thank you for your help, -Asaf
Upvotes: 1
Reputation: 35864
The uniqueness will be at the database level. You're never saving the domain, so as far as upayConfigTwo is concerned, it is unique. You'll need to do a regular mock and actually call save() on upayConfigOne.
Upvotes: 5