2014-04-29 8 views
1

Grails에서 새로운 기능을 제공하지만 일부 테스트를 수행하고 있지만 beforeUpdate 및 beforeInsert가 개발 중에 호출되었지만 테스트 결과에 따르면 실제로 수행하지 않습니다. 잘못된?beforeUpdate 또는 beforeInsert가 Grails에서 Spock을 사용하여 테스트 됨

저는 Cicle과 Measurement를 조롱하고 있습니다. 그래서 save 메소드가 호출 될 때 beforeUpdate 나 beforeInsert가 트리거 될 것이라고 생각합니다. 그러나 테스트를 실행할 때 grails 응답이 "너무 적은 호출 : 1 * cicle.updateCicleValue() 호출 (호출 0) "

"when "을 잘못 사용하고 있습니까? 또는 save가 beforeMatch 객체의 beforeUpdate와 beforeInsert를 트리거하지 않습니까?

:

Cicle.goovy

class Cicle { 

String machine 
double cicleValue 

static hasMany = [measurements:Measurement] 

def beforeInsert(){ 
    if (measurements != null) updateCicleValue() 
} 

def beforeUpdate(){ 
    if (measurements != null) updateCicleValue() 
} 

public void updateCicleValue(){ 

    double sumCicleValue = 0 

    measurements.each{ measurement -> 
     sumCicleValue += measurement.cicleValue 
    } 

    cicleValue = sumCicleValue/measurements.size() 
} 
} 

CicleSepc.groovy

@TestFor(Cicle) 
@Mock([Cicle, Measurement]) 
class CicleSpec extends Specification { 

Measurement mea1  
Measurement mea2  
Cicle cicle 


def setup() { 
    mea1 = new Measurement(machine: "2-12", cicleValue: 34600)  
    mea2 = new Measurement(machine: "2-12", cicleValue: 17280)  
    cicle = new Cicle(machine: "2-12") 

    cicle.addToMeasurements(mea1) 
    cicle.addToMeasurements(mea2)  
} 

def cleanup() { 
} 

void "Test updateCicleValue is triggered"(){ 

    when: "Saving..." 
    cicle.save(flush:true) 

    then: "updateCicleValue is called once" 
    1 * cicle.updateCicleValue() 
} 
} 

감사를 도와주세요! 위의 간단한 테스트는 (간결하게 언급) withNewSesion를 지정하지 않고 통과 할 것이지만

+6

장치 사양은 이벤트 후크를 테스트하기에 좋지 않습니다. 통합 사양을 사용해보십시오. – dmahapatro

+0

왜 그렇지 않습니까? 이것이 작동하지 않는 이유입니까? 어떻게 그것의 단위 스펙을 말할 수 있습니까? –

+0

예. 작동하지 않는 이유입니다. 단위 테스트 환경은 완전한 영구 환경을 빼앗기므로 이러한 이벤트는 통합 또는 기능 테스트 환경에서 테스트해야합니다. – dmahapatro

답변

4
//Integration Spec 
import grails.test.spock.IntegrationSpec 

class AuthorIntSpec extends IntegrationSpec { 

    void "test something"() { 
     given: 
      def author 

     when: 
      Author.withNewSession { 
       author = new Author(name: 'blah').save(flush: true) 
      } 

     then: 
      author.name == 'foo' 
    } 
} 

//Author 
class Author { 
    String name 

    def beforeInsert() { 
     this.name = 'foo' 
    } 
} 

또한 당신이 어떤 엔티티를 지속 끝날 경우 이벤트에 withNewSession를 사용하는주의. 사용 사례에

는 상호 작용을 테스트하는 것이 가능 AFAIK하지 그래서 반군 조롱이없는,하지만 당신은 circleValue의 값이 차례로 테스트에서 beforeInsert 이벤트가 적절하게 해고되는 것을 삽입 (높이), 후 업데이트했다고 주장 할 수 .