【问题标题】:Grails 3 Unit Testing: How do you do mockFor, createMock, and demands in Grails 3?Grails 3 单元测试:如何在 Grails 3 中进行 mockFor、createMock 和需求?
【发布时间】:2016-02-27 14:08:57
【问题描述】:

我正在将应用程序从 Grails 2.4.4 升级到 Grails 3.0.9,但我找不到任何有关如何在 Grails 3 中执行 mockFor、createMock 和需求的信息。

我曾经做过这样的事情:

fooService = mockFor(FooService)
controller.fooService = fooService.createMock()

fooService.demand.barMethod() { a,b ->
}

但看起来 'mockFor' 已经消失了,即使从文档中也是如此。执行此操作的 Grails 3 方法是什么?

更新:

我不想将使用 Grails 'mockFor' 样式编写的数千个测试重写为 Spock 交互样式,所以我想出了这个解决方案:

  • 用新的 MockFor() 替换 mockFor()
  • 将 createMock() 替换为 proxyInstance()
  • 将对 fooBean.fooService = fooService.proxyInstance() 的调用移至 需求之后

没有进一步的更改,这在 Grails 3 中“正常工作”。

【问题讨论】:

  • 答案将取决于您使用的测试框架,这在您的问题中没有说明。你在用斯波克吗? JUnit?还有什么?
  • 我一直在使用从 Grails 1.3.7(GrailsUnitTestCase JUnit 风格)到 Grails 2.4.4(规范 Spock 风格)的 mockFor+createMock+demand 模式。

标签: grails grails-3.0 grails-3.0.9


【解决方案1】:

我还从使用 mockFor 并使用 HypeMK 概述的类似方法的 grails 2 升级了许多测试:

  1. 为 groovy 的 MockFor 添加导入: import groovy.mock.interceptor.MockFor
  2. mockFor 重命名为new MockFor
  3. createMock() 重命名为proxyInstance()
  4. 删除对verify()的调用

【讨论】:

  • 答案在 Grails 3.2.4 中适用于 Junit 测试用例
【解决方案2】:

你可以默认使用Spock

@TestFor(MyController)
class MyControllerSpec extends Specification {

    void "test if mocking works"() {
        given:
        def fooService = Mock(FooService)
        fooService.barMethod(_, _) >> {a, b ->
            return a - b
        }

        when:
        def result = fooService.barMethod(5, 4)

        then:
        result == 1
    }
}

class FooService {
    int barMethod(int a, int b) {
        return a + b;
    }
}

【讨论】:

  • 这对我来说已经足够了,非常感谢。
  • 查看我提出的 Groovy 解决方案(在原帖中更新)。
  • 感谢您的提示,这可能会派上用场:)
猜你喜欢
  • 2010-11-15
  • 2018-10-29
  • 1970-01-01
  • 2016-06-06
  • 2023-03-28
  • 1970-01-01
  • 2016-05-29
  • 2017-02-07
  • 2019-11-17
相关资源
最近更新 更多