Grails可能在数据库会话中的竞争条件?

时间:2014-02-09 17:11:38

标签: unit-testing grails testing

我正在学习grails并阅读Grails In Action书。尝试从中执行一些测试,但对我来说有一些奇怪的行为。我有下一个简单的集成测试:

@Test
public void testProjections() throws Exception {
    User user1 = new User(mail: 'test1@test.tld', password: 'password1').save(flush: true)
    User user2 = new User(mail: 'test2@test.tld', 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。

我做错了什么以及它为什么有效 有时候

1 个答案:

答案 0 :(得分:0)

我想说问题的根源在于这一行:

user1.addToPosts(new Post(content: 'First').addToTags(new Tag(name: 'tag-0')))

在父实例上调用save()之前,这些动态addTo *方法不会传播保存到关联的实例。所以在之后调用user1上的save()应该修复它:

user1.addToPosts(new Post(content: 'First').addToTags(new Tag(name: 'tag-0')))
user1.save()

这应首先将save()传播到Post实例,然后传递给Tag实例。