正如我所说,我不是Spring用户,但在使用MCVE时,我注意到了以下几点:
-
对于
@DataJpaTest
,不仅
persisted2 == persisted1
是真的,但是
persisted2 === persisted1
也就是说,对象已更改到位,没有创建新实例。因此,检查
persisted2.lastModifiedDate.isAfter(persisted1.lastModifiedDate)
永远无法工作。
-
对于
@数据JpaTest
,
lastModifiedDate
从不更新。也许这种测试并不是为了检查时间戳。即你甚至不能使用
def lastModifiedDate = persisted1.lastModifiedDate
在保存第二次及以后
persisted2.lastModifiedDate.isAfter(lastModifiedDate)
。它也失败了。
所以你真的应该使用
@SpringBootTest
,如果你想检查这样的时间戳。然而,您需要满足父子关系的参照完整性。如果有修改的选项
@数据JpaTest
为了行为也更新时间戳,我不知道。但这可能是JPA测试中被嘲笑的数据库功能。在春天更有经验的人也许可以回答这个问题。
使现代化
这样的东西应该对你有用:
package spring.jpa
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import spock.lang.Specification
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
class AuditingSpec extends Specification {
@Autowired
OneToManyRepository repo
def "New parent and child are both assigned IDs and dates"() {
given:
def parent = new OneToManyEntity()
parent.setChildren([createChild(parent)])
when:
def persisted = repo.save(parent)
then:
def persistedChild = persisted.children.first()
persisted.createdDate
persisted.createdDate == persisted.lastModifiedDate
persistedChild.createdDate
persistedChild.createdDate == persistedChild.lastModifiedDate
}
def "Appended child is assigned IDs and dates"() {
given:
def parent = new OneToManyEntity()
parent.setChildren([createChild(parent)])
def persisted = repo.save(parent)
persisted.children.add(createChild(parent))
when:
def persisted2 = repo.save(persisted)
then:
persisted2.children.size() == 2
def firstChild = persisted2.children.first()
def secondChild = persisted2.children.last()
secondChild.id > firstChild.id
secondChild.createdDate
secondChild.createdDate == secondChild.lastModifiedDate
}
def "LastModifiedDate value is updated"() {
given:
def persisted1 = repo.save(new OneToManyEntity())
//sleep(1000)
persisted1.setChildren([])
def persisted2 = repo.save(persisted1)
expect:
persisted2.lastModifiedDate.isAfter(persisted1.lastModifiedDate)
}
static ManyToOneEntity createChild(OneToManyEntity parent) {
def child = new ManyToOneEntity()
child.setParent(parent)
child
}
}