views:

171

answers:

2

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

A: 

Looks ok to me

The Definitive Guide to Grails book (which admittedly is 2006), it says to do it with:

assertLength( 1, myObject.tags as Object[] )

or using the size() method like:

assertEquals( 1, myObject.tags.size() )
tim_yates
Ok, that's how I'm doing assertLength() inside the method. I'd be interested to know if use of a method like this would be discouraged.Also, any thoughts on my assertEquals() method?
Alison
A: 

There don't seem to be any problems with the approach outlined in the question.

Alison