我在 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 字段有关吗?