2014-10-08 94 views
0
@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() 
    } 
} 

該代碼使所有的樓宇業主「約翰」或無的Grails /斯波克單元測試與SessionFactory的

但在單元測試代碼,我不能使用@Mock(SessionFactory的),因爲它是不在grails env。如果我莫克(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' 

然而building.owner爲NULL,我覺得會沖洗不應該嘲笑

所以,我應該怎麼辦? thx

回答

0

由於您實際將值存儲在數據庫中並測試結果,因此應該執行集成測試。你可以做到這一點通過擴展IntegrationSpec或使用@TestMixin(IntegrationTestMixin)如果你只是想從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'   
    } 
} 

只要確保你在你的正確DataSource.groovy中定義的「測試」環境。