Grails unit testing domain classes with Set properties - is this safe?
Posted
by Ali G
on Stack Overflow
See other posts from Stack Overflow
or by Ali G
Published on 2010-03-31T11:28:10Z
Indexed on
2010/03/31
11:33 UTC
Read the original article
Hit count: 233
I've created a domain class in Grails like this:
class MyObject {
static hasMany = [tags: String]
// Have to declare this here, as nullable constraint does not seem to be honoured
Set tags = new HashSet()
static constraints = {
tags(nullable: false)
}
}
Writing unit tests to check the size and content of the MyObject.tags property, I found I had to do the following:
assertLength(x, myObject.tags as Object[])
assertEquals(new HashSet([...]), myObject.tags)
To make the syntax nicer for writing the tests, I implemented the following methods:
void assertEquals(List expected, Set actual) {
assertEquals(new HashSet(expected), actual)
}
void assertLength(int expected, Set set) {
assertLength(expected, set as Object[])
}
I can now call the assertLength() and assertEquals() methods directly on an instance of Set, e.g. assertLength(x, myObject.tags) assertEquals([...], myObject.tags)
I'm new to Groovy and Grails, so unaware how dangerous method overloading like this is. Is it safe? If so, I'm slightly* surprised that these methods (or similar) aren't already available - please let me know if they are.
*
I can see how these methods could also introduce ambiguity if people weren't expecting them. E.g. assertLength(1, set)
always passes, no matter what the content of set
© Stack Overflow or respective owner