我在Grails 3应用程序中使用MongoDB数据库,在进行单一测试时遇到了一些问题。
这是我的域类
@ToString(includeFields = true, includeNames = true, excludes = "dateCreated, lastUpdated, metaClass, sites")
@EqualsAndHashCode(excludes = "site")
class Campaign {
static mapWith = "mongo"
ObjectId id
String name
Boolean manualActive
Date startDate
Date endDate
static belongsTo = [site:Site]
static constraints = {
name size: 1..255, blank:false
manualActive nullable:true, validator: {val, obj->
(val != null && obj.startDate == null && obj.endDate == null) || (val == null && obj.startDate != null)
}
startDate nullable:true, validator: {val, obj->
(val != null && obj.manualActive == null) || (val == null && obj.manualActive != null)
}
endDate nullable:true, validator: {val, obj ->
(val != null && obj.startDate != null) || (val == null)
}
}
}
我还使用build-test-data插件来简化测试的数据创建,如果我尝试类似下面的内容,我会收到StackoverflowException:
@TestFor(CampaignService)
@Mock([Site, Campaign])
@Build([Site, Campaign])
class CampaignServiceSpec extends Specification {
def setup() {
}
def cleanup() {
}
void "Test that isSameCampaign throws a ForbiddenException if no site is given"() {
given:
def campaign = Campaign.build(id:new ObjectId(), manualActive:true)
def site = null
when:
service.isSameSite(site, campaign)
then:
thrown ForbiddenException
}
void "Test that isSameCampaign throws a ForbiddenException if it mismatches from the campaign"() {
given:
def site = Site.build(id:new ObjectId(), )
def campaign = Campaign.build(id:new ObjectId(), manualActive:true)
when:
service.isSameSite(site, campaign)
then:
thrown ForbiddenException
}
void "Test that isSameCampaign does NOT throw a ForbiddenException if no campaign is given"() {
given:
def site = Site.build(id:new ObjectId(), )
def campaign = Campaign.build(id:new ObjectId(), site:site,manualActive:true)
when:
service.isSameSite(site, campaign)
then:
notThrown ForbiddenException
}
}
但是如果我从域类中删除de @ToString()注释并实现我自己的toString方法,则测试运行正常。 任何想法为什么会发生这种stackoverflowException?可能与ObjectId字段有关吗?