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

标签 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)
    }
  }
}

现在,我正在尝试编写一个单元测试,通过使用以下Spec对该函数进行模拟,以检查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()是否正确处理异常的任何见解

最佳答案

在这里您可以找到示例工作测试:

@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() {
  }
}

关于grails - 依赖服务中的Grails单元测试模拟方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30856131/

相关文章:

sql - to_char函数在Hibernate中引发异常

grails - 将应用程序从 Grails 2.2.5 升级到 3.0

php - 带有回调参数的模拟方法

class - Jest 用 typescript 模拟一个类(class)

ruby-on-rails - mock、stub 和 factory girl 有什么区别?

unit-testing - 从 2.2.4 升级到 Grails 2.4.3 后,在单元测试期间,元类更改不会在测试之间重置

testing - 学习 GEB 和 Spock

grails - 有没有办法在Grails Web框架中生成子进程?

grails - 如何动态检测生产中的grails Assets 更新?

java - Spock stub 在功能方法中不起作用