【问题标题】:Mock testing in Grails 2.0 errorsGrails 2.0 错误中的模拟测试
【发布时间】:2012-09-06 13:53:42
【问题描述】:

我最近将一个 Grails 1.3.7 项目升级到 Grails 2.0.4,并注意到我的许多模拟单元测试开始失败。控制器测试似乎顺利通过,当您让服务相互协作并尝试模拟对协作者的调用时,问题就出现了。奇怪的是,如果我运行单个测试,它会通过,但是一旦我运行整个套件,它们就会失败并给出错误:

No more calls to 'getName' expected at this point. End of demands.
junit.framework.AssertionFailedError: No more calls to 'getName' expected at this point. End of demands.

我什至尝试过使用 GMock 而不是 new MockFor(),但得到这个非常相似的错误:

No more calls to 'getSimpleName' expected at this point. End of demands.
junit.framework.AssertionFailedError: No more calls to 'getSimpleName' expected at this point. End of demands.

这是一个人为的示例,展示了如何复制我遇到的错误,以及 GitHub 上 https://github.com/punkisdead/FunWithMocks 上的整个示例项目。关于如何完成这项工作的任何想法?

栏控制器:

package funwithmocks

class BarController {

  def barService
  def fooService

  def index() { }
}

酒吧服务:

package funwithmocks

class BarService {

  def fooService
  def bazService

  def serviceMethod() {

  }
}

BarControllerTests:

package funwithmocks

import grails.test.mixin.*
import org.junit.*
import groovy.mock.interceptor.MockFor

/**
 * See the API for {@link grails.test.mixin.web.ControllerUnitTestMixin} for usage instructions
 */
@TestFor(BarController)
class BarControllerTests {

  def fooService
  def barService

  @Before
  public void setUp() {
    fooService = new MockFor(FooService)
    fooService.use {
      controller.fooService = new FooService()
    }

    barService = new MockFor(BarService)
    barService.use {
      controller.barService = new BarService()
    }
  }

  @Test
  void doSomething() {
    controller.index()
  }
}

BarServiceTests: 包 funwithmocks

import grails.test.mixin.*
import org.junit.*
import groovy.mock.interceptor.MockFor

/**
 * See the API for {@link grails.test.mixin.services.ServiceUnitTestMixin} for usage instructions
 */
@TestFor(BarService)
class BarServiceTests {

  def fooService
  def bazService

  @Before
  public void setUp() {
    fooService = new MockFor(FooService)
    fooService.use {
      service.fooService = new FooService()
    }

    bazService = new MockFor(BazService)
    bazService.use {
      service.bazService = new BazService()
    }
  }

  @Test
  void callSomeService() {
    service.serviceMethod()
  }
}

【问题讨论】:

    标签: grails mocking gmock


    【解决方案1】:

    您不应该将新的测试 mixin 与 MockFor groovy 类结合使用。将所有MockFor 实例替换为mockFor 方法。

    http://grails.org/doc/latest/guide/testing.html#mockingCollaborators

    【讨论】:

    • 谢谢。我不确定为什么他们没有在文档中更清楚地说明这一点,但这确实起到了作用。看起来很奇怪,它会那样破裂。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-11
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多