我在学Grails并阅读Grails In Action书。尝试从它执行一些测试,但对我来说却有奇怪的行为。我有下一个简单的集成测试:数据库会话中Grails可能的竞争状态?
@Test
public void testProjections() throws Exception {
User user1 = new User(mail: '[email protected]', password: 'password1').save(flush: true)
User user2 = new User(mail: '[email protected]', password: 'password2').save(flush: true)
assertNotNull(user1)
assertNotNull(user2)
// Chain add Tag to Post
user1.addToPosts(new Post(content: 'First').addToTags(new Tag(name: 'tag-0')))
// Separate add tag to post
Post post = user1.posts.iterator().next()
Tag tag1 = new Tag(name: 'tag-1')
post.addToTags(tag1)
// http://stackoverflow.com/questions/6288991/do-i-ever-need-to-explicitly-flush-gorm-save-calls-in-grails
// Have tried with and without next line without success:
//sessionFactory.getCurrentSession().flush()
assertEquals(['tag-0', 'tag-1'], user1.posts.iterator().next().tags*.name.sort()) // line 154
…
}
然后我运行它连续两次:
grails>
grails> test-app -rerun -integration
| Running 5 integration tests... 2 of 5
| Failure: testProjections(com.tariffus.QueryIntegrationTests)
| java.lang.AssertionError: expected:<[tag-0, tag-1]> but was:<[tag-1]>
at org.junit.Assert.fail(Assert.java:88)
at org.junit.Assert.failNotEquals(Assert.java:743)
at org.junit.Assert.assertEquals(Assert.java:118)
at org.junit.Assert.assertEquals(Assert.java:144)
at com.tariffus.QueryIntegrationTests.testProjections(QueryIntegrationTests.groovy:154)
| Completed 5 integration tests, 1 failed in 0m 0s
| Tests FAILED - view reports in /home/pasha/Projects/grails/com.tariffus/target/test-reports
grails>
grails> test-app -rerun -integration
| Running 5 integration tests... 2 of 5
| Failure: testProjections(com.tariffus.QueryIntegrationTests)
| java.lang.AssertionError: expected:<[3, 1, 2]> but was:<[[tag-1, tag-2, tag-0, tag-5, tag-3, tag-4], [tag-6]]>
at org.junit.Assert.fail(Assert.java:88)
at org.junit.Assert.failNotEquals(Assert.java:743)
at org.junit.Assert.assertEquals(Assert.java:118)
at org.junit.Assert.assertEquals(Assert.java:144)
at com.tariffus.QueryIntegrationTests.testProjections(QueryIntegrationTests.groovy:164)
| Completed 5 integration tests, 1 failed in 0m 0s
| Tests FAILED - view reports in /home/pasha/Projects/grails/com.tariffus/target/test-reports
grails>
正如你所看到的第一个失败的行157和第二刚过,在第二无需任何修改也是拼命地跑进一步。
我在模式dbCreate ='update'中使用Postgres数据库和环境测试配置的dataSource。
我做了什么不正确以及它为什么起作用有时?
尝试向'user1.addToPosts(...)'和'post.addToTags(tag1)' – nickdos
添加'.save(flush:true)'它实际上解决了这个问题。但为什么它需要? sessionFactory.getCurrentSession()。flush()不应该在全局上做同样的技巧吗? – Hubbitus
我赶紧说。这不利于我们。 – Hubbitus