Grails单元测试通过引用并不适用于模拟

时间:2016-11-06 20:45:31

标签: unit-testing grails mocking spock

我有一个单元测试,我嘲笑服务类来保存域。最初,我的控制器方法看起来像这样:

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)

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

1 个答案:

答案 0 :(得分:1)

  

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

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