开发者

Grails unit testing domain classes with Set properties - is this safe?

开发者 https://www.devze.com 2022-12-25 00:59 出处:网络
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

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(ex开发者_JS百科pected, 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


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() )


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号