6

Anyone used this annotation in grails unit tests? Didnt seem to work for me. Thanks. D

Update: the last line of my test below does throw the expected exception. However the test fails (Stack trace too big for here...). I'm using grails 1.2 and running the test in eclipse's junit runner. Maybe grails is using an earlier version of junit than 4?

/**
 * 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")
}
Derek
  • 760
  • 2
  • 11
  • 20

1 Answers1

17

Only JUnit 3 is currently supported, so use shouldFail() instead:

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() is actually more convenient since you can use it more than once per test, and it returns the exception message so you can assert based on the message as well as the exception.

Rob Hruska
  • 118,520
  • 32
  • 167
  • 192
Burt Beckwith
  • 75,342
  • 5
  • 143
  • 156
  • is this still applicable as of 1.3.7 ? – dbrin Mar 24 '12 at 04:05
  • 1
    As of 2.0 you can use JUnit 4, but as I said I'd still use shouldFail since it's so flexible. – Burt Beckwith Mar 24 '12 at 04:51
  • Not to troll this question, but I found the answer helpful with a small change. In my opinion, you should only wrap the code under test in the shouldFail(){} block. Because if any of the buildup for the test fails, this test will be green and give you a false positive. – ekawas Aug 27 '14 at 18:19