6

有人在 grails 单元测试中使用过这个注解吗?似乎对我不起作用。谢谢。D

更新:我下面测试的最后一行确实抛出了预期的异常。但是测试失败(堆栈跟踪对于这里来说太大了......)。我正在使用 grails 1.2 并在 eclipse 的 junit runner 中运行测试。也许 grails 使用的是比 4 更早的 junit 版本?

/**
 * Get the EC by a manager of a different company. Should throw exception
 */
@ExpectedException(ServiceAuthorizationException.class)
void testGetEcByNonOwnerManagerOfDifferentCompany() {
    mockDomain(ExpenseClaim , [new ExpenseClaim(id:"1",narrative:"marksClaim", employee:userMark, company:dereksCompany)])      

    def authControl = mockFor(AuthenticateService)
    authControl.demand.userDomain(1..1)  {-> otherUserMgr }
    authControl.demand.ifAllGranted(1..1)  {String arg1 -> return "ROLE_COMPANYMANAGER".equals(arg1) } //returns true
    def testService = new ExpenseClaimService()
    testService.authenticateService = authControl.createMock()
    def thrown = false
    testService.getExpenseClaim("1")
}
4

1 回答 1

17

当前仅支持 JUnit 3,因此请shouldFail()改用:

void testGetEcByNonOwnerManagerOfDifferentCompany() {

  shouldFail(ServiceAuthorizationException) {
    mockDomain(ExpenseClaim , [new ExpenseClaim(id:"1",
                               narrative:"marksClaim", employee:userMark,
                               company:dereksCompany)])      

    def authControl = mockFor(AuthenticateService)
    authControl.demand.userDomain(1..1)  {-> otherUserMgr }
    authControl.demand.ifAllGranted(1..1)  {String arg1 ->
       "ROLE_COMPANYMANAGER".equals(arg1) } //returns true
    def testService = new ExpenseClaimService()
    testService.authenticateService = authControl.createMock()
    testService.getExpenseClaim("1")
  }
}

shouldFail()实际上更方便,因为您可以在每个测试中多次使用它,并且它会返回异常消息,因此您可以根据消息和异常进行断言。

于 2009-12-30T23:38:04.550 回答