Grails Spock测试没有保存对象,我怀疑它与静态映射有关?
我对这种行为困惑了几个小时。我正在使用Grails2.4.2和spock进行测试。我有一个域对象,如下所示:Grails Spock测试没有保存对象,我怀疑它与静态映射有关?,grails,Grails,我对这种行为困惑了几个小时。我正在使用Grails2.4.2和spock进行测试。我有一个域对象,如下所示: class AccRegStrDb implements Serializable { BigInteger accountId String keyName BigInteger indexNumber String value static mapping = { version false keyName
class AccRegStrDb implements Serializable {
BigInteger accountId
String keyName
BigInteger indexNumber
String value
static mapping = {
version false
keyName column: "`key`"
indexNumber column: "`index`"
id generator:'assigned',
composite: ['accountId', 'keyName', 'indexNumber']
}
}
请注意,我的类具有静态映射线。在我的spock测试中,我试图测试一个将对象保存到DB中的服务。我有以下代码:
@TestFor(AccountRecordService)
@Mock([AccRegStrDb])
class AccountRecordServiceSpec extends Specification {
def setup() {
}
def cleanup() {
}
void "saveValue() of String saves to AccRegStrDb"() {
when:
service.saveValue(2000000, "keyName", "string")
then:
1 == AccRegStrDb.count()
}
}
我的服务如下所示:
@Transactional
class AccountRecordService {
public void saveValue(Long accountId, String keyName, String value) {
def test = new AccRegStrDb(
accountId: accountId,
keyName: keyName,
indexNumber: BigInteger.ZERO,
value: value
).save(flush: true, failOnError: true)
}
}
class AccRegStrDb implements Serializable {
BigInteger accountId
String keyName
BigInteger indexNumber
String value
static mapping = {
version false
keyName column: "`key`"
indexNumber column: "`index`"
id composite: ['accountId', 'keyName', 'indexNumber']
}
}
在测试应用程序上,我的断言失败,因为对象未保存。没有任何奇怪的错误。当我移除类中的静态映射时,断言将通过。有什么不对劲吗?有什么帮助吗
:D通过删除我的域类中的generator:“assigned”解决了此问题。现在看起来是这样的:
@Transactional
class AccountRecordService {
public void saveValue(Long accountId, String keyName, String value) {
def test = new AccRegStrDb(
accountId: accountId,
keyName: keyName,
indexNumber: BigInteger.ZERO,
value: value
).save(flush: true, failOnError: true)
}
}
class AccRegStrDb implements Serializable {
BigInteger accountId
String keyName
BigInteger indexNumber
String value
static mapping = {
version false
keyName column: "`key`"
indexNumber column: "`index`"
id composite: ['accountId', 'keyName', 'indexNumber']
}
}