I've got a class:
class Test {
List<BigDecimal> values
static constraints = {
values(unique: true)
}
}
However,
void testUniqueness() {
List valList = [
new BigDeci开发者_如何学Pythonmal(1),
new BigDecimal(1)
]
def testInstance = new Test(values: valList)
mockForConstraintsTests(Test, [testInstance])
assertFalse "Validation should fail for non-unique values", testInstance.validate()
}
This assert fails, because .validate() is true!
I want a list of BigDecimal's which is unique to each instance of the Test object
This is not how it works. If you think about something simpler, e.g. "String username", the uniqueness check creates a unique index in the database on that column. So two users cannot have the same username/login/etc.
But you're asking for the contents of a List to be unique. The constraint (if it made sense) would compare two Lists and ensure that no two Test
instances' values
lists are the same. For example [1, 3, 5] <-> [1, 3] would be ok, but [1, 3, 5] <-> [1, 3, 5] would fail. This would be impractical to implement and is not supported. It's the equivalent of requiring that a username not repeat a letter - "burt" would be ok but "burtbeckwith" would fail.
If you want to have unique elements in a collection, just change it from a List to a Set. You don't even need a constraint:
class Test {
Set<BigDecimal> values
}
精彩评论