【问题标题】:Grails Unit Testing Pass By Reference Doesn't Work When MockingGrails 单元测试通过引用传递在模拟时不起作用
【发布时间】:2016-11-07 04:56:18
【问题描述】:

我有一个单元测试,我在其中模拟一个服务类来保存域。最初,我的控制器方法如下所示:

def save(Long organizationId, Convention convention) {
  conventionService.save(organizationId, convention)

  if (convention.hasErrors()) {
    response.status = HttpStatus.UNPROCESSABLE_ENTITY.value()
    respond convention.errors
  } else {
    response.status = HttpStatus.CREATED.value()
    respond convention
  }
}

通常,这是可行的,因为 Java 是通过引用传递的,因此传递给 save 方法的 convention 在整个方法中都是相同的 convention 对象。但是,在模拟 conventionService.save 方法时,按引用传递不起作用。调整我的方法来解决这个问题:

def save(Long organizationId, Convention convention) {
  convention = conventionService.save(organizationId, convention)

  if (convention.hasErrors()) {
    response.status = HttpStatus.UNPROCESSABLE_ENTITY.value()
    respond convention.errors
  } else {
    response.status = HttpStatus.CREATED.value()
    respond convention
  }
}

允许我的测试通过,因为 convention 对象是我对我的模拟的期望:

1 * service.save(1, _) >> new Convention(
       id: 1,
       name: 'Con 1',
       description: 'This is a pretty cool convention, everyone should go',
       startDate: new Date(),
       endDate: new Date()+10,
       organization: organization)

我的问题是,这是我应该报告的预期行为还是错误?

【问题讨论】:

    标签: unit-testing grails mocking spock


    【解决方案1】:

    我的问题是,这是预期的行为还是我应该的错误 举报?

    这是预期的行为。这不是您应该报告的错误。

    【讨论】:

    • 谢谢杰夫。我假设了很多,但想确定一下。我将不得不在几周内解释这一点。
    • “我将不得不在几周内解释这一点。” - 你知道怎么做吗?
    • 我相信是的。我理解它在一般模拟方面的基本逻辑。我只是想确定没有任何 Spock 或 Groovy/Grails 魔法会操纵我的期望。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-11
    • 1970-01-01
    • 2012-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多