简体   繁体   English

使用sessionFactory进行Grails / Spock单元测试

[英]Grails/Spock Unit testing with sessionFactory

@Transactional
class service {
    def sessionFactory 

    def doSomething(buildings) {
        buildings.each {
            def building ->
                building.owner = 'John'
                building.save(failOnError:true)
        }

        def session = sessionFactory.getCurrentSession()
        checkNotNull(session)
        session.flush()
    }
}

This code make all the building owners to 'John' or none 此代码使所有建筑物的所有者都变成“约翰”,或者一无所有

but the in the Unit testing code, i cannot use @Mock(SessionFactory), because it is not in the grails env. 但是在单元测试代码中,我不能使用@Mock(SessionFactory),因为它不在grails env中。 if i Mock(SessionFactory), code like: 如果我模拟(SessionFactory),则代码如下:

    given:
    service.sessionFactory = Mock(SessionFactory)
    Session session = Mock(Session)
    service.sessionFactory.getCurrentSession() >> session

    Building building = new Building(communityId: 199).save(flush: true, failOnError: true)

    when:
    service.doSomething(Lists.newArrayList(building)
    building = Building.findById(building.id)

    then:
    building.owner == 'John'

However the building.owner is NULL, i think the session flush should not mock 但是building.owner为NULL,我认为会话刷新不应该模拟

So, what should i do? 所以我该怎么做? thx in advance 提前

Since you are actually storing the values in database and testing the result, you should do integration test. 由于您实际上是将值存储在数据库中并测试结果,因此应该进行集成测试。 You can do that by extending the IntegrationSpec or using the @TestMixin(IntegrationTestMixin) if you just want to extends from Specification : 如果您只想从Specification扩展,则可以通过扩展IntegrationSpec或使用@TestMixin(IntegrationTestMixin)来实现:

class ServiceSpec extends IntegrationSpec {

    def "service test"() {
        given:
        Building building = new Building(communityId: 199).save(flush: true, failOnError: true)

        when:
        service.doSomething([building])
        building = Building.findById(building.id)

        then:
        building.owner == 'John'        
    }
}

Just make sure that you are defining the "test" environment correctly in your DataSource.groovy. 只要确保您在DataSource.groovy中正确定义了“测试”环境即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM