我在學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