2015-06-15 141 views
0

我有一個使用其他服務的服務,像這樣:Grails的單元測試嘲諷方法

class ServiceA implements IFaceClass { 
    ServiceB bServ 
    @Override 
    void functionA(Map map) { 
    try { 
     bServ.functionB() // this throws an exception on error 
    } catch (Exception e) { 
     log.warn("Exception occured: " + e.message) 
    } 
    } 
} 

現在我試圖寫一個單元測試,檢查該異常是從bServ.functionB()提出和處理由functionA()通過嘲笑以下規範的功能。

class ServiceASpec extends Specification { 
    ServiceB bServ 
    def setup() { 
    bServ = Mock(ServiceB) 
    service.bServ = bServ 
    } 

    def "test exception raised by functionB is handled"() { 
    given: 
     bServ.functionB() >> { 
     throw new Exception("some exception message") 
     } 
    when: 
     service.functionA() 
    then: 
     1 * log.warn("Exception occured: some exception message") 
    } 
} 

但是,我得到一個錯誤,說這個測試說(0 invocations)的log.warn語句。

希望得到任何見解,爲什麼這個測試是不正確的,我怎麼能測試該異常正被functionA()

+0

'泛函( )'需要服務類中的Map參數。該測試不會以Map爲參數調用'functionA()'。 – dmahapatro

+0

如果您發現我的答案有用,請接受並註銷它。 – Opal

回答

0

在這裏你可以找到樣品的工作測試正確處理:

@Grab('org.spockframework:spock-core:0.7-groovy-2.0') 
@Grab('cglib:cglib-nodep:3.1') 
@Grab('org.slf4j:slf4j-api:1.7.12') 

import spock.lang.* 
import org.slf4j.Logger 

class ServiceASpec extends Specification { 

    def "test exception raised by functionB is handled"() { 
    given: 
     ServiceB serviceB = GroovyMock() 
     serviceB.functionB() >> { throw new Exception("some exception message") } 

    and: 
     ServiceA serviceA = new ServiceA() 
     serviceA.serviceB = serviceB 
     serviceA.log = Mock(Logger) 

    when: 
     serviceA.functionA([:]) 

    then: 
     1 * serviceA.log.warn("Exception occured: some exception message") 
    } 
} 

class ServiceA { 

    ServiceB serviceB 
    Logger log 

    void functionA(Map map) { 
    try { 
     serviceB.functionB() 
    } catch (Exception e) { 
     log.warn("Exception occured: " + e.message) 
    } 
    } 
} 

class ServiceB { 
    void functionB() { 
    } 
}