简体   繁体   中英

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. if i Mock(SessionFactory), code like:

    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

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 :

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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