Grails 使用 Set 属性对域类进行单元测试 - 这安全吗?
我在 Grails 中创建了一个域类,如下所示:
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)
}
}
编写单元测试来检查 MyObject.tags 属性的大小和内容,我发现我必须执行以下操作:
assertLength(x, myObject.tags as Object[])
assertEquals(new HashSet([...]), myObject.tags)
为了使语法更好地编写测试,我实现了以下方法:
void assertEquals(List expected, Set actual) {
assertEquals(new HashSet(expected), actual)
}
void assertLength(int expected, Set set) {
assertLength(expected, set as Object[])
}
我现在可以直接在 Set 的实例上调用assertLength() 和assertEquals() 方法,例如 断言长度(x,myObject.tags) assertEquals([...], myObject.tags)
我是 Groovy 和 Grails 的新手,所以不知道像这样的方法重载有多么危险。安全吗?如果是这样,我有点*惊讶的是这些方法(或类似的方法)尚不可用 - 请让我知道它们是否可用。
*
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看起来不错
对我来说,Grails 权威指南一书(诚然是 2006 年) ,它说要这样做:
或使用 size() 方法,例如:
Looks ok to me
The Definitive Guide to Grails book (which admittedly is 2006), it says to do it with:
or using the size() method like:
问题中概述的方法似乎没有任何问题。
There don't seem to be any problems with the approach outlined in the question.