依赖服务中的Grails单元测试模拟方法

时间:2015-06-15 22:39:33

标签: grails mocking spock

我有一项使用其他服务的服务,例如:

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")
  }
}

但是我在这个测试中输入了一个错误,说明了log.warn语句的(0次调用)。

非常感谢有关此测试不正确的原因,以及我如何测试functionA()正确处理异常

1 个答案:

答案 0 :(得分: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() {
  }
}